From 6f17c15d2c43bcb0eff1489369665875341e507b Mon Sep 17 00:00:00 2001 From: Charles Gagnon Date: Wed, 16 Oct 2019 10:43:12 -0700 Subject: [PATCH] Test fixes (#877) * Test fixes * Delete unneeded using --- .../Connection/ConnectionService.cs | 2 +- .../BatchParser/BatchParserTests.cs | 146 +++++----------- .../DisasterRecovery/BackupServiceTests.cs | 165 ++++++++---------- .../SchemaCompareServiceTests.cs | 2 +- .../SchemaCompare/SchemaCompareTestUtils.cs | 2 +- 5 files changed, 128 insertions(+), 189 deletions(-) diff --git a/src/Microsoft.SqlTools.ServiceLayer/Connection/ConnectionService.cs b/src/Microsoft.SqlTools.ServiceLayer/Connection/ConnectionService.cs index 14700415..cc118825 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/Connection/ConnectionService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/Connection/ConnectionService.cs @@ -1472,7 +1472,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection /// The connection info to connect with /// A plaintext string that will be included in the application name for the connection /// A SqlConnection created with the given connection info - internal static SqlConnection OpenSqlConnection(ConnectionInfo connInfo, string featureName = null) + public static SqlConnection OpenSqlConnection(ConnectionInfo connInfo, string featureName = null) { try { diff --git a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserTests.cs b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserTests.cs index 17a7ab3b..23613825 100644 --- a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserTests.cs +++ b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserTests.cs @@ -15,15 +15,13 @@ using System.Globalization; using System.IO; using System.Text; using Xunit; +using Microsoft.SqlTools.ServiceLayer.Connection; +using System.Threading.Tasks; namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser { public class BatchParserTests : BaselinedTest { - private bool testFailed = false; - private static ScriptExecutionResult executionResult = ScriptExecutionResult.All; - private const string CONNECTION_STRING = "Data Source=.;Initial Catalog=master;Integrated Security=True"; - public BatchParserTests() { InitializeTest(); @@ -150,15 +148,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser public void VerifyExecute() { Batch batch = new Batch(sqlText: "SELECT 1+1", isResultExpected: true, execTimeout: 15); - using (SqlConnection con = new SqlConnection(CONNECTION_STRING)) + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - con.Open(); - if (con.State.ToString().ToLower() == "open") - { - executionResult = batch.Execute(con, ShowPlanType.AllShowPlan); - } + var executionResult = batch.Execute(sqlConn, ShowPlanType.AllShowPlan); + Assert.Equal(ScriptExecutionResult.Success, executionResult); } - Assert.Equal(ScriptExecutionResult.Success, executionResult); + } // Verify the exeception is handled by passing invalid keyword. @@ -166,13 +162,10 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser public void VerifyHandleExceptionMessage() { Batch batch = new Batch(sqlText: "SEL@ECT 1+1", isResultExpected: true, execTimeout: 15); - using (SqlConnection con = new SqlConnection(CONNECTION_STRING)) + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - con.Open(); - if (con.State.ToString().ToLower() == "open") - { - ScriptExecutionResult result = batch.Execute(con, ShowPlanType.AllShowPlan); - } + ScriptExecutionResult result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan); } ScriptExecutionResult finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; @@ -185,13 +178,10 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser { Batch batch = new Batch(sqlText: null, isResultExpected: true, execTimeout: 15); ScriptExecutionResult finalResult = ScriptExecutionResult.All; - using (SqlConnection con = new SqlConnection(CONNECTION_STRING)) + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - con.Open(); - if (con.State.ToString().ToLower() == "open") - { - ScriptExecutionResult result = batch.Execute(con, ShowPlanType.AllShowPlan); - } + ScriptExecutionResult result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan); } finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; @@ -204,19 +194,19 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser { ScriptExecutionResult result = ScriptExecutionResult.All; Batch batch = new Batch(sqlText: "SELECT 1+1", isResultExpected: true, execTimeout: 15); - using (SqlConnection con = new SqlConnection(CONNECTION_STRING)) + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - con.Open(); - if (con.State.ToString().ToLower() == "open") - { - batch.Cancel(); - result = batch.Execute(con, ShowPlanType.AllShowPlan); - } + batch.Cancel(); + result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan); } Assert.Equal(result, ScriptExecutionResult.Cancel); } - // verify weather lexer can consume token for SqlCmd variable + // + /// + /// Verify whether lexer can consume token for SqlCmd variable + /// [Fact] public void VerifyLexerSetState() { @@ -228,14 +218,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser { lexer.ConsumeToken(); } - executionResult = ScriptExecutionResult.Success; } - catch (Exception) + catch (Exception e) { - executionResult = ScriptExecutionResult.Failure; + Assert.True(false, $"Unexpected error consuming token : {e.Message}"); } // we doesn't expect any exception or testCase failures - Assert.Equal(ScriptExecutionResult.Success, executionResult); + } // This test case is to verify that, Powershell's Invoke-SqlCmd handles ":!!if" in an inconsistent way @@ -308,10 +297,10 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser { string query = @"SELECT 1+2 Go 2"; - using (SqlConnection con = new SqlConnection(CONNECTION_STRING)) + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - con.Open(); - TestExecutor testExecutor = new TestExecutor(query, con, new ExecutionEngineConditions()); + TestExecutor testExecutor = new TestExecutor(query, sqlConn, new ExecutionEngineConditions()); testExecutor.Run(); ScriptExecutionResult result = (testExecutor.ExecutionResult == ScriptExecutionResult.Success) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; @@ -328,10 +317,10 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser using (ExecutionEngine executionEngine = new ExecutionEngine()) { string query = @"sqlcmd -Q ""select 1 + 2 as col"" "; - using (SqlConnection con = new SqlConnection(CONNECTION_STRING)) + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - con.Open(); - TestExecutor testExecutor = new TestExecutor(query, con, new ExecutionEngineConditions()); + TestExecutor testExecutor = new TestExecutor(query, sqlConn, new ExecutionEngineConditions()); testExecutor.Run(); Assert.True(testExecutor.ResultCountQueue.Count >= 1); } @@ -360,16 +349,15 @@ GO select $(__var1) + $(__var2) as col GO"; - using (SqlConnection con = new SqlConnection(CONNECTION_STRING)) + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); + var condition = new ExecutionEngineConditions() { IsSqlCmd = true }; + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) + using (TestExecutor testExecutor = new TestExecutor(sqlCmdQuery, sqlConn, condition)) { - con.Open(); - var condition = new ExecutionEngineConditions() { IsSqlCmd = true }; - TestExecutor testExecutor = new TestExecutor(sqlCmdQuery, con, condition); testExecutor.Run(); - - Assert.True(testExecutor.ResultCountQueue.Count >= 1); - Assert.True(testExecutor.ErrorMessageQueue.Count == 0); - + + Assert.True(testExecutor.ResultCountQueue.Count >= 1, $"Unexpected number of ResultCount items - expected 0 but got {testExecutor.ResultCountQueue.Count}"); + Assert.True(testExecutor.ErrorMessageQueue.Count == 0, $"Unexpected error messages from test executor : {string.Join(Environment.NewLine, testExecutor.ErrorMessageQueue)}"); } } } @@ -381,23 +369,22 @@ GO"; using (ExecutionEngine executionEngine = new ExecutionEngine()) { string query = "SELECT 1+2"; - using (SqlConnection con = new SqlConnection(CONNECTION_STRING)) + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - con.Open(); - - executionEngine.BatchParserExecutionFinished += OnBatchParserExecutionFinished; - executionEngine.ExecuteBatch(new ScriptExecutionArgs(query, con, 15, new ExecutionEngineConditions(), new BatchParserMockEventHandler())); - Assert.Equal(ScriptExecutionResult.Success, executionResult); + var executionPromise = new TaskCompletionSource(); + executionEngine.BatchParserExecutionFinished += (object sender, BatchParserExecutionFinishedEventArgs e) => + { + Assert.Equal(ScriptExecutionResult.Success, e.ExecutionResult); + executionPromise.SetResult(true); + }; + executionEngine.ExecuteBatch(new ScriptExecutionArgs(query, sqlConn, 15, new ExecutionEngineConditions(), new BatchParserMockEventHandler())); + Task.WaitAny(executionPromise.Task, Task.Delay(5000)); + Assert.True(executionPromise.Task.IsCompleted, "Execution did not finish in time"); } } } - // Capture the event once batch finish execution. - private void OnBatchParserExecutionFinished(object sender, BatchParserExecutionFinishedEventArgs e) - { - executionResult = e.ExecutionResult; - } - [Fact] public void CanceltheBatch() { @@ -489,42 +476,6 @@ GO"; FileUtilities.SetFileReadWrite(filename); } - // [Fact] - public void BatchParserTest() - { - CopyToOutput(FilesLocation, "TS-err-cycle1.txt"); - CopyToOutput(FilesLocation, "cycle2.txt"); - Start("err-blockComment"); - Start("err-blockComment2"); - Start("err-varDefinition"); - Start("err-varDefinition2"); - Start("err-varDefinition3"); - Start("err-varDefinition4"); - Start("err-varDefinition5"); - Start("err-varDefinition6"); - Start("err-varDefinition7"); - Start("err-varDefinition8"); - Start("err-varDefinition9"); - Start("err-variableRef"); - Start("err-variableRef2"); - Start("err-variableRef3"); - Start("err-variableRef4"); - Start("err-cycle1"); - Start("input"); - Start("input2"); - Start("pass-blockComment"); - Start("pass-lineComment"); - Start("pass-lineComment2"); - Start("pass-noBlockComments"); - Start("pass-noLineComments"); - Start("pass-varDefinition"); - Start("pass-varDefinition2"); - Start("pass-varDefinition3"); - Start("pass-varDefinition4"); - Start("pass-command-and-comment"); - Assert.False(testFailed, "At least one of test cases failed. Check output for details."); - } - public void TestParser(string filename, StringBuilder output) { try @@ -620,7 +571,6 @@ GO"; Console.WriteLine(":: To update the baseline:"); Console.WriteLine("copy \"" + outputFilename + "\" \"" + baselineFilename + "\""); Console.WriteLine(); - testFailed = true; } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/BackupServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/BackupServiceTests.cs index 385d42f3..e7abed8c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/BackupServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/BackupServiceTests.cs @@ -45,27 +45,28 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; ///[Fact] public async void GetBackupConfigInfoTest() { - string databaseName = "testbackup_" + new Random().Next(10000000, 99999999); - SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); - var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); - - var requestContext = new Mock>(); - requestContext.Setup(x => x.SendResult(It.IsAny())) - .Returns(Task.FromResult(new object())); - - var dbParams = new DefaultDatabaseInfoParams + string databaseName = "testbackup_" + new Random().Next(10000000, 99999999); + using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName)) { - OwnerUri = liveConnection.ConnectionInfo.OwnerUri - }; - DisasterRecoveryService service = new DisasterRecoveryService(); - await service.HandleBackupConfigInfoRequest(dbParams, requestContext.Object); + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); - requestContext.Verify(x => x.SendResult(It.Is - (p => p.BackupConfigInfo.RecoveryModel != string.Empty - && p.BackupConfigInfo.DefaultBackupFolder != string.Empty))); - - testDb.Cleanup(); + var requestContext = new Mock>(); + requestContext.Setup(x => x.SendResult(It.IsAny())) + .Returns(Task.FromResult(new object())); + + var dbParams = new DefaultDatabaseInfoParams + { + OwnerUri = liveConnection.ConnectionInfo.OwnerUri + }; + + DisasterRecoveryService service = new DisasterRecoveryService(); + await service.HandleBackupConfigInfoRequest(dbParams, requestContext.Object); + + requestContext.Verify(x => x.SendResult(It.Is + (p => p.BackupConfigInfo.RecoveryModel != string.Empty + && p.BackupConfigInfo.DefaultBackupFolder != string.Empty))); + } } /// @@ -76,14 +77,12 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; { DisasterRecoveryService service = new DisasterRecoveryService(); string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); - SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); - try + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); + using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName)) + using (DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true)) + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); - DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true); - SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo); - string backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn); BackupInfo backupInfo = CreateDefaultBackupInfo(databaseName, @@ -95,12 +94,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; // Backup the database service.PerformBackup(backupOperation); - VerifyAndCleanBackup(backupPath); - sqlConn.Close(); - } - finally - { - testDb.Cleanup(); + VerifyAndCleanBackup(sqlConn, backupPath); } } @@ -109,13 +103,12 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; { DisasterRecoveryService service = new DisasterRecoveryService(); string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); - SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); - try + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); + using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName)) + using (DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true)) + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); - DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true); - SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo); string backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn); @@ -133,15 +126,10 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; // Execute the script testDb.RunQuery(script); - VerifyAndCleanBackup(backupPath); - sqlConn.Close(); - } - finally - { - testDb.Cleanup(); + VerifyAndCleanBackup(sqlConn, backupPath); } } - + /// /// Test creating backup with advanced options set. /// @@ -150,13 +138,12 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; { DisasterRecoveryService service = new DisasterRecoveryService(); string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); - SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); - try + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); + using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName)) + using (DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true)) + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); - DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true); - SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo); string backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn); string certificateName = CreateCertificate(testDb); @@ -186,19 +173,11 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; // Remove the backup file Console.WriteLine("Verify the backup file exists and remove.."); - VerifyAndCleanBackup(backupPath); + VerifyAndCleanBackup(sqlConn, backupPath); // Delete certificate and master key Console.WriteLine("Remove certificate and master key.."); testDb.RunQuery(cleanupCertificateQuery); - - sqlConn.Close(); - } - finally - { - // Clean up the database - Console.WriteLine("Clean up database.."); - testDb.Cleanup(); } } @@ -210,13 +189,12 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; { DisasterRecoveryService service = new DisasterRecoveryService(); string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); - SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); - try + var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); + using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName)) + using (DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true)) + using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { - var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); - DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true); - SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo); string backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn); string certificateName = CreateCertificate(testDb); @@ -248,18 +226,11 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; // Remove the backup file Console.WriteLine("Verify the backup file exists and remove.."); - VerifyAndCleanBackup(backupPath); + VerifyAndCleanBackup(sqlConn, backupPath); // Delete certificate and master key Console.WriteLine("Remove certificate and master key.."); testDb.RunQuery(cleanupCertificateQuery); - sqlConn.Close(); - } - finally - { - // Clean up the database - Console.WriteLine("Clean up database.."); - testDb.Cleanup(); } } @@ -270,9 +241,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; public void ScriptBackupWithDifferentActionTypesTest() { string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); - SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); - - try + using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName)) { // Create Full backup script string script = GenerateScriptForBackupType(BackupType.Full, databaseName); @@ -298,12 +267,6 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; Assert.DoesNotContain("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase); Assert.Contains("WITH DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase); } - finally - { - // Clean up the database - Console.WriteLine("Clean up database.."); - testDb.Cleanup(); - } } //[Fact] @@ -366,7 +329,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; Assert.True(eventParams.Children.Length > 0); }) .Complete(); - + // Expand the node in file browser await service.RunFileBrowserExpandTask(expandParams, expandEventFlowValidator.Object); @@ -383,7 +346,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; var validateEventFlowValidator = new EventFlowValidator() .AddEventValidation(FileBrowserValidatedNotification.Type, eventParams => Assert.True(eventParams.Succeeded)) .Complete(); - + // Validate selected files in the browser await service.RunFileBrowserValidateTask(validateParams, validateEventFlowValidator.Object); @@ -404,7 +367,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; string certificateName = "backupcertificate" + new Random().Next(10000000, 99999999); string masterkeyPassword = Guid.NewGuid().ToString(); string createCertificateQuery = string.Format(CreateCertificateQueryFormat, masterkeyPassword, certificateName); - + // create master key and certificate Console.WriteLine("Create master key and certificate.."); testDb.RunQuery(createCertificateQuery); @@ -444,16 +407,42 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; return service.CreateBackupOperation(dataContainer, sqlConn, backupParams.BackupInfo); } - private void VerifyAndCleanBackup(string backupPath) + private void VerifyAndCleanBackup(SqlConnection sqlConn, string backupPath) { - // Verify it created backup - Assert.True(File.Exists(backupPath)); - - // Remove the backup file - if (File.Exists(backupPath)) + try { - File.Delete(backupPath); + sqlConn.Open(); + using (SqlCommand sqlCmd = sqlConn.CreateCommand()) + { + sqlCmd.CommandText = @" +DECLARE @Files TABLE + (fileName nvarchar(max) + ,depth int + ,isFile int) + +INSERT INTO @Files +EXEC xp_dirtree @Path,1,1 + +SELECT CASE WHEN COUNT(*) > 0 THEN 'true' ELSE 'false' END FROM @Files where isFile=1 and fileName=@FileName"; + sqlCmd.Parameters.AddWithValue("@Path", Path.GetDirectoryName(backupPath)); + sqlCmd.Parameters.AddWithValue("@FileName", Path.GetFileName(backupPath)); + var ret = bool.Parse(sqlCmd.ExecuteScalar().ToString()); + + // Verify it created backup + Assert.True(ret, $"Backup file {backupPath} was not created"); + } } + finally + { + using (SqlCommand sqlCmd = sqlConn.CreateCommand()) + { + sqlCmd.CommandText = "EXECUTE master.dbo.xp_delete_file 0,@Path"; + sqlCmd.Parameters.AddWithValue("@Path", backupPath); + sqlCmd.ExecuteNonQuery(); + } + } + + } private bool ContainsFileInTheFolder(FileTreeNode folderNode, string filePath) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceTests.cs index a4de186a..7d9b857c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceTests.cs @@ -1150,7 +1150,7 @@ WITH VALUES } retry--; } - Assert.Equal(false, TaskService.Instance.TaskManager.Tasks.Any()); + Assert.False(TaskService.Instance.TaskManager.Tasks.Any(), $"No tasks were expected to exist but had {TaskService.Instance.TaskManager.Tasks.Count} [{string.Join(",", TaskService.Instance.TaskManager.Tasks.Select(t => t.TaskId))}]"); TaskService.Instance.TaskManager.Reset(); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareTestUtils.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareTestUtils.cs index 69ef1cc7..b737fb1f 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareTestUtils.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareTestUtils.cs @@ -22,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SchemaCompare internal static void VerifyAndCleanup(string filePath) { // Verify it was created - Assert.True(File.Exists(filePath)); + Assert.True(File.Exists(filePath), $"File {filePath} was expected to exist but did not"); // Remove the file if (File.Exists(filePath))