Example #1
0
        /// <summary>
        /// DBデータが期待値と等しいかチェックする
        /// </summary>
        /// <param name="expected_DtDevice_TableDataPath">期待する端末データのDBテーブル内容</param>
        private void CheckDbDataEquals(string expected_DtDevice_TableDataPath)
        {
            // テーブルデータの実際の値・期待値を取得(EdgeId以外)
            DataTable deviceActualTable = DbTestHelper.SelectTable(
                @"SELECT 
                    SID, EQUIPMENT_MODEL_SID, INSTALL_TYPE_SID, CONNECT_STATUS_SID, EQUIPMENT_UID, REMOTE_CONNECT_UID, RMS_SOFT_VERSION, CONNECT_START_DATETIME, CONNECT_UPDATE_DATETIME, CREATE_DATETIME, UPDATE_DATETIME 
                FROM core.DT_DEVICE");
            DataTable deviceExpectedTable = DbTestHelper.SelectCsv(expected_DtDevice_TableDataPath,
                                                                   @"SELECT 
                    SID, EQUIPMENT_MODEL_SID, INSTALL_TYPE_SID, CONNECT_STATUS_SID, EQUIPMENT_UID, REMOTE_CONNECT_UID, RMS_SOFT_VERSION, CONNECT_START_DATETIME, CONNECT_UPDATE_DATETIME, CREATE_DATETIME, UPDATE_DATETIME
                FROM core.DT_DEVICE");

            // テーブルデータの比較
            CheckDataTableEquals(deviceExpectedTable, deviceActualTable);
        }
        public void DirectoryUsageTest(string no, string in_InitializeSqlSet, string in_Message, string expected_TableData, string expected_FailureBlobFileSet, string expected_LogMessages, string expected_WithoutError, string in_AppSettings, string error_Method, string remarks)
        {
            List <TestLog> actual_logs = new List <TestLog>();

            // AppSettings
            Dictionary <string, string> appSettingsConfigures = null;

            if (!string.IsNullOrEmpty(in_AppSettings))
            {
                using (var sr = new StreamReader(in_AppSettings))
                {
                    JsonTextReader reader = new JsonTextReader(sr);
                    var            se     = new JsonSerializer();
                    appSettingsConfigures = se.Deserialize <Dictionary <string, string> >(reader);
                }
            }

            // DI
            DependencyInjection(appSettingsConfigures, actual_logs, error_Method);

            // FailureBlobのファイルはDI後に削除する(コンテナ名を変更しての試験があるため)
            DispatcherTestCommon.DeleteFailureBlobFile(_failureBlob, _diAppSettings.FailureBlobContainerNameDispatcher);

            // テストデータ準備
            {
                if (Directory.Exists(in_InitializeSqlSet))
                {
                    using (SqlConnection connection = new SqlConnection(_localAppSettings.PrimaryDbConnectionString))
                    {
                        try
                        {
                            connection.Open();

                            // 各試験で必要となるデータを設定
                            foreach (string path in Directory.GetFiles(in_InitializeSqlSet, "*.sql", SearchOption.AllDirectories))
                            {
                                var cmdText = File.ReadAllText(path);
                                using (SqlCommand command = new SqlCommand(cmdText, connection))
                                {
                                    command.ExecuteNonQuery();
                                }
                            }
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
                }

                in_Message = (in_Message != null && File.Exists(in_Message)) ? File.ReadAllText(in_Message) : in_Message;
            }

            // テスト実行後、テーブルを評価するかどうか
            bool isCheckTable = !string.IsNullOrEmpty(expected_TableData) && File.Exists(expected_TableData);

            // 評価対象テーブル名
            string targetTableName = isCheckTable ? Path.GetFileNameWithoutExtension(expected_TableData) : null;

            // 期待値
            DataTable     expected_table     = isCheckTable ? DbTestHelper.SelectCsv(expected_TableData, "SELECT * FROM " + targetTableName) : null;
            DirectoryInfo expectedFailureDir = new DirectoryInfo(expected_FailureBlobFileSet);

            string[]      expectedFailureFiles      = expectedFailureDir.Exists ? expectedFailureDir.GetFiles("*", SearchOption.AllDirectories).Select(x => x.FullName).OrderBy(x => x).ToArray() : new string[] { };
            string[]      expected_failure_names    = expectedFailureFiles.Select(x => x.Replace(expectedFailureDir.FullName, string.Empty)).ToArray();
            string[]      expected_failure_contents = expectedFailureFiles.Select(x => File.ReadAllText(x)).ToArray();
            List <string> expected_log_messages     = (!string.IsNullOrEmpty(expected_LogMessages) && File.Exists(expected_LogMessages)) ? File.ReadLines(expected_LogMessages).ToList() : new List <string>();

            // テスト実行
            _target.DispatchDirectoryUsage(in_Message, new TestLogger <DispatchController>(actual_logs));

            // テスト結果
            DataTable     actual_table = isCheckTable ? DbTestHelper.SelectTable("SELECT * FROM " + targetTableName) : null;
            DirectoryInfo actualDir    = new DirectoryInfo(Path.Combine(TestResultRootDir, no));

            string[]      actualFailureFiles      = _failureBlob.Client.GetFiles(_diAppSettings.FailureBlobContainerNameDispatcher, actualDir).OrderBy(x => x).ToArray();
            string[]      actual_failure_names    = actualFailureFiles.Select(x => x.Replace(actualDir.FullName, string.Empty)).ToArray();
            string[]      actual_failure_contents = actualFailureFiles.Select(x => File.ReadAllText(x)).ToArray();
            List <string> actual_log_messages     = actual_logs.Select(x => x.GetSimpleText()).ToList();

            // 確認
            if (isCheckTable)
            {
                // 評価対象外のカラムを除外
                Array.ForEach(IgnoreColumns, x => expected_table.Columns.Remove(x));
                Array.ForEach(IgnoreColumns, x => actual_table.Columns.Remove(x));

                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(expected_table.Rows.Count, actual_table.Rows.Count);
                for (int i = 0; i < expected_table.Rows.Count; i++)
                {
                    CollectionAssert.AreEqual(expected_table.Rows[i].ItemArray, actual_table.Rows[i].ItemArray);
                }
            }

            // フォルダ名は小文字で取得されるため大文字に変換
            for (int i = 0; i < expected_failure_names.Length; i++)
            {
                expected_failure_names[i] = expected_failure_names[i].Replace(FailureBlobReplacePath, FailureBlobReplacePath.ToUpper());
            }
            CollectionAssert.AreEqual(expected_failure_names, actual_failure_names);
            CollectionAssert.AreEqual(expected_failure_contents, actual_failure_contents);

            bool.TryParse(expected_WithoutError, out bool isWithoutError);
            if (isWithoutError)
            {
                // エラーログが含まれない事を確認
                // actual_logsはexpected_log_messageとの比較時に要素が削除されるため本処理を先に実行すること
                var error_logs = actual_logs.Where(x => x.LogLevel == Microsoft.Extensions.Logging.LogLevel.Error);
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(false, error_logs.Any());
            }

            foreach (var expected_log_message in expected_log_messages)
            {
                var matching_element = actual_log_messages.FirstOrDefault(actual => actual.Contains(expected_log_message));
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(matching_element, string.Format("「{0}」に一致する要素が見つかりません", expected_log_message));
                if (matching_element != null)
                {
                    actual_log_messages.Remove(matching_element);
                }
            }
        }
Example #3
0
        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);
        }
Example #4
0
        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);
        }
        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);
        }
Example #6
0
        public void ServiceBillLogTest(string no, string in_InitializeSqlSet, string in_Message, string expected_TableData, string expected_FailureBlobFileSet, string expected_LogMessages, string expected_WithoutError, string remarks)
        {
            List <TestLog> actual_logs = new List <TestLog>();

            // DI
            DependencyInjection(DefaultAppSettingValues, actual_logs);

            // テストデータ準備
            {
                if (Directory.Exists(in_InitializeSqlSet))
                {
                    using (SqlConnection connection = new SqlConnection(settings.PrimaryDbConnectionString))
                    {
                        try
                        {
                            connection.Open();
                            foreach (string path in Directory.GetFiles(in_InitializeSqlSet, "*.sql", SearchOption.AllDirectories))
                            {
                                string cmdText = File.ReadAllText(path);
                                using (SqlCommand command = new SqlCommand(cmdText, connection))
                                {
                                    command.ExecuteNonQuery();
                                }
                            }
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
                }

                in_Message = (in_Message != null && File.Exists(in_Message)) ? File.ReadAllText(in_Message) : in_Message;
            }

            // テスト実行後、テーブルを評価するかどうか
            bool isCheckTable = !string.IsNullOrEmpty(expected_TableData) && File.Exists(expected_TableData);

            // 評価対象テーブル名
            string targetTableName = isCheckTable ? Path.GetFileNameWithoutExtension(expected_TableData) : null;

            // 期待値
            DataTable     expected_table     = isCheckTable ? DbTestHelper.SelectCsv(expected_TableData, "SELECT * FROM " + targetTableName) : null;
            DirectoryInfo expectedFailureDir = new DirectoryInfo(expected_FailureBlobFileSet);

            string[]      expectedFailureFiles      = expectedFailureDir.Exists ? expectedFailureDir.GetFiles("*", SearchOption.AllDirectories).Select(x => x.FullName).OrderBy(x => x).ToArray() : new string[] { };
            string[]      expected_failure_names    = expectedFailureFiles.Select(x => x.Replace(expectedFailureDir.FullName, string.Empty)).ToArray();
            string[]      expected_failure_contents = expectedFailureFiles.Select(x => File.ReadAllText(x)).ToArray();
            List <string> expected_log_messages     = (!string.IsNullOrEmpty(expected_LogMessages) && File.Exists(expected_LogMessages)) ? File.ReadLines(expected_LogMessages).ToList() : new List <string>();

            // テスト実行
            target.DispatchPlusServiceBillLog(in_Message, new TestLogger <DispatchController>(actual_logs));

            // テスト結果
            DataTable     actual_table = isCheckTable ? DbTestHelper.SelectTable("SELECT * FROM " + targetTableName) : null;
            DirectoryInfo actualDir    = new DirectoryInfo(Path.Combine(TestResultRootDir, no));

            string[]      actualFailureFiles      = failureBlob.Client.GetFiles(settings.FailureBlobContainerNameDispatcher, actualDir).OrderBy(x => x).ToArray();
            string[]      actual_failure_names    = actualFailureFiles.Select(x => x.Replace(actualDir.FullName, string.Empty)).ToArray();
            string[]      actual_failure_contents = actualFailureFiles.Select(x => File.ReadAllText(x)).ToArray();
            List <string> actual_log_messages     = actual_logs.Select(x => x.GetSimpleText()).ToList();

            // 確認
            if (isCheckTable)
            {
                // 評価対象外のカラムを除外
                Array.ForEach(IgnoreColumns, x => expected_table.Columns.Remove(x));
                Array.ForEach(IgnoreColumns, x => actual_table.Columns.Remove(x));

                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(expected_table.Rows.Count, actual_table.Rows.Count);
                for (int i = 0; i < expected_table.Rows.Count; i++)
                {
                    CollectionAssert.AreEqual(expected_table.Rows[i].ItemArray, actual_table.Rows[i].ItemArray);
                }
            }

            CollectionAssert.AreEqual(expected_failure_names, actual_failure_names);
            CollectionAssert.AreEqual(expected_failure_contents, actual_failure_contents);

            bool.TryParse(expected_WithoutError, out bool isWithoutError);
            if (isWithoutError)
            {
                var error_logs = actual_logs.Where(x => x.LogLevel == Microsoft.Extensions.Logging.LogLevel.Error);
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(false, error_logs.Any());
            }

            foreach (var expected_log_message in expected_log_messages)
            {
                var matching_element = actual_log_messages.FirstOrDefault(actual => actual.Contains(expected_log_message));
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(matching_element, string.Format("「{0}」に一致する要素が見つかりません", expected_log_message));
                if (matching_element != null)
                {
                    actual_log_messages.Remove(matching_element);
                }
            }
        }
Example #7
0
        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;
            }
        }
Example #8
0
        public void CleanDbTest(string no, string mock_Exception, string in_AppSettingsJson, string in_InitializeSqlList, string expected_TargetTableDataSet, string expected_NonTargetTableDataSet, string expected_ExistLogMessages, string expected_NotExistLogMessages, string remarks)
        {
            List <TestLog> actual_logs = new List <TestLog>();

            // アプリケーション設定(local.settings.jsonに上書きする設定)
            Dictionary <string, string> appSettings = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(in_AppSettingsJson));

            // DI
            DependencyInjection(appSettings, actual_logs, Type.GetType(mock_Exception));

            // テストデータ準備
            {
                using (SqlConnection connection = new SqlConnection(settings.PrimaryDbConnectionString))
                {
                    try
                    {
                        connection.Open();
                        foreach (string path in in_InitializeSqlList.Split(",", StringSplitOptions.RemoveEmptyEntries))
                        {
                            string cmdText = File.ReadAllText(path);
                            using (SqlCommand command = new SqlCommand(cmdText, connection))
                            {
                                command.ExecuteNonQuery();
                            }
                        }
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }

            // 期待値
            Dictionary <string, DataTable> expected_target_tables = Directory.GetFiles(expected_TargetTableDataSet, "*.csv", SearchOption.AllDirectories)
                                                                    .ToDictionary(
                x => Path.GetFileNameWithoutExtension(x),
                y => DbTestHelper.SelectCsv(y, "SELECT SID, COLLECT_DATETIME FROM " + Path.GetFileNameWithoutExtension(y)));
            Dictionary <string, DataTable> expected_nontarget_tables = Directory.GetFiles(expected_NonTargetTableDataSet, "*.csv", SearchOption.AllDirectories)
                                                                       .ToDictionary(
                x => Path.GetFileNameWithoutExtension(x),
                y => DbTestHelper.SelectCsv(y, "SELECT SID FROM " + Path.GetFileNameWithoutExtension(y)));
            List <string> expected_exist_log_messages    = File.ReadLines(expected_ExistLogMessages).ToList();
            List <string> expected_notexist_log_messages = File.ReadLines(expected_NotExistLogMessages).ToList();

            // テスト実行
            target.CleanDb(null, new TestLogger <DbCleanController>(actual_logs));

            // テスト結果
            Dictionary <string, DataTable> actual_target_tables    = TargetTableNames.ToDictionary(x => x, y => DbTestHelper.SelectTable("SELECT SID, COLLECT_DATETIME FROM " + y));
            Dictionary <string, DataTable> actual_nontarget_tables = NonTargetTableNames.ToDictionary(x => x, y => DbTestHelper.SelectTable("SELECT SID FROM " + y));
            List <string> actual_log_messages = actual_logs.Select(x => x.GetSimpleText()).ToList();

            // 確認(削除対象テーブル)
            foreach (string tableName in TargetTableNames)
            {
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(expected_target_tables[tableName].Rows.Count, actual_target_tables[tableName].Rows.Count);
                for (int i = 0; i < expected_target_tables[tableName].Rows.Count; i++)
                {
                    CollectionAssert.AreEqual(expected_target_tables[tableName].Rows[i].ItemArray, actual_target_tables[tableName].Rows[i].ItemArray);
                }
            }

            // 確認(削除対象外テーブル)
            foreach (string tableName in NonTargetTableNames)
            {
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(expected_nontarget_tables[tableName].Rows.Count, actual_nontarget_tables[tableName].Rows.Count);
                for (int i = 0; i < expected_nontarget_tables[tableName].Rows.Count; i++)
                {
                    CollectionAssert.AreEqual(expected_nontarget_tables[tableName].Rows[i].ItemArray, actual_nontarget_tables[tableName].Rows[i].ItemArray);
                }
            }

            // 確認(非出力ログの確認)
            foreach (var expected_log in expected_notexist_log_messages)
            {
                var matching_element = actual_log_messages.FirstOrDefault(actual => actual.Contains(expected_log));
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNull(matching_element, string.Format("「{0}」に一致する要素が存在します", expected_log));
            }

            // 確認(出力ログの確認)
            foreach (var expected_log in expected_exist_log_messages)
            {
                var matching_element = actual_log_messages.FirstOrDefault(actual => actual.Contains(expected_log));
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(matching_element, string.Format("「{0}」に一致する要素が見つかりません", expected_log));
                if (matching_element != null)
                {
                    actual_log_messages.Remove(matching_element);
                }
            }
        }