public void TestInitialize() { InitializeTestData(); // マスタテーブルデータを作成する DbTestHelper.ExecSqlFromFilePath(@"TestData\MakeMasterTableData.sql"); }
public static void ClassInit(TestContext context) { // 関連DBデータを全削除 DbTestHelper.DeleteAllReseed(); // マスタテーブルデータを作成する DbTestHelper.ExecSqlFromFilePath(@"TestData\MakeMasterTableData.sql"); }
/// <summary> /// 共通の事前設定項目 /// </summary> /// <param name="timeProviderUtcNow">DIするTimeProviderのUtcNowで返却させる日時</param> /// <param name="in_InvalidDbConnectionString">投入するAppSettingsが正常値かどうか</param> /// <param name="in_InvalidBlobConnectionString">Blob接続文字列を不正地で設定するかどうか</param> /// <param name="in_ServiceException">Serviceで強制的に例外を発生させるかどうか</param> /// <param name="in_DeliveringBlobContainerNameInstallbase">AppSettingsに登録するDeliveringBlobのコンテナ名</param> /// <param name="in_DeliveringBlobInstallbaseFilePath">AppSettingsに登録するDeliveringBlobのファイルパス</param> /// <param name="in_InsertNewDataSqlPath">挿入するデータのSQLファイルパス</param> /// <param name="in_InitialBlobFilePath">事前にBlobにアップロードしておくファイルのパス</param> /// <param name="configContents">事前アップロードしたBlobファイル内容</param> /// <returns></returns> private bool CommonPreset( DateTime timeProviderUtcNow, string in_InvalidDbConnectionString, string in_InvalidBlobConnectionString, string in_ServiceException, string in_DeliveringBlobContainerNameInstallbase, string in_DeliveringBlobInstallbaseFilePath, string in_InsertNewDataSqlPath, string in_InitialBlobFilePath, out string configContents) { Dictionary <string, string> dic = new Dictionary <string, string>(); if (bool.TryParse(in_InvalidDbConnectionString, out bool isDbSettingsInvalid) && isDbSettingsInvalid) { // DB接続文字列が不正なAppSettingsとする dic.Add("ConnectionStrings:PrimaryDbConnectionString", null); } if (bool.TryParse(in_InvalidBlobConnectionString, out bool isBlobSettingsInvalid) && isBlobSettingsInvalid) { // Blob接続文字列が不正なAppSettingsとする dic.Add("ConnectionStrings:DeliveringBlobConnectionString", "BlobEndpoint=https://rmscoemujpedeliver01.blob.core.windows.net/;QueueEndpoint=https://rmscoemujpedeliver01.queue.core.windows.net/;FileEndpoint=https://rmscoemujpedeliver01.file.core.windows.net/;TableEndpoint=https://rmscoemujpedeliver01.table.core.windows.net/;SharedAccessSignature=sv=2019-02-02&ss=bfqt&srt=sco&sp=rwdlacup&se=9999-12-31T14:59:59Z&st=2019-12-31T15:00:00Z&spr=https&sig=hogehogehogehogehogehogehogehogehogehogehogehoge"); } // Blobのコンテナ名・ファイルパスの設定 dic.Add("DeliveringBlobContainerNameInstallbase", in_DeliveringBlobContainerNameInstallbase); dic.Add("DeliveringBlobInstallbaseFilePath", in_DeliveringBlobInstallbaseFilePath); // DI実施 DependencyInjection(timeProviderUtcNow, dic, (bool.TryParse(in_ServiceException, out bool isServiceException) && isServiceException)); // 初期データ挿入 DbTestHelper.ExecSqlFromFilePath(in_InsertNewDataSqlPath); // アップロード予定の場所にあるBlobを削除する TryDeleteBlob(_initialBlobContainerName, _initialBlobFilePath); // 初期Blobを入れる場合はアップロードする configContents = string.Empty; bool didUploadInitialBlob = false; if (!string.IsNullOrEmpty(in_InitialBlobFilePath) && File.Exists(in_InitialBlobFilePath)) { configContents = File.ReadAllText(in_InitialBlobFilePath); // テストでは固定のコンテナ名・ファイルパスで設定する TryUploadBlob(_initialBlobContainerName, _initialBlobFilePath, configContents); didUploadInitialBlob = true; } // WebAPIでアップロードする先のコンテナを作成する _ = TryCreateContainer(in_DeliveringBlobContainerNameInstallbase); return(didUploadInitialBlob); }
public static void ClassInit(TestContext context) { // 関連DBデータを全削除 DbTestHelper.DeleteAllReseed(); // マスタテーブルデータを作成する DbTestHelper.ExecSqlFromFilePath(@"TestData\MakeMasterTableData.sql"); // 配信グループに関連する配信ファイル・端末データを作成する DbTestHelper.ExecSqlFromFilePath(@"TestData\MakeDeviceAndDeliveryFileData.sql"); }
public void TestCleanup() { // 配信グループ・配信結果・適用結果テーブルのデータを削除して次回作成時のSIDを1にする DbTestHelper.ExecSqlFromFilePath(@"TestData\ReseedDeliveryGroupChildren.sql"); }
public void DeleteDeliveryGroupTest( string no, string in_InsertNewDataSqlPath, string in_DeleteNewDataSqlPath, string in_SidFormat, string in_RowVersionFormat, string in_AppSettingsInvalid, string in_ServiceException, string expected_DataJsonPath, string expected_LogMessagesPath, string expected_DtDeliveryGroup_TableDataPath, string expected_DtDeliveryResult_TableDataPath, string expected_DtInstallResult_TableDataPath, string remarks) { Dictionary <string, string> dir = null; if (bool.TryParse(in_AppSettingsInvalid, out bool isAppSettingsInvalid) && isAppSettingsInvalid) { // DB接続文字列が不正なAppSettingsとする dir = new Dictionary <string, string>() { { "ConnectionStrings:PrimaryDbConnectionString", "TestConnectionString" } }; } // DI実施 DependencyInjection(DateTime.Parse("2020/04/01 09:00:00.0000000"), dir, (bool.TryParse(in_ServiceException, out bool isServiceException) && isServiceException)); // 初期データ挿入 DbTestHelper.ExecSqlFromFilePath(in_InsertNewDataSqlPath); // SID, RowVersionの取得 DataTable inputDataTable = DbTestHelper.SelectTable("SELECT SID, ROW_VERSION FROM core.DT_DELIVERY_GROUP"); long sid = 1; long rowVersion = 0; if (inputDataTable.Rows.Count > 0) { sid = (long)inputDataTable.Rows[0].ItemArray[0]; rowVersion = WebApiHelper.ConvertByteArrayToLong((byte[])inputDataTable.Rows[0].ItemArray[1]); } // 投入値の設定 var inputSid = long.Parse(string.Format(in_SidFormat, sid)); var inputRowVersion = long.Parse(string.Format(in_RowVersionFormat, rowVersion)); // ログ格納用ロガーの用意 var actualLogs = new List <TestLog>(); var logger = new TestLogger <DeliveryGroupsController>(actualLogs); // WebApi実行 var postResult = _controller.DeleteDeliveryGroup(null, inputSid, inputRowVersion, logger); // データのjson化 string resultJson = Rms.Server.Core.Utility.ObjectExtensions.ToStringJsonIndented(postResult); string expectJson = null; if (File.Exists(expected_DataJsonPath)) { expectJson = File.ReadAllText(expected_DataJsonPath); } // データの比較 Assert.AreEqual(expectJson, resultJson); // 期待するログ、実際のログを取得 List <string> expectedLogMessages = (!string.IsNullOrEmpty(expected_LogMessagesPath) && File.Exists(expected_LogMessagesPath)) ? File.ReadLines(expected_LogMessagesPath).ToList() : new List <string>(); List <string> actualControllerLogMessages = actualLogs.Select(x => x.GetSimpleText()).ToList(); List <string> actualServiceLogMessages = _serviceLogs.Select(x => x.GetSimpleText()).ToList(); // ControllerかServiceで期待するログが出力されたか確認 foreach (var expectedLogMessage in expectedLogMessages) { var matchingElementController = actualControllerLogMessages.FirstOrDefault(actual => actual.Contains(expectedLogMessage)); var matchingElementService = actualServiceLogMessages.FirstOrDefault(actual => actual.Contains(expectedLogMessage)); Assert.IsTrue((matchingElementController != null || matchingElementService != null), string.Format("「{0}」に一致する要素が見つかりません", expectedLogMessage)); actualControllerLogMessages.Remove(matchingElementController); actualControllerLogMessages.Remove(matchingElementService); } // テーブルデータの実際の値・期待値を取得 DataTable deliveryGroupActualTable = DbTestHelper.SelectTable( @"SELECT SID, DELIVERY_FILE_SID, DELIVERY_GROUP_STATUS_SID, NAME, START_DATETIME, DOWNLOAD_DELAY_TIME, CREATE_DATETIME, UPDATE_DATETIME FROM core.DT_DELIVERY_GROUP"); DataTable deliveryResultActualTable = DbTestHelper.SelectTable("SELECT * FROM core.DT_DELIVERY_RESULT"); DataTable installResultActualTable = DbTestHelper.SelectTable("SELECT * FROM core.DT_INSTALL_RESULT"); DataTable deliveryGroupExpectedTable = DbTestHelper.SelectCsv(expected_DtDeliveryGroup_TableDataPath, @"SELECT SID, DELIVERY_FILE_SID, DELIVERY_GROUP_STATUS_SID, NAME, START_DATETIME, DOWNLOAD_DELAY_TIME, CREATE_DATETIME, UPDATE_DATETIME FROM core.DT_DELIVERY_GROUP"); DataTable deliveryResultExpectedTable = DbTestHelper.SelectCsv(expected_DtDeliveryResult_TableDataPath, "SELECT * FROM core.DT_DELIVERY_RESULT"); DataTable installResultExpectedTable = DbTestHelper.SelectCsv(expected_DtInstallResult_TableDataPath, "SELECT * FROM core.DT_INSTALL_RESULT"); // テーブルデータの比較 CheckDataTableEquals(deliveryGroupExpectedTable, deliveryGroupActualTable); CheckDataTableEquals(deliveryResultExpectedTable, deliveryResultActualTable); CheckDataTableEquals(installResultExpectedTable, installResultActualTable); // 後処理 DbTestHelper.ExecSqlFromFilePath(in_DeleteNewDataSqlPath); }
public void PostDeliveryGroupTest( string no, string in_InsertNewDataSqlPath, string in_DeleteNewDataSqlPath, string in_InputJsonDataPath, string in_AppSettingsInvalid, string in_ServiceException, string expected_DataJsonPath, string expected_LogMessagesPath, string expected_DtDeliveryGroup_TableDataPath, string expected_DtDeliveryResult_TableDataPath, string expected_DtInstallResult_TableDataPath, string remarks) { Dictionary <string, string> dir = null; if (bool.TryParse(in_AppSettingsInvalid, out bool isAppSettingsInvalid) && isAppSettingsInvalid) { // DB接続文字列が不正なAppSettingsとする dir = new Dictionary <string, string>() { { "ConnectionStrings:PrimaryDbConnectionString", "TestConnectionString" } }; } // DI実施 DependencyInjection(DateTime.Parse("2020/04/01 09:00:00.0000000"), dir, (bool.TryParse(in_ServiceException, out bool isServiceException) && isServiceException)); // 初期データ挿入 DbTestHelper.ExecSqlFromFilePath(in_InsertNewDataSqlPath); // 投入JSONをDTOに変換する string inputDtoJson = (!string.IsNullOrEmpty(in_InputJsonDataPath) && File.Exists(in_InputJsonDataPath)) ? File.ReadAllText(in_InputJsonDataPath) : ""; // DTO変換できない場合は初期値とする(Azure Functionsと同様の挙動) DeliveryGroupAddRequestDto inputDto = null; try { inputDto = JsonConvert.DeserializeObject <DeliveryGroupAddRequestDto>(inputDtoJson); } catch (Exception) { inputDto = new DeliveryGroupAddRequestDto(); } // ログ格納用ロガーの用意 var actualLogs = new List <TestLog>(); var logger = new TestLogger <DeliveryGroupsController>(actualLogs); // WebApi実行 var postResult = _controller.PostDeliveryGroup(inputDto, logger); if (postResult is OkObjectResult) { // 結果が流動的になる値は比較できないので固定値を入れる var okDto = ((postResult as OkObjectResult).Value as DeliveryGroupResponseDto); Assert.IsNotNull(okDto); okDto.RowVersion = 0; } // データのjson化 string resultJson = Rms.Server.Core.Utility.ObjectExtensions.ToStringJsonIndented(postResult); string expectJson = null; if (File.Exists(expected_DataJsonPath)) { expectJson = File.ReadAllText(expected_DataJsonPath); } // データの比較 Assert.AreEqual(expectJson, resultJson); // 期待するログ、実際のログを取得 List <string> expectedLogMessages = (!string.IsNullOrEmpty(expected_LogMessagesPath) && File.Exists(expected_LogMessagesPath)) ? File.ReadLines(expected_LogMessagesPath).ToList() : new List <string>(); List <string> actualControllerLogMessages = actualLogs.Select(x => x.GetSimpleText()).ToList(); List <string> actualServiceLogMessages = _serviceLogs.Select(x => x.GetSimpleText()).ToList(); // ControllerかServiceで期待するログが出力されたか確認 foreach (var expectedLogMessage in expectedLogMessages) { var matchingElementController = actualControllerLogMessages.FirstOrDefault(actual => actual.Contains(expectedLogMessage)); var matchingElementService = actualServiceLogMessages.FirstOrDefault(actual => actual.Contains(expectedLogMessage)); Assert.IsTrue((matchingElementController != null || matchingElementService != null), string.Format("「{0}」に一致する要素が見つかりません", expectedLogMessage)); actualControllerLogMessages.Remove(matchingElementController); actualControllerLogMessages.Remove(matchingElementService); } // テーブルデータの実際の値・期待値を取得 DataTable deliveryGroupActualTable = DbTestHelper.SelectTable( @"SELECT SID, DELIVERY_FILE_SID, DELIVERY_GROUP_STATUS_SID, NAME, START_DATETIME, DOWNLOAD_DELAY_TIME, CREATE_DATETIME, UPDATE_DATETIME FROM core.DT_DELIVERY_GROUP"); DataTable deliveryResultActualTable = DbTestHelper.SelectTable("SELECT * FROM core.DT_DELIVERY_RESULT"); DataTable installResultActualTable = DbTestHelper.SelectTable("SELECT * FROM core.DT_INSTALL_RESULT"); DataTable deliveryGroupExpectedTable = DbTestHelper.SelectCsv(expected_DtDeliveryGroup_TableDataPath, @"SELECT SID, DELIVERY_FILE_SID, DELIVERY_GROUP_STATUS_SID, NAME, START_DATETIME, DOWNLOAD_DELAY_TIME, CREATE_DATETIME, UPDATE_DATETIME FROM core.DT_DELIVERY_GROUP"); DataTable deliveryResultExpectedTable = DbTestHelper.SelectCsv(expected_DtDeliveryResult_TableDataPath, "SELECT * FROM core.DT_DELIVERY_RESULT"); DataTable installResultExpectedTable = DbTestHelper.SelectCsv(expected_DtInstallResult_TableDataPath, "SELECT * FROM core.DT_INSTALL_RESULT"); // テーブルデータの比較 CheckDataTableEquals(deliveryGroupExpectedTable, deliveryGroupActualTable); CheckDataTableEquals(deliveryResultExpectedTable, deliveryResultActualTable); CheckDataTableEquals(installResultExpectedTable, installResultActualTable); // 後処理 DbTestHelper.ExecSqlFromFilePath(in_DeleteNewDataSqlPath); }
/// <summary> /// 試験対象DBのデータを削除する /// </summary> public static void DeleteDbData() { DbTestHelper.ExecSqlFromFilePath(@"TestData\DeleteDispatcherData.sql"); }
/// <summary> /// マスタテーブルデータを生成する /// </summary> public static void MakeMasterTableData() { DbTestHelper.ExecSqlFromFilePath(@"TestData\MakeMasterTableData.sql"); }
/// <summary> /// マスタテーブルデータを削除する /// </summary> public static void DeleteMasterTableData() { DbTestHelper.ExecSqlFromFilePath(@"TestData\DeleteMastersReseed.sql"); }
public void PutDeliveryFileStatusTest( string no, string in_InsertNewDataSqlPath, string in_DeleteNewDataSqlPath, string in_InputJsonDataPath, string in_SidFormat, string in_AppSettingsInvalid, string in_ServiceException, string expected_DataJsonPath, string expected_LogMessagesPath, string expected_DtDeliveryFile_TableDataPath, string remarks) { Dictionary <string, string> dir = null; if (bool.TryParse(in_AppSettingsInvalid, out bool isAppSettingsInvalid) && isAppSettingsInvalid) { // DB接続文字列が不正なAppSettingsとする dir = new Dictionary <string, string>() { { "ConnectionStrings:PrimaryDbConnectionString", "TestConnectionString" } }; } // DI実施 DependencyInjection(DateTime.Parse("2020/04/30 09:00:00.0000000"), dir, (bool.TryParse(in_ServiceException, out bool isServiceException) && isServiceException)); // 初期データ挿入 DbTestHelper.ExecSqlFromFilePath(in_InsertNewDataSqlPath); // 投入JSONをDTOに変換する string inputDtoJson = (!string.IsNullOrEmpty(in_InputJsonDataPath) && File.Exists(in_InputJsonDataPath)) ? File.ReadAllText(in_InputJsonDataPath) : ""; // SID, RowVersionの取得 DataTable inputDataTable = DbTestHelper.SelectTable("SELECT SID, ROW_VERSION FROM core.DT_DELIVERY_FILE"); long sid = 1; long rowVersion = 0; if (inputDataTable.Rows.Count > 0) { sid = (long)inputDataTable.Rows[0].ItemArray[0]; rowVersion = WebApiHelper.ConvertByteArrayToLong((byte[])inputDataTable.Rows[0].ItemArray[1]); } // 投入するSIDを設定 long inputSid = long.Parse(string.Format(in_SidFormat, sid)); // JSONにRowVersionを埋め込む(JSONだと中括弧がFormatに影響を与えて面倒なので、Replaceを使用する) inputDtoJson = inputDtoJson.Replace("\"rowVersion\": {0}", "\"rowVersion\": " + rowVersion); // DTO変換できない場合は初期値とする(Azure Functionsと同様の挙動) DeliveryFileStatusUpdateRequestDto inputDto = null; try { inputDto = JsonConvert.DeserializeObject <DeliveryFileStatusUpdateRequestDto>(inputDtoJson); } catch (Exception) { inputDto = new DeliveryFileStatusUpdateRequestDto(); } // ログ格納用ロガーの用意 var actualLogs = new List <TestLog>(); var logger = new TestLogger <DeliveryFilesController>(actualLogs); // WebApi実行 var postResult = _controller.PutDeliveryFileStatus(inputDto, inputSid, logger); // データのjson化 string resultJson = Rms.Server.Core.Utility.ObjectExtensions.ToStringJsonIndented(postResult); string expectJson = null; if (File.Exists(expected_DataJsonPath)) { expectJson = File.ReadAllText(expected_DataJsonPath); // 期待値は投入RowVersion値+1(JSONだと中括弧がFormatに影響を与えて面倒なので、Replaceを使用する) expectJson = expectJson.Replace("\"rowVersion\": {0}", "\"rowVersion\": " + (rowVersion + 1)); } // データの比較 Assert.AreEqual(expectJson, resultJson); // 期待するログ、実際のログを取得 List <string> expectedLogMessages = (!string.IsNullOrEmpty(expected_LogMessagesPath) && File.Exists(expected_LogMessagesPath)) ? File.ReadLines(expected_LogMessagesPath).ToList() : new List <string>(); List <string> actualControllerLogMessages = actualLogs.Select(x => x.GetSimpleText()).ToList(); List <string> actualServiceLogMessages = _serviceLogs.Select(x => x.GetSimpleText()).ToList(); // ControllerかServiceで期待するログが出力されたか確認 foreach (var expectedLogMessage in expectedLogMessages) { var matchingElementController = actualControllerLogMessages.FirstOrDefault(actual => actual.Contains(expectedLogMessage)); var matchingElementService = actualServiceLogMessages.FirstOrDefault(actual => actual.Contains(expectedLogMessage)); Assert.IsTrue((matchingElementController != null || matchingElementService != null), string.Format("「{0}」に一致する要素が見つかりません", expectedLogMessage)); actualControllerLogMessages.Remove(matchingElementController); actualControllerLogMessages.Remove(matchingElementService); } // テーブルデータの実際の値・期待値を取得(RowVersion以外) DataTable DeliveryFileActualTable = DbTestHelper.SelectTable( @"SELECT SID, DELIVERY_FILE_TYPE_SID, INSTALL_TYPE_SID, FILE_PATH, VERSION, INSTALLABLE_VERSION, DESCRIPTION, INFORMATION_ID, IS_CANCELED, CREATE_DATETIME, UPDATE_DATETIME FROM core.DT_DELIVERY_FILE"); DataTable DeliveryFileExpectedTable = DbTestHelper.SelectCsv(expected_DtDeliveryFile_TableDataPath, @"SELECT SID, DELIVERY_FILE_TYPE_SID, INSTALL_TYPE_SID, FILE_PATH, VERSION, INSTALLABLE_VERSION, DESCRIPTION, INFORMATION_ID, IS_CANCELED, CREATE_DATETIME, UPDATE_DATETIME FROM core.DT_DELIVERY_FILE"); // テーブルデータの比較 CheckDataTableEquals(DeliveryFileExpectedTable, DeliveryFileActualTable); // 後処理 DbTestHelper.ExecSqlFromFilePath(in_DeleteNewDataSqlPath); }
public void PutDeviceTest( string no, string in_InsertNewDataSqlPath, string in_DeleteNewDataSqlPath, string in_InputJsonDataPath, string in_InitialBlobFilePath, string in_DeliveringBlobContainerNameInstallbase, string in_DeliveringBlobInstallbaseFilePath, string in_SidFormat, string in_InvalidDbConnectionString, string in_InvalidBlobConnectionString, string in_ServiceException, string expected_DataJsonPath, string expected_LogMessagesPath, string expected_UploadedDeliveringBlobPath, string expected_DtDevice_TableDataPath, string remarks) { string configContents; try { bool didUploadInitialBlob = CommonPreset( DateTime.Parse("2020/04/30 09:00:00.0000000"), in_InvalidDbConnectionString, in_InvalidBlobConnectionString, in_ServiceException, in_DeliveringBlobContainerNameInstallbase, in_DeliveringBlobInstallbaseFilePath, in_InsertNewDataSqlPath, in_InitialBlobFilePath, out configContents); // 投入JSONをDTOに変換する string inputDtoJson = (!string.IsNullOrEmpty(in_InputJsonDataPath) && File.Exists(in_InputJsonDataPath)) ? File.ReadAllText(in_InputJsonDataPath) : ""; // SID, RowVersionの取得 DataTable inputDataTable = DbTestHelper.SelectTable("SELECT SID, EDGE_ID, EQUIPMENT_UID FROM core.DT_DEVICE"); long sid = 1; string edgeId = string.Empty; string equipmentUid = string.Empty; if (inputDataTable.Rows.Count > 0) { sid = (long)inputDataTable.Rows[0].ItemArray[0]; edgeId = ((Guid)inputDataTable.Rows[0].ItemArray[1]).ToString(); equipmentUid = (string)inputDataTable.Rows[0].ItemArray[2]; } // 投入するSIDを設定 long inputSid = long.Parse(string.Format(in_SidFormat, sid)); // DTO変換できない場合は初期値とする(Azure Functionsと同様の挙動) DeviceUpdateRequestDto inputDto; try { inputDto = JsonConvert.DeserializeObject <DeviceUpdateRequestDto>(inputDtoJson); } catch (Exception) { inputDto = new DeviceUpdateRequestDto(); } // アップロード予定の場所にあるBlobを削除する TryFormatDeliveringBlobInstallbaseFilePath(_appSettings.DeliveringBlobInstallbaseFilePath, equipmentUid, out string filePath); if (didUploadInitialBlob && (!_appSettings.DeliveringBlobContainerNameInstallbase.Equals(_initialBlobContainerName) || !filePath.Equals(_initialBlobFilePath))) { // 事前Blobがアップロードされている場合は違うパスの時のみ削除する TryDeleteBlob(in_DeliveringBlobContainerNameInstallbase, filePath); } // ログ格納用ロガーの用意 var actualLogs = new List <TestLog>(); var logger = new TestLogger <DevicesController>(actualLogs); // WebApi実行 var putResult = _controller.PutDevice(inputDto, inputSid, logger); // レスポンスデータをチェックする CheckResponseDataEquals(putResult, expected_DataJsonPath, edgeId); // ログの出力をチェックする CheckLogMessagesContains(expected_LogMessagesPath, actualLogs, edgeId); // DB内容をチェックする CheckDbDataEquals(expected_DtDevice_TableDataPath); // アップロードしたBlobの内容をチェックし、削除する CheckBlobsEqualsAndCleanBlobs( didUploadInitialBlob, edgeId, configContents, _appSettings.DeliveringBlobContainerNameInstallbase, filePath, expected_UploadedDeliveringBlobPath); // 後処理 DbTestHelper.ExecSqlFromFilePath(in_DeleteNewDataSqlPath); } catch { throw; } }
public void PostDeviceTest( string no, string in_InsertNewDataSqlPath, string in_DeleteNewDataSqlPath, string in_InputJsonDataPath, string in_InitialBlobFilePath, string in_DeliveringBlobContainerNameInstallbase, string in_DeliveringBlobInstallbaseFilePath, string in_InvalidDbConnectionString, string in_InvalidBlobConnectionString, string in_ServiceException, string expected_DataJsonPath, string expected_LogMessagesPath, string expected_UploadedDeliveringBlobPath, string expected_DtDevice_TableDataPath, string remarks) { string configContents; try { bool didUploadInitialBlob = CommonPreset( DateTime.Parse("2020/04/01 09:00:00.0000000"), in_InvalidDbConnectionString, in_InvalidBlobConnectionString, in_ServiceException, in_DeliveringBlobContainerNameInstallbase, in_DeliveringBlobInstallbaseFilePath, in_InsertNewDataSqlPath, in_InitialBlobFilePath, out configContents); // 投入JSONをDTOに変換する string inputDtoJson = (!string.IsNullOrEmpty(in_InputJsonDataPath) && File.Exists(in_InputJsonDataPath)) ? File.ReadAllText(in_InputJsonDataPath) : ""; // DTO変換できない場合は初期値とする(Azure Functionsと同様の挙動) DeviceAddRequestDto inputDto; try { inputDto = JsonConvert.DeserializeObject <DeviceAddRequestDto>(inputDtoJson); } catch (Exception) { inputDto = new DeviceAddRequestDto(); } // アップロード予定の場所にあるBlobを削除する TryFormatDeliveringBlobInstallbaseFilePath(_appSettings.DeliveringBlobInstallbaseFilePath, inputDto.Device?.EquipmentUid, out string filePath); TryDeleteBlob(in_DeliveringBlobContainerNameInstallbase, filePath); // ログ格納用ロガーの用意 var actualLogs = new List <TestLog>(); var logger = new TestLogger <DevicesController>(actualLogs); // WebApi実行 string edgeId = string.Empty; var postResult = _controller.PostDevice(inputDto, logger); if (postResult is OkObjectResult) { // 結果が流動的になる値は比較できないので固定値を入れる var okDto = ((postResult as OkObjectResult).Value as DeviceResponseDto); Assert.IsNotNull(okDto); edgeId = okDto.EdgeId.ToString(); } // レスポンスデータをチェックする CheckResponseDataEquals(postResult, expected_DataJsonPath, edgeId); // ログの出力をチェックする CheckLogMessagesContains(expected_LogMessagesPath, actualLogs, edgeId); // DB内容をチェックする CheckDbDataEquals(expected_DtDevice_TableDataPath); // アップロードしたBlobの内容をチェックし、削除する CheckBlobsEqualsAndCleanBlobs( didUploadInitialBlob, edgeId, configContents, _appSettings.DeliveringBlobContainerNameInstallbase, filePath, expected_UploadedDeliveringBlobPath); // 後処理 DbTestHelper.ExecSqlFromFilePath(in_DeleteNewDataSqlPath); } catch { // デバッグでエラー番号見る用 throw; } }
public void TestCleanup() { // 端末データを全削除して次回作成時のSIDを1にする DbTestHelper.ExecSqlFromFilePath(@"TestData\ReseedDevice.sql"); }
public async Task BlobCleanTest( string no, string TestDateTime, string LocalFileRoot, string in_AppSettings, string in_InsertNewDataSqlPath, string expected_BlobStatusPath, string expected_FileAttributesCheck, string expected_FileAttributesCount, string expected_LogLevel, string expected_LogResource, string expected_LogInfo, string expected_WithoutError, string expected_ErrorDescription, string error_DeleteDtDeviceFile, string error_Delete, string remarks) { // AppSettings Dictionary <string, string> appSettingsConfigures = null; if (!string.IsNullOrEmpty(in_AppSettings)) { appSettingsConfigures = JsonConvert.DeserializeObject <Dictionary <string, string> >(in_AppSettings); } // 例外処理を発生させるメソッドを示すフラグ bool.TryParse(error_DeleteDtDeviceFile, out bool isErrorOnDeleteDtDeviceFile); bool.TryParse(error_Delete, out bool isErrorOnDelete); // エラーログが出ていないことを確認するかどうかを示すフラグ bool.TryParse(expected_WithoutError, out bool isWithoutError); // エラーログの一致性は確認しないがエラーメッセージの有無はチェックするかどうかを示すフラグ bool.TryParse(expected_ErrorDescription, out bool isErrorDescriptionNeeded); // 端末ファイル属性データテーブルの状態をテストするかどうかを示すフラグ bool.TryParse(expected_FileAttributesCheck, out bool isFileAttributesChecked); // 端末ファイル属性データテーブルの状態をテストする場合に、期待するレコード数 // 全削除を期待するのであれば0 int.TryParse(expected_FileAttributesCount, out int expectedFileAttributesCount); // ログ格納用ロガーの用意 // Controller用 var actualControllerLogs = new List <TestLog>(); var logger = new TestLogger <BlobCleanController>(actualControllerLogs); // Service用 var actualServiceLogs = new List <TestLog>(); _serviceLogger = new TestLogger <CleanBlobService>(actualServiceLogs); // テスト実行日時(ファイル削除閾値の基準となる値) DateTime testDateTime = default(DateTime); if (!string.IsNullOrEmpty(TestDateTime)) { testDateTime = DateTime.ParseExact(TestDateTime, DateTimeFormat, null); } // テスト用実行日時情報、Logger、AppSettingsを渡してDI DependencyInjection(testDateTime, _serviceLogger, appSettingsConfigures); // 例外処理を実行フラグをモックに設定する // 第1引数は削除対象ファイルのうち何番目のファイル処理時に例外を起こすかを指定するインデックスだが、 // 基本的に1番目のファイルを対象とするので1固定とする _dtDeviceFileRepositoryMock.Init(1, isErrorOnDeleteDtDeviceFile); _primaryBlobRepositoryMock.Init(1, isErrorOnDelete); // テスト用データをDBに挿入する if (!string.IsNullOrEmpty(in_InsertNewDataSqlPath)) { DbTestHelper.ExecSqlFromFilePath(in_InsertNewDataSqlPath); } // PrimaryBlobの接続文字列 var connectionString = _appSettings.PrimaryBlobConnectionString; // ローカルファイルパスの記述がある場合にはBlobにファイルをアップロードする int dbMaxCount = 0; if (!string.IsNullOrEmpty(LocalFileRoot)) { // ファイルリスト取得 string[] fileList = Directory.GetFiles(LocalFileRoot, "*", SearchOption.AllDirectories); dbMaxCount = fileList.Length; // 端末ファイルの数だけDBからファイルパス情報を取得する List <BlobInfo> blobInfoList = GetBlobInfoListFromDB(dbMaxCount); // Blobアップロード処理 foreach (string name in fileList) { // ローカルのテスト用ファイルのファイル名のみを取得 string filename = Path.GetFileName(name); foreach (var blobInfo in blobInfoList) { // Blobコンテナを取得する var container = GetContainer(connectionString, blobInfo.ContainerName); // ローカルのテスト用ファイル名が、Blobのパスに含まれていた場合にそのファイルをBlobとして追加する // ローカルファイルとBlobのアップロード先のファイル名を1対1に対応させる if (blobInfo.FilePath.Contains(filename)) { // 指定したローカルファイルパスのファイルをアップロード await Upload(container, blobInfo.FilePath, name); break; } } } } // BlobCleaner実行 { Rms.Server.Core.Utility.Assert.IfNull(_controller); _controller.CleanBlob(null, logger); } // テスト結果フラグ bool isDatabaseStatusMatched = true; bool isBlobStatusMatched = true; bool isExpectedLogContained = false; // DBとBlobの状態確認 if (!string.IsNullOrEmpty(expected_BlobStatusPath)) { var expectedBlobStatusList = GetBlobExpectedStatusList(expected_BlobStatusPath); var actualDBStatusList = GetBlobInfoListFromDB(dbMaxCount).Select(x => x.FilePath); foreach (var eachStatus in expectedBlobStatusList) { // DBの確認 if (eachStatus.IsDBCheckNeeded) { if (eachStatus.IsDeletedFromDB) { if (actualDBStatusList.Contains(eachStatus.Path)) { isDatabaseStatusMatched = false; break; } } else { if (!actualDBStatusList.Contains(eachStatus.Path)) { isDatabaseStatusMatched = false; break; } } } // Containerの確認 if (eachStatus.IsContainerCheckNeeded) { var actualBlobList = await GetBlobList(connectionString, eachStatus.ContainerName); if (eachStatus.IsDeletedFromContainer) { if (actualBlobList.Contains(eachStatus.Path)) { isBlobStatusMatched = false; break; } } else { if (!actualBlobList.Contains(eachStatus.Path)) { isBlobStatusMatched = false; break; } } } } } // DB(FileAttributes)のチェック if (isFileAttributesChecked) { int actualFileAttributesCount = GetFileAttributesCount(dbMaxCount); if (actualFileAttributesCount != expectedFileAttributesCount) { isDatabaseStatusMatched = false; } } // ログの確認 if (isWithoutError) { // エラーログが出ていないことを確認する bool isControllerError = false; bool isServiceError = false; // Controllerログ foreach (TestLog eachLog in actualControllerLogs) { if (eachLog.LogLevel == Microsoft.Extensions.Logging.LogLevel.Error) { isControllerError = true; break; } } // Serviceログ foreach (TestLog eachLog in actualServiceLogs) { if (eachLog.LogLevel == Microsoft.Extensions.Logging.LogLevel.Error) { isServiceError = true; break; } } isExpectedLogContained = !(isControllerError || isServiceError); } else if (isErrorDescriptionNeeded) { // エラーログの詳細が含まれているか確認する // Serviceログ(Controllerのログはチェックしない) foreach (TestLog eachLog in actualServiceLogs) { if (eachLog.LogLevel == Microsoft.Extensions.Logging.LogLevel.Error) { string message = eachLog.GetSimpleText(); if (!message.Contains("()")) { isExpectedLogContained = true; break; } } } } else { // // ログの詳細を確認する // // ログに出力する情報 var logInfo = GetLogInfo(expected_LogInfo); // 期待するログメッセージ var expectedLogMessages = GetLogMessages(expected_LogResource, logInfo); // ログレベル int expectedLogLevel = -1; if (!string.IsNullOrEmpty(expected_LogLevel)) { int.TryParse(expected_LogLevel, out expectedLogLevel); } int expectedLogMessagesCount = expectedLogMessages.Count; int countMatchLogs = 0; foreach (string expectedLogMessage in expectedLogMessages) { // Controllerログ foreach (TestLog eachLog in actualControllerLogs) { string actualLog = eachLog.GetSimpleText(); if (actualLog.Contains(expectedLogMessage) && eachLog.LogLevel == (Microsoft.Extensions.Logging.LogLevel)expectedLogLevel) { // 期待していたログが見つかった countMatchLogs += 1; break; } } // Serviceログ foreach (TestLog eachLog in actualServiceLogs) { string actualLog = eachLog.GetSimpleText(); if (actualLog.Contains(expectedLogMessage)) { // 期待していたログが見つかった countMatchLogs += 1; break; } } } // 期待するログがすべて見つかればフラグを立てる if (countMatchLogs == expectedLogMessagesCount) { isExpectedLogContained = true; } } // Blob削除(コンテナは削除しない): テストケース1回ごとにBlobを削除する // 不正な接続文字列を指定していた場合には例外が発生するが、テストとは関係ないため例外は無視する try { foreach (string containerName in ContainerNameList) { await DeleteBlobInContainer(connectionString, containerName); } } catch (Exception) { ; } // Blob削除後にテスト // 期待するログがService用のロガーに記録されていればテストOK Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(true, isDatabaseStatusMatched); Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(true, isBlobStatusMatched); Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(true, isExpectedLogContained); }