Test fixes (#877)

* Test fixes

* Delete unneeded using
This commit is contained in:
Charles Gagnon
2019-10-16 10:43:12 -07:00
committed by GitHub
parent 96593d66e3
commit 6f17c15d2c
5 changed files with 128 additions and 189 deletions

View File

@@ -1472,7 +1472,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
/// <param name="connInfo">The connection info to connect with</param> /// <param name="connInfo">The connection info to connect with</param>
/// <param name="featureName">A plaintext string that will be included in the application name for the connection</param> /// <param name="featureName">A plaintext string that will be included in the application name for the connection</param>
/// <returns>A SqlConnection created with the given connection info</returns> /// <returns>A SqlConnection created with the given connection info</returns>
internal static SqlConnection OpenSqlConnection(ConnectionInfo connInfo, string featureName = null) public static SqlConnection OpenSqlConnection(ConnectionInfo connInfo, string featureName = null)
{ {
try try
{ {

View File

@@ -15,15 +15,13 @@ using System.Globalization;
using System.IO; using System.IO;
using System.Text; using System.Text;
using Xunit; using Xunit;
using Microsoft.SqlTools.ServiceLayer.Connection;
using System.Threading.Tasks;
namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
{ {
public class BatchParserTests : BaselinedTest 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() public BatchParserTests()
{ {
InitializeTest(); InitializeTest();
@@ -150,15 +148,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
public void VerifyExecute() public void VerifyExecute()
{ {
Batch batch = new Batch(sqlText: "SELECT 1+1", isResultExpected: true, execTimeout: 15); 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(); var executionResult = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
if (con.State.ToString().ToLower() == "open") Assert.Equal<ScriptExecutionResult>(ScriptExecutionResult.Success, executionResult);
{
executionResult = batch.Execute(con, ShowPlanType.AllShowPlan);
}
} }
Assert.Equal<ScriptExecutionResult>(ScriptExecutionResult.Success, executionResult);
} }
// Verify the exeception is handled by passing invalid keyword. // Verify the exeception is handled by passing invalid keyword.
@@ -166,13 +162,10 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
public void VerifyHandleExceptionMessage() public void VerifyHandleExceptionMessage()
{ {
Batch batch = new Batch(sqlText: "SEL@ECT 1+1", isResultExpected: true, execTimeout: 15); 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(); ScriptExecutionResult result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
if (con.State.ToString().ToLower() == "open")
{
ScriptExecutionResult result = batch.Execute(con, ShowPlanType.AllShowPlan);
}
} }
ScriptExecutionResult finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; 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); Batch batch = new Batch(sqlText: null, isResultExpected: true, execTimeout: 15);
ScriptExecutionResult finalResult = ScriptExecutionResult.All; 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(); ScriptExecutionResult result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
if (con.State.ToString().ToLower() == "open")
{
ScriptExecutionResult result = batch.Execute(con, ShowPlanType.AllShowPlan);
}
} }
finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure;
@@ -204,19 +194,19 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
{ {
ScriptExecutionResult result = ScriptExecutionResult.All; ScriptExecutionResult result = ScriptExecutionResult.All;
Batch batch = new Batch(sqlText: "SELECT 1+1", isResultExpected: true, execTimeout: 15); 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(); batch.Cancel();
if (con.State.ToString().ToLower() == "open") result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
{
batch.Cancel();
result = batch.Execute(con, ShowPlanType.AllShowPlan);
}
} }
Assert.Equal<ScriptExecutionResult>(result, ScriptExecutionResult.Cancel); Assert.Equal<ScriptExecutionResult>(result, ScriptExecutionResult.Cancel);
} }
// verify weather lexer can consume token for SqlCmd variable //
/// <summary>
/// Verify whether lexer can consume token for SqlCmd variable
/// </summary>
[Fact] [Fact]
public void VerifyLexerSetState() public void VerifyLexerSetState()
{ {
@@ -228,14 +218,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
{ {
lexer.ConsumeToken(); 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 // we doesn't expect any exception or testCase failures
Assert.Equal<ScriptExecutionResult>(ScriptExecutionResult.Success, executionResult);
} }
// This test case is to verify that, Powershell's Invoke-SqlCmd handles ":!!if" in an inconsistent way // 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 string query = @"SELECT 1+2
Go 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, sqlConn, new ExecutionEngineConditions());
TestExecutor testExecutor = new TestExecutor(query, con, new ExecutionEngineConditions());
testExecutor.Run(); testExecutor.Run();
ScriptExecutionResult result = (testExecutor.ExecutionResult == ScriptExecutionResult.Success) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; 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()) using (ExecutionEngine executionEngine = new ExecutionEngine())
{ {
string query = @"sqlcmd -Q ""select 1 + 2 as col"" "; 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, sqlConn, new ExecutionEngineConditions());
TestExecutor testExecutor = new TestExecutor(query, con, new ExecutionEngineConditions());
testExecutor.Run(); testExecutor.Run();
Assert.True(testExecutor.ResultCountQueue.Count >= 1); Assert.True(testExecutor.ResultCountQueue.Count >= 1);
} }
@@ -360,16 +349,15 @@ GO
select $(__var1) + $(__var2) as col select $(__var1) + $(__var2) as col
GO"; 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(); testExecutor.Run();
Assert.True(testExecutor.ResultCountQueue.Count >= 1); Assert.True(testExecutor.ResultCountQueue.Count >= 1, $"Unexpected number of ResultCount items - expected 0 but got {testExecutor.ResultCountQueue.Count}");
Assert.True(testExecutor.ErrorMessageQueue.Count == 0); 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()) using (ExecutionEngine executionEngine = new ExecutionEngine())
{ {
string query = "SELECT 1+2"; 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(); var executionPromise = new TaskCompletionSource<bool>();
executionEngine.BatchParserExecutionFinished += (object sender, BatchParserExecutionFinishedEventArgs e) =>
executionEngine.BatchParserExecutionFinished += OnBatchParserExecutionFinished; {
executionEngine.ExecuteBatch(new ScriptExecutionArgs(query, con, 15, new ExecutionEngineConditions(), new BatchParserMockEventHandler())); Assert.Equal(ScriptExecutionResult.Success, e.ExecutionResult);
Assert.Equal(ScriptExecutionResult.Success, 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] [Fact]
public void CanceltheBatch() public void CanceltheBatch()
{ {
@@ -489,42 +476,6 @@ GO";
FileUtilities.SetFileReadWrite(filename); 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) public void TestParser(string filename, StringBuilder output)
{ {
try try
@@ -620,7 +571,6 @@ GO";
Console.WriteLine(":: To update the baseline:"); Console.WriteLine(":: To update the baseline:");
Console.WriteLine("copy \"" + outputFilename + "\" \"" + baselineFilename + "\""); Console.WriteLine("copy \"" + outputFilename + "\" \"" + baselineFilename + "\"");
Console.WriteLine(); Console.WriteLine();
testFailed = true;
} }
} }
} }

View File

@@ -45,27 +45,28 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
///[Fact] ///[Fact]
public async void GetBackupConfigInfoTest() public async void GetBackupConfigInfoTest()
{ {
string databaseName = "testbackup_" + new Random().Next(10000000, 99999999); string databaseName = "testbackup_" + new Random().Next(10000000, 99999999);
SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName))
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);
var requestContext = new Mock<RequestContext<BackupConfigInfoResponse>>();
requestContext.Setup(x => x.SendResult(It.IsAny<BackupConfigInfoResponse>()))
.Returns(Task.FromResult(new object()));
var dbParams = new DefaultDatabaseInfoParams
{ {
OwnerUri = liveConnection.ConnectionInfo.OwnerUri
};
DisasterRecoveryService service = new DisasterRecoveryService(); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);
await service.HandleBackupConfigInfoRequest(dbParams, requestContext.Object);
requestContext.Verify(x => x.SendResult(It.Is<BackupConfigInfoResponse> var requestContext = new Mock<RequestContext<BackupConfigInfoResponse>>();
(p => p.BackupConfigInfo.RecoveryModel != string.Empty requestContext.Setup(x => x.SendResult(It.IsAny<BackupConfigInfoResponse>()))
&& p.BackupConfigInfo.DefaultBackupFolder != string.Empty))); .Returns(Task.FromResult(new object()));
testDb.Cleanup(); 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<BackupConfigInfoResponse>
(p => p.BackupConfigInfo.RecoveryModel != string.Empty
&& p.BackupConfigInfo.DefaultBackupFolder != string.Empty)));
}
} }
/// <summary> /// <summary>
@@ -76,14 +77,12 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
{ {
DisasterRecoveryService service = new DisasterRecoveryService(); DisasterRecoveryService service = new DisasterRecoveryService();
string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); 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 backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);
BackupInfo backupInfo = CreateDefaultBackupInfo(databaseName, BackupInfo backupInfo = CreateDefaultBackupInfo(databaseName,
@@ -95,12 +94,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
// Backup the database // Backup the database
service.PerformBackup(backupOperation); service.PerformBackup(backupOperation);
VerifyAndCleanBackup(backupPath); VerifyAndCleanBackup(sqlConn, backupPath);
sqlConn.Close();
}
finally
{
testDb.Cleanup();
} }
} }
@@ -109,13 +103,12 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
{ {
DisasterRecoveryService service = new DisasterRecoveryService(); DisasterRecoveryService service = new DisasterRecoveryService();
string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); 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 backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);
@@ -133,15 +126,10 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
// Execute the script // Execute the script
testDb.RunQuery(script); testDb.RunQuery(script);
VerifyAndCleanBackup(backupPath); VerifyAndCleanBackup(sqlConn, backupPath);
sqlConn.Close();
}
finally
{
testDb.Cleanup();
} }
} }
/// <summary> /// <summary>
/// Test creating backup with advanced options set. /// Test creating backup with advanced options set.
/// </summary> /// </summary>
@@ -150,13 +138,12 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
{ {
DisasterRecoveryService service = new DisasterRecoveryService(); DisasterRecoveryService service = new DisasterRecoveryService();
string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); 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 backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);
string certificateName = CreateCertificate(testDb); string certificateName = CreateCertificate(testDb);
@@ -186,19 +173,11 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
// Remove the backup file // Remove the backup file
Console.WriteLine("Verify the backup file exists and remove.."); Console.WriteLine("Verify the backup file exists and remove..");
VerifyAndCleanBackup(backupPath); VerifyAndCleanBackup(sqlConn, backupPath);
// Delete certificate and master key // Delete certificate and master key
Console.WriteLine("Remove certificate and master key.."); Console.WriteLine("Remove certificate and master key..");
testDb.RunQuery(cleanupCertificateQuery); 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(); DisasterRecoveryService service = new DisasterRecoveryService();
string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); 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 backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);
string certificateName = CreateCertificate(testDb); string certificateName = CreateCertificate(testDb);
@@ -248,18 +226,11 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
// Remove the backup file // Remove the backup file
Console.WriteLine("Verify the backup file exists and remove.."); Console.WriteLine("Verify the backup file exists and remove..");
VerifyAndCleanBackup(backupPath); VerifyAndCleanBackup(sqlConn, backupPath);
// Delete certificate and master key // Delete certificate and master key
Console.WriteLine("Remove certificate and master key.."); Console.WriteLine("Remove certificate and master key..");
testDb.RunQuery(cleanupCertificateQuery); 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() public void ScriptBackupWithDifferentActionTypesTest()
{ {
string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999);
SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName))
try
{ {
// Create Full backup script // Create Full backup script
string script = GenerateScriptForBackupType(BackupType.Full, databaseName); 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.DoesNotContain("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase);
Assert.Contains("WITH DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase); Assert.Contains("WITH DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase);
} }
finally
{
// Clean up the database
Console.WriteLine("Clean up database..");
testDb.Cleanup();
}
} }
//[Fact] //[Fact]
@@ -366,7 +329,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
Assert.True(eventParams.Children.Length > 0); Assert.True(eventParams.Children.Length > 0);
}) })
.Complete(); .Complete();
// Expand the node in file browser // Expand the node in file browser
await service.RunFileBrowserExpandTask(expandParams, expandEventFlowValidator.Object); await service.RunFileBrowserExpandTask(expandParams, expandEventFlowValidator.Object);
@@ -383,7 +346,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
var validateEventFlowValidator = new EventFlowValidator<bool>() var validateEventFlowValidator = new EventFlowValidator<bool>()
.AddEventValidation(FileBrowserValidatedNotification.Type, eventParams => Assert.True(eventParams.Succeeded)) .AddEventValidation(FileBrowserValidatedNotification.Type, eventParams => Assert.True(eventParams.Succeeded))
.Complete(); .Complete();
// Validate selected files in the browser // Validate selected files in the browser
await service.RunFileBrowserValidateTask(validateParams, validateEventFlowValidator.Object); 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 certificateName = "backupcertificate" + new Random().Next(10000000, 99999999);
string masterkeyPassword = Guid.NewGuid().ToString(); string masterkeyPassword = Guid.NewGuid().ToString();
string createCertificateQuery = string.Format(CreateCertificateQueryFormat, masterkeyPassword, certificateName); string createCertificateQuery = string.Format(CreateCertificateQueryFormat, masterkeyPassword, certificateName);
// create master key and certificate // create master key and certificate
Console.WriteLine("Create master key and certificate.."); Console.WriteLine("Create master key and certificate..");
testDb.RunQuery(createCertificateQuery); testDb.RunQuery(createCertificateQuery);
@@ -444,16 +407,42 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
return service.CreateBackupOperation(dataContainer, sqlConn, backupParams.BackupInfo); return service.CreateBackupOperation(dataContainer, sqlConn, backupParams.BackupInfo);
} }
private void VerifyAndCleanBackup(string backupPath) private void VerifyAndCleanBackup(SqlConnection sqlConn, string backupPath)
{ {
// Verify it created backup try
Assert.True(File.Exists(backupPath));
// Remove the backup file
if (File.Exists(backupPath))
{ {
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) private bool ContainsFileInTheFolder(FileTreeNode folderNode, string filePath)

View File

@@ -1150,7 +1150,7 @@ WITH VALUES
} }
retry--; 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(); TaskService.Instance.TaskManager.Reset();
} }
} }

View File

@@ -22,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SchemaCompare
internal static void VerifyAndCleanup(string filePath) internal static void VerifyAndCleanup(string filePath)
{ {
// Verify it was created // 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 // Remove the file
if (File.Exists(filePath)) if (File.Exists(filePath))