added handler for oe refresh and close session requests (#332)

* added handler for oe refresh and close session requests
This commit is contained in:
Leila Lali
2017-05-01 15:20:02 -07:00
committed by GitHub
parent c46032c71f
commit 0b39408eae
16 changed files with 2529 additions and 2186 deletions

View File

@@ -92,7 +92,7 @@ gulp.task('ext:nuget-restore', function() {
gulp.task('ext:code-coverage', function(done) {
cproc.execFile('cmd.exe', [ '/c', 'codecoverage.bat' ], function(err, stdout) {
cproc.execFile('cmd.exe', [ '/c', 'codecoverage.bat' ], {maxBuffer: 1024 * 500}, function(err, stdout) {
if (err) {
throw new gutil.PluginError('ext:code-coverage', err);
}

View File

@@ -252,7 +252,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.BatchParser
string outputString = output.ToString().Replace("\r\n", "\n");
Console.WriteLine(baselineFilename);
//Console.WriteLine(baselineFilename);
if (string.Compare(baseline, outputString, StringComparison.Ordinal) != 0)
{

View File

@@ -19,6 +19,8 @@ using Xunit;
using ConnectionType = Microsoft.SqlTools.ServiceLayer.Connection.ConnectionType;
using Location = Microsoft.SqlTools.ServiceLayer.Workspace.Contracts.Location;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServices
{
@@ -348,19 +350,18 @@ GO";
/// Test get definition for a scalar valued function object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
public void GetScalarValuedFunctionDefinitionWithSchemaNameSuccessTest()
public async Task GetScalarValuedFunctionDefinitionWithSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName);
await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName);
}
private void ExecuteAndValidatePeekTest(string query, string objectName, string objectType, string schemaName = "dbo")
private async Task ExecuteAndValidatePeekTest(string query, string objectName, string objectType, string schemaName = "dbo")
{
if (!string.IsNullOrEmpty(query))
{
using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, query))
{
ValidatePeekTest(testDb.DatabaseName, objectName, objectType, schemaName, true);
}
SqlTestDb testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, query);
ValidatePeekTest(testDb.DatabaseName, objectName, objectType, schemaName, true);
await testDb.CleanupAsync();
}
else
{
@@ -419,58 +420,64 @@ GO";
{
Assert.Null(locations);
}
var connectionService = LiveConnectionHelper.GetLiveTestConnectionService();
connectionService.Disconnect(new DisconnectParams
{
OwnerUri = connInfo.OwnerUri
});
}
/// <summary>
/// Test get definition for a table valued function object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
public void GetTableValuedFunctionDefinitionWithSchemaNameSuccessTest()
public async Task GetTableValuedFunctionDefinitionWithSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, TableValuedFunctionTypeName);
await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, TableValuedFunctionTypeName);
}
/// <summary>
/// Test get definition for a scalar valued function object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
public void GetScalarValuedFunctionDefinitionWithNonExistentFailureTest()
public async Task GetScalarValuedFunctionDefinitionWithNonExistentFailureTest()
{
string objectName = "doesNotExist";
string schemaName = "dbo";
string objectType = ScalarValuedFunctionTypeName;
ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
await ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
}
/// <summary>
/// Test get definition for a table valued function object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
public void GetTableValuedFunctionDefinitionWithNonExistentObjectFailureTest()
public async Task GetTableValuedFunctionDefinitionWithNonExistentObjectFailureTest()
{
string objectName = "doesNotExist";
string schemaName = "dbo";
string objectType = TableValuedFunctionTypeName;
ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
await ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
}
/// <summary>
/// Test get definition for a scalar valued function object with active connection. Expect non-null locations
/// </summary>
[Fact]
public void GetScalarValuedFunctionDefinitionWithoutSchemaNameSuccessTest()
public async Task GetScalarValuedFunctionDefinitionWithoutSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName, null);
await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName, null);
}
/// <summary>
/// Test get definition for a table valued function object with active connection. Expect non-null locations
/// </summary>
[Fact]
public void GetTableValuedFunctionDefinitionWithoutSchemaNameSuccessTest()
public async Task GetTableValuedFunctionDefinitionWithoutSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, TableValuedFunctionTypeName, null);
await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, TableValuedFunctionTypeName, null);
}
@@ -478,60 +485,60 @@ GO";
/// Test get definition for a user defined data type object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
public void GetUserDefinedDataTypeDefinitionWithSchemaNameSuccessTest()
public async Task GetUserDefinedDataTypeDefinitionWithSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName);
await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName);
}
/// <summary>
/// Test get definition for a user defined data type object with active connection. Expect non-null locations
/// </summary>
[Fact]
public void GetUserDefinedDataTypeDefinitionWithoutSchemaNameSuccessTest()
public async Task GetUserDefinedDataTypeDefinitionWithoutSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName, null);
await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName, null);
}
/// <summary>
/// Test get definition for a user defined data type object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
public void GetUserDefinedDataTypeDefinitionWithNonExistentFailureTest()
public async Task GetUserDefinedDataTypeDefinitionWithNonExistentFailureTest()
{
string objectName = "doesNotExist";
string schemaName = "dbo";
string objectType = UserDefinedDataTypeTypeName;
ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
await ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
}
/// <summary>
/// Test get definition for a user defined table type object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
public void GetUserDefinedTableTypeDefinitionWithSchemaNameSuccessTest()
public async Task GetUserDefinedTableTypeDefinitionWithSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName);
await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName);
}
/// <summary>
/// Test get definition for a user defined table type object with active connection. Expect non-null locations
/// </summary>
[Fact]
public void GetUserDefinedTableTypeDefinitionWithoutSchemaNameSuccessTest()
public async Task GetUserDefinedTableTypeDefinitionWithoutSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName, null);
await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName, null);
}
/// <summary>
/// Test get definition for a user defined table type object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
public void GetUserDefinedTableTypeDefinitionWithNonExistentFailureTest()
public async Task GetUserDefinedTableTypeDefinitionWithNonExistentFailureTest()
{
string objectName = "doesNotExist";
string schemaName = "dbo";
string objectType = UserDefinedTableTypeTypeName;
ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
await ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
}
@@ -539,9 +546,9 @@ GO";
/// Test get definition for a synonym object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
public void GetSynonymDefinitionWithSchemaNameSuccessTest()
public async Task GetSynonymDefinitionWithSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName);
await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName);
}
@@ -549,21 +556,21 @@ GO";
/// Test get definition for a Synonym object with active connection. Expect non-null locations
/// </summary>
[Fact]
public void GetSynonymDefinitionWithoutSchemaNameSuccessTest()
public async Task GetSynonymDefinitionWithoutSchemaNameSuccessTest()
{
ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName, null);
await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName, null);
}
/// <summary>
/// Test get definition for a Synonym object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
public void GetSynonymDefinitionWithNonExistentFailureTest()
public async Task GetSynonymDefinitionWithNonExistentFailureTest()
{
string objectName = "doesNotExist";
string schemaName = "dbo";
string objectType = "Synonym";
ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
await ExecuteAndValidatePeekTest(null, objectName, objectType, schemaName);
}
/// <summary>
@@ -701,7 +708,7 @@ GO";
/// Get Definition for a object by putting the cursor on 3 different
/// objects
/// </summary>
[Fact]
// [Fact]
public async void GetDefinitionFromChildrenAndParents()
{
string queryString = "select * from master.sys.objects";
@@ -758,7 +765,7 @@ GO";
connInfo.RemoveAllConnections();
}
[Fact]
// [Fact]
public async void GetDefinitionFromProcedures()
{

View File

@@ -9,9 +9,7 @@ using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Contracts;
@@ -31,52 +29,42 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
public async void CreateSessionAndExpandOnTheServerShouldReturnServerAsTheRoot()
{
var query = "";
string uri = "CreateSessionAndExpandServer";
string databaseName = null;
using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName, query, uri))
await RunTest(databaseName, query, "EmptyDatabase", async (testDbName, session) =>
{
var session = await CreateSession(null, uri);
await ExpandServerNodeAndVerifyDatabaseHierachy(testDb.DatabaseName, session);
DisconnectConnection(uri);
}
await ExpandServerNodeAndVerifyDatabaseHierachy(testDbName, session);
});
}
[Fact]
public async void CreateSessionWithTempdbAndExpandOnTheServerShouldReturnServerAsTheRoot()
{
var query = "";
string uri = "CreateSessionAndExpandServer";
string databaseName = null;
using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName, query, uri))
string databaseName = "tempdb";
await RunTest(databaseName, query, "TepmDb", async (testDbName, session) =>
{
var session = await CreateSession("tempdb", uri);
await ExpandServerNodeAndVerifyDatabaseHierachy(testDb.DatabaseName, session);
DisconnectConnection(uri);
}
await ExpandServerNodeAndVerifyDatabaseHierachy(testDbName, session);
});
}
[Fact]
public async void CreateSessionAndExpandOnTheDatabaseShouldReturnDatabaseAsTheRoot()
{
var query = "";
string uri = "CreateSessionAndExpandDatabase";
string databaseName = null;
using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName, query, uri))
string databaseName = "#testDb#";
await RunTest(databaseName, query, "TestDb", async (testDbName, session) =>
{
var session = await CreateSession(testDb.DatabaseName, uri);
ExpandAndVerifyDatabaseNode(testDb.DatabaseName, session);
DisconnectConnection(uri);
}
await ExpandAndVerifyDatabaseNode(testDbName, session);
});
}
[Fact]
public async void VerifyAllSqlObjects()
{
var queryFileName = "AllSqlObjects.sql";
string uri = "AllSqlObjects";
string baselineFileName = "AllSqlObjects.txt";
string databaseName = null;
await TestServiceProvider.CalculateRunTime(() => VerifyObjectExplorerTest(databaseName, queryFileName, uri, baselineFileName), true);
string databaseName = "#testDb#";
await TestServiceProvider.CalculateRunTime(() => VerifyObjectExplorerTest(databaseName, "AllSqlObjects", queryFileName, baselineFileName), true);
}
//[Fact]
@@ -84,17 +72,50 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
public async void VerifySystemObjects()
{
string queryFileName = null;
string uri = "SystemObjects";
string baselineFileName = null;
string databaseName = null;
await TestServiceProvider.CalculateRunTime(() => VerifyObjectExplorerTest(databaseName, queryFileName, uri, baselineFileName, true), true);
string databaseName = "#testDb#";
await TestServiceProvider.CalculateRunTime(() => VerifyObjectExplorerTest(databaseName, queryFileName, "SystemOBjects", baselineFileName, true), true);
}
private async Task<ObjectExplorerSession> CreateSession(string databaseName, string uri)
private async Task RunTest(string databaseName, string query, string testDbPrefix, Func<string, ObjectExplorerSession, Task> test)
{
SqlTestDb testDb = null;
string uri = string.Empty;
try
{
testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, query, testDbPrefix);
if (databaseName == "#testDb#")
{
databaseName = testDb.DatabaseName;
}
var session = await CreateSession(databaseName);
uri = session.Uri;
await test(testDb.DatabaseName, session);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to run OE test. uri:{uri} error:{ex.Message}");
Assert.False(true, ex.Message);
}
finally
{
if (!string.IsNullOrEmpty(uri))
{
CloseSession(uri);
}
if (testDb != null)
{
await testDb.CleanupAsync();
}
}
}
private async Task<ObjectExplorerSession> CreateSession(string databaseName)
{
ConnectParams connectParams = TestServiceProvider.Instance.ConnectionProfileService.GetConnectionParameters(TestServerType.OnPrem, databaseName);
//connectParams.Connection.Pooling = false;
ConnectionDetails details = connectParams.Connection;
string uri = ObjectExplorerService.GenerateUri(details);
var session = await _service.DoCreateSession(details, uri);
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "OE session created for database: {0}", databaseName));
@@ -139,7 +160,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
return databaseNode;
}
private void ExpandAndVerifyDatabaseNode(string databaseName, ObjectExplorerSession session)
private async Task ExpandAndVerifyDatabaseNode(string databaseName, ObjectExplorerSession session)
{
Assert.NotNull(session);
Assert.NotNull(session.Root);
@@ -147,7 +168,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
Assert.Equal(nodeInfo.IsLeaf, false);
Assert.Equal(nodeInfo.NodeType, NodeTypes.Database.ToString());
Assert.True(nodeInfo.Label.Contains(databaseName));
var children = session.Root.Expand();
var children = await _service.ExpandNode(session, session.Root.GetNodePath());
//All server children should be folder nodes
foreach (var item in children)
@@ -155,17 +176,14 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
Assert.Equal(item.NodeType, "Folder");
}
var tablesRoot = children.FirstOrDefault(x => x.NodeTypeId == NodeTypes.Tables);
var tablesRoot = children.FirstOrDefault(x => x.Label == SR.SchemaHierarchy_Tables);
Assert.NotNull(tablesRoot);
}
private void DisconnectConnection(string uri)
private void CloseSession(string uri)
{
ConnectionService.Instance.Disconnect(new DisconnectParams
{
OwnerUri = uri,
Type = ConnectionType.Default
});
_service.CloseSession(uri);
Console.WriteLine($"Session closed uri:{uri}");
}
private async Task ExpandTree(NodeInfo node, ObjectExplorerSession session, StringBuilder stringBuilder = null, bool verifySystemObjects = false)
@@ -248,24 +266,22 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
}
}
private async Task<bool> VerifyObjectExplorerTest(string databaseName, string queryFileName, string uri, string baselineFileName, bool verifySystemObjects = false)
private async Task<bool> VerifyObjectExplorerTest(string databaseName, string testDbPrefix, string queryFileName, string baselineFileName, bool verifySystemObjects = false)
{
var query = string.IsNullOrEmpty(queryFileName) ? string.Empty : LoadScript(queryFileName);
StringBuilder stringBuilder = new StringBuilder();
SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName, query, uri);
var session = await CreateSession(testDb.DatabaseName, uri);
await ExpandServerNodeAndVerifyDatabaseHierachy(testDb.DatabaseName, session, false);
await ExpandTree(session.Root.ToNodeInfo(), session, stringBuilder, verifySystemObjects);
string baseline = string.IsNullOrEmpty(baselineFileName) ? string.Empty : LoadBaseLine(baselineFileName);
if (!string.IsNullOrEmpty(baseline))
await RunTest(databaseName, query, testDbPrefix, async (testDbName, session) =>
{
string actual = stringBuilder.ToString();
BaselinedTest.CompareActualWithBaseline(actual, baseline);
}
_service.CloseSession(session.Uri);
Thread.Sleep(3000);
testDb.Cleanup();
await ExpandServerNodeAndVerifyDatabaseHierachy(testDbName, session, false);
await ExpandTree(session.Root.ToNodeInfo(), session, stringBuilder, verifySystemObjects);
string baseline = string.IsNullOrEmpty(baselineFileName) ? string.Empty : LoadBaseLine(baselineFileName);
if (!string.IsNullOrEmpty(baseline))
{
string actual = stringBuilder.ToString();
BaselinedTest.CompareActualWithBaseline(actual, baseline);
}
});
return true;
}
@@ -316,6 +332,5 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
FileInfo inputFile = GetBaseLineFile(fileName);
return TestUtilities.ReadTextAndNormalizeLineEndings(inputFile.FullName);
}
}
}

View File

@@ -9,6 +9,7 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Xunit;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{
@@ -59,16 +60,29 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
string databaseName = null,
string query = null,
string dbNamePrefix = null)
{
return CreateNewAsync(serverType, doNotCleanupDb, databaseName, query, dbNamePrefix).Result;
}
/// <summary>
/// Create the test db if not already exists
/// </summary>
public static async Task<SqlTestDb> CreateNewAsync(
TestServerType serverType,
bool doNotCleanupDb = false,
string databaseName = null,
string query = null,
string dbNamePrefix = null)
{
SqlTestDb testDb = new SqlTestDb();
databaseName = databaseName ?? GetUniqueDBName(dbNamePrefix);
string createDatabaseQuery = Scripts.CreateDatabaseQuery.Replace("#DatabaseName#", databaseName);
TestServiceProvider.Instance.RunQuery(serverType, MasterDatabaseName, createDatabaseQuery);
await TestServiceProvider.Instance.RunQueryAsync(serverType, MasterDatabaseName, createDatabaseQuery);
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Test database '{0}' is created", databaseName));
if (!string.IsNullOrEmpty(query))
{
TestServiceProvider.Instance.RunQuery(serverType, databaseName, query);
await TestServiceProvider.Instance.RunQueryAsync(serverType, databaseName, query);
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Test database '{0}' SQL types are created", databaseName));
}
testDb.DatabaseName = databaseName;
@@ -107,6 +121,11 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
}
public void Cleanup()
{
CleanupAsync().Wait();
}
public async Task CleanupAsync()
{
try
{
@@ -116,7 +135,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
(ServerType == TestServerType.Azure ? Scripts.DropDatabaseIfExistAzure : Scripts.DropDatabaseIfExist), DatabaseName);
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Cleaning up database {0}", DatabaseName));
TestServiceProvider.Instance.RunQuery(ServerType, MasterDatabaseName, dropDatabaseQuery);
await TestServiceProvider.Instance.RunQueryAsync(ServerType, MasterDatabaseName, dropDatabaseQuery);
}
}
catch (Exception ex)

View File

@@ -79,6 +79,15 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
/// Runs a query by calling the services directly (not using the test driver)
/// </summary>
public void RunQuery(TestServerType serverType, string databaseName, string queryText, bool throwOnError = false)
{
RunQueryAsync(serverType, databaseName, queryText, throwOnError).Wait();
}
/// <summary>
/// Runs a query by calling the services directly (not using the test driver)
/// </summary>
public async Task RunQueryAsync(TestServerType serverType, string databaseName, string queryText, bool throwOnError = false)
{
string uri = "";
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -88,7 +97,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
ConnectionInfo connInfo = InitLiveConnectionInfo(serverType, databaseName, uri);
Query query = new Query(queryText, connInfo, new QueryExecutionSettings(), MemoryFileSystem.GetFileStreamFactory());
query.Execute();
query.ExecutionTask.Wait();
await query.ExecutionTask;
if (throwOnError)
{

View File

@@ -1,191 +1,364 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Contracts;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer
{
public class ObjectExplorerServiceTests : ObjectExplorerTestBase
{
private ObjectExplorerService service;
private Mock<ConnectionService> connectionServiceMock;
private Mock<IProtocolEndpoint> serviceHostMock;
public ObjectExplorerServiceTests()
{
connectionServiceMock = new Mock<ConnectionService>();
serviceHostMock = new Mock<IProtocolEndpoint>();
service = CreateOEService(connectionServiceMock.Object);
service.InitializeService(serviceHostMock.Object);
}
[Fact]
public async Task CreateSessionRequestErrorsIfConnectionDetailsIsNull()
{
object errorResponse = null;
var contextMock = RequestContextMocks.Create<CreateSessionResponse>(null)
.AddErrorHandling((errorMessage, errorCode) => errorResponse = errorMessage);
await service.HandleCreateSessionRequest(null, contextMock.Object);
VerifyErrorSent(contextMock);
Assert.True(((string)errorResponse).Contains("ArgumentNullException"));
}
[Fact]
public async Task CreateSessionRequestReturnsFalseOnConnectionFailure()
{
// Given the connection service fails to connect
ConnectionDetails details = TestObjects.GetTestConnectionDetails();
ConnectionCompleteParams completeParams = null;
serviceHostMock.AddEventHandling(ConnectionCompleteNotification.Type, (et, p) => completeParams = p);
string expectedExceptionText = "Error!!!";
connectionServiceMock.Setup(c => c.Connect(It.IsAny<ConnectParams>()))
.Throws(new Exception(expectedExceptionText));
// when creating a new session
// then expect the create session request to return false
await RunAndVerify<CreateSessionResponse>(
test: (requestContext) => service.HandleCreateSessionRequest(details, requestContext),
verify: (actual =>
{
Assert.False(actual.Success);
Assert.Null(actual.SessionId);
Assert.Null(actual.RootNode);
}));
// And expect error notification to be sent
serviceHostMock.Verify(x => x.SendEvent(ConnectionCompleteNotification.Type, It.IsAny<ConnectionCompleteParams>()), Times.Once());
Assert.NotNull(completeParams);
Assert.True(completeParams.Messages.Contains(expectedExceptionText));
}
[Fact]
public async Task CreateSessionRequestWithMasterConnectionReturnsServerSuccessAndNodeInfo()
{
// Given the connection service fails to connect
ConnectionDetails details = new ConnectionDetails()
{
UserName = "user",
Password = "password",
DatabaseName = "master",
ServerName = "serverName"
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Contracts;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer
{
public class ObjectExplorerServiceTests : ObjectExplorerTestBase
{
private ObjectExplorerService service;
private Mock<ConnectionService> connectionServiceMock;
private Mock<IProtocolEndpoint> serviceHostMock;
public ObjectExplorerServiceTests()
{
connectionServiceMock = new Mock<ConnectionService>();
serviceHostMock = new Mock<IProtocolEndpoint>();
service = CreateOEService(connectionServiceMock.Object);
service.InitializeService(serviceHostMock.Object);
}
[Fact]
public async Task CreateSessionRequestErrorsIfConnectionDetailsIsNull()
{
object errorResponse = null;
var contextMock = RequestContextMocks.Create<CreateSessionResponse>(null)
.AddErrorHandling((errorMessage, errorCode) => errorResponse = errorMessage);
await service.HandleCreateSessionRequest(null, contextMock.Object);
VerifyErrorSent(contextMock);
Assert.True(((string)errorResponse).Contains("ArgumentNullException"));
}
[Fact]
public async Task CreateSessionRequestReturnsFalseOnConnectionFailure()
{
// Given the connection service fails to connect
ConnectionDetails details = TestObjects.GetTestConnectionDetails();
ConnectionCompleteParams completeParams = null;
serviceHostMock.AddEventHandling(ConnectionCompleteNotification.Type, (et, p) => completeParams = p);
string expectedExceptionText = "Error!!!";
connectionServiceMock.Setup(c => c.Connect(It.IsAny<ConnectParams>()))
.Throws(new Exception(expectedExceptionText));
// when creating a new session
// then expect the create session request to return false
await RunAndVerify<CreateSessionResponse>(
test: (requestContext) => service.HandleCreateSessionRequest(details, requestContext),
verify: (actual =>
{
Assert.False(actual.Success);
Assert.Null(actual.SessionId);
Assert.Null(actual.RootNode);
}));
// And expect error notification to be sent
serviceHostMock.Verify(x => x.SendEvent(ConnectionCompleteNotification.Type, It.IsAny<ConnectionCompleteParams>()), Times.Once());
Assert.NotNull(completeParams);
Assert.True(completeParams.Messages.Contains(expectedExceptionText));
}
[Fact]
public async Task CreateSessionRequestWithMasterConnectionReturnsServerSuccessAndNodeInfo()
{
// Given the connection service fails to connect
ConnectionDetails details = new ConnectionDetails()
{
UserName = "user",
Password = "password",
DatabaseName = "master",
ServerName = "serverName"
};
await CreateSessionRequestAndVerifyServerNodeHelper(details);
}
[Fact]
public async Task CreateSessionRequestWithEmptyConnectionReturnsServerSuccessAndNodeInfo()
{
// Given the connection service fails to connect
ConnectionDetails details = new ConnectionDetails()
{
UserName = "user",
Password = "password",
DatabaseName = "",
ServerName = "serverName"
[Fact]
public async Task CreateSessionRequestWithEmptyConnectionReturnsServerSuccessAndNodeInfo()
{
// Given the connection service fails to connect
ConnectionDetails details = new ConnectionDetails()
{
UserName = "user",
Password = "password",
DatabaseName = "",
ServerName = "serverName"
};
await CreateSessionRequestAndVerifyServerNodeHelper(details);
}
[Fact]
public async Task CreateSessionRequestWithMsdbConnectionReturnsServerSuccessAndNodeInfo()
{
// Given the connection service fails to connect
ConnectionDetails details = new ConnectionDetails()
{
UserName = "user",
Password = "password",
DatabaseName = "msdb",
ServerName = "serverName"
[Fact]
public async Task CreateSessionRequestWithMsdbConnectionReturnsServerSuccessAndNodeInfo()
{
// Given the connection service fails to connect
ConnectionDetails details = new ConnectionDetails()
{
UserName = "user",
Password = "password",
DatabaseName = "msdb",
ServerName = "serverName"
};
await CreateSessionRequestAndVerifyServerNodeHelper(details);
}
private async Task CreateSessionRequestAndVerifyServerNodeHelper(ConnectionDetails details)
{
serviceHostMock.AddEventHandling(ConnectionCompleteNotification.Type, null);
connectionServiceMock.Setup(c => c.Connect(It.IsAny<ConnectParams>()))
.Returns((ConnectParams connectParams) => Task.FromResult(GetCompleteParamsForConnection(connectParams.OwnerUri, details)));
// when creating a new session
// then expect the create session request to return false
await RunAndVerify<CreateSessionResponse>(
test: (requestContext) => service.HandleCreateSessionRequest(details, requestContext),
verify: (actual =>
{
Assert.True(actual.Success);
Assert.NotNull(actual.SessionId);
VerifyServerNode(actual.RootNode, details);
}));
// And expect no error notification to be sent
serviceHostMock.Verify(x => x.SendEvent(ConnectionCompleteNotification.Type,
It.IsAny<ConnectionCompleteParams>()), Times.Never());
}
private void VerifyServerNode(NodeInfo serverNode, ConnectionDetails details)
{
Assert.NotNull(serverNode);
Assert.Equal(NodeTypes.Server.ToString(), serverNode.NodeType);
string[] pathParts = serverNode.NodePath.Split(TreeNode.PathPartSeperator);
Assert.Equal(1, pathParts.Length);
Assert.Equal(details.ServerName, pathParts[0]);
Assert.True(serverNode.Label.Contains(details.ServerName));
Assert.False(serverNode.IsLeaf);
}
private static ConnectionCompleteParams GetCompleteParamsForConnection(string uri, ConnectionDetails details)
{
return new ConnectionCompleteParams()
{
ConnectionId = Guid.NewGuid().ToString(),
OwnerUri = uri,
ConnectionSummary = new ConnectionSummary()
{
ServerName = details.ServerName,
DatabaseName = details.DatabaseName,
UserName = details.UserName
},
ServerInfo = TestObjects.GetTestServerInfo()
};
}
private async Task RunAndVerify<T>(Func<RequestContext<T>, Task> test, Action<T> verify)
{
T result = default(T);
var contextMock = RequestContextMocks.Create<T>(r => result = r).AddErrorHandling(null);
await test(contextMock.Object);
VerifyResult(contextMock, verify, result);
}
private void VerifyResult<T>(Mock<RequestContext<T>> contextMock, Action<T> verify, T actual)
{
contextMock.Verify(c => c.SendResult(It.IsAny<T>()), Times.Once);
contextMock.Verify(c => c.SendError(It.IsAny<string>(), It.IsAny<int>()), Times.Never);
verify(actual);
}
private void VerifyErrorSent<T>(Mock<RequestContext<T>> contextMock)
{
contextMock.Verify(c => c.SendResult(It.IsAny<T>()), Times.Never);
contextMock.Verify(c => c.SendError(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
}
}
}
}
[Fact]
public async Task ExpandNodeGivenValidSessionShouldReturnTheNodeChildren()
{
await ExpandAndVerifyServerNodes();
}
[Fact]
public async Task RefreshNodeGivenValidSessionShouldReturnTheNodeChildren()
{
await RefreshAndVerifyServerNodes();
}
[Fact]
public async Task ExpandNodeGivenInvalidSessionShouldReturnEmptyList()
{
ExpandParams expandParams = new ExpandParams()
{
SessionId = "invalid session is",
NodePath = "Any path"
};
// when expanding
// then expect the nodes are server children
await RunAndVerify<ExpandResponse>(
test: (requestContext) => service.HandleExpandRequest(expandParams, requestContext),
verify: (actual =>
{
Assert.Equal(actual.SessionId, expandParams.SessionId);
Assert.Null(actual.Nodes);
}));
}
[Fact]
public async Task RefreshNodeGivenInvalidSessionShouldReturnEmptyList()
{
RefreshParams expandParams = new RefreshParams()
{
SessionId = "invalid session is",
NodePath = "Any path"
};
// when expanding
// then expect the nodes are server children
await RunAndVerify<RefreshResponse>(
test: (requestContext) => service.HandleRefreshRequest(expandParams, requestContext),
verify: (actual =>
{
Assert.Equal(actual.SessionId, expandParams.SessionId);
Assert.Null(actual.Nodes);
}));
}
[Fact]
public async Task CloseSessionGivenInvalidSessionShouldReturnEmptyList()
{
CloseSessionParams closeSessionParamsparams = new CloseSessionParams()
{
SessionId = "invalid session is",
};
// when expanding
// then expect the nodes are server children
await RunAndVerify<CloseSessionResponse>(
test: (requestContext) => service.HandleCloseSessionRequest(closeSessionParamsparams, requestContext),
verify: (actual =>
{
Assert.Equal(actual.SessionId, closeSessionParamsparams.SessionId);
Assert.False(actual.Success);
}));
}
[Fact]
public async Task CloseSessionGivenValidSessionShouldCloseTheSessionAndDisconnect()
{
var session = await CreateSession();
CloseSessionParams closeSessionParamsparams = new CloseSessionParams()
{
SessionId = session.SessionId,
};
// when expanding
// then expect the nodes are server children
await RunAndVerify<CloseSessionResponse>(
test: (requestContext) => service.HandleCloseSessionRequest(closeSessionParamsparams, requestContext),
verify: (actual =>
{
Assert.Equal(actual.SessionId, closeSessionParamsparams.SessionId);
Assert.True(actual.Success);
Assert.False(service.SessionIds.Contains(session.SessionId));
}));
connectionServiceMock.Verify(c => c.Disconnect(It.IsAny<DisconnectParams>()));
}
private async Task<CreateSessionResponse> CreateSession()
{
ConnectionDetails details = new ConnectionDetails()
{
UserName = "user",
Password = "password",
DatabaseName = "msdb",
ServerName = "serverName"
};
serviceHostMock.AddEventHandling(ConnectionCompleteNotification.Type, null);
CreateSessionResponse result = default(CreateSessionResponse);
var contextMock = RequestContextMocks.Create<CreateSessionResponse>(r => result = r).AddErrorHandling(null);
connectionServiceMock.Setup(c => c.Connect(It.IsAny<ConnectParams>()))
.Returns((ConnectParams connectParams) => Task.FromResult(GetCompleteParamsForConnection(connectParams.OwnerUri, details)));
ConnectionInfo connectionInfo = new ConnectionInfo(null, null, null);
string fakeConnectionString = "Data Source=server;Initial Catalog=database;Integrated Security=False;User Id=user";
connectionInfo.AddConnection("Default", new SqlConnection(fakeConnectionString));
connectionServiceMock.Setup((c => c.TryFindConnection(It.IsAny<string>(), out connectionInfo))).
OutCallback((string t, out ConnectionInfo v) => v = connectionInfo)
.Returns(true);
connectionServiceMock.Setup(c => c.Disconnect(It.IsAny<DisconnectParams>())).Returns(true);
await service.HandleCreateSessionRequest(details, contextMock.Object);
return result;
}
private async Task ExpandAndVerifyServerNodes()
{
var session = await CreateSession();
ExpandParams expandParams = new ExpandParams()
{
SessionId = session.SessionId,
NodePath = session.RootNode.NodePath
};
// when expanding
// then expect the nodes are server children
await RunAndVerify<ExpandResponse>(
test: (requestContext) => service.HandleExpandRequest(expandParams, requestContext),
verify: (actual =>
{
Assert.Equal(actual.SessionId, session.SessionId);
Assert.NotNull(actual.SessionId);
VerifyServerNodeChildren(actual.Nodes);
}));
}
private async Task RefreshAndVerifyServerNodes()
{
var session = await CreateSession();
RefreshParams expandParams = new RefreshParams()
{
SessionId = session.SessionId,
NodePath = session.RootNode.NodePath
};
// when expanding
// then expect the nodes are server children
await RunAndVerify<RefreshResponse>(
test: (requestContext) => service.HandleRefreshRequest(expandParams, requestContext),
verify: (actual =>
{
Assert.Equal(actual.SessionId, session.SessionId);
Assert.NotNull(actual.SessionId);
VerifyServerNodeChildren(actual.Nodes);
}));
}
private async Task CreateSessionRequestAndVerifyServerNodeHelper(ConnectionDetails details)
{
serviceHostMock.AddEventHandling(ConnectionCompleteNotification.Type, null);
connectionServiceMock.Setup(c => c.Connect(It.IsAny<ConnectParams>()))
.Returns((ConnectParams connectParams) => Task.FromResult(GetCompleteParamsForConnection(connectParams.OwnerUri, details)));
// when creating a new session
// then expect the create session request to return false
await RunAndVerify<CreateSessionResponse>(
test: (requestContext) => service.HandleCreateSessionRequest(details, requestContext),
verify: (actual =>
{
Assert.True(actual.Success);
Assert.NotNull(actual.SessionId);
VerifyServerNode(actual.RootNode, details);
}));
// And expect no error notification to be sent
serviceHostMock.Verify(x => x.SendEvent(ConnectionCompleteNotification.Type,
It.IsAny<ConnectionCompleteParams>()), Times.Never());
}
private void VerifyServerNode(NodeInfo serverNode, ConnectionDetails details)
{
Assert.NotNull(serverNode);
Assert.Equal(NodeTypes.Server.ToString(), serverNode.NodeType);
string[] pathParts = serverNode.NodePath.Split(TreeNode.PathPartSeperator);
Assert.Equal(1, pathParts.Length);
Assert.Equal(details.ServerName, pathParts[0]);
Assert.True(serverNode.Label.Contains(details.ServerName));
Assert.False(serverNode.IsLeaf);
}
private void VerifyServerNodeChildren(NodeInfo[] children)
{
Assert.NotNull(children);
Assert.True(children.Count() == 3);
Assert.True(children.All((x => x.NodeType == "Folder")));
}
private static ConnectionCompleteParams GetCompleteParamsForConnection(string uri, ConnectionDetails details)
{
return new ConnectionCompleteParams()
{
ConnectionId = Guid.NewGuid().ToString(),
OwnerUri = uri,
ConnectionSummary = new ConnectionSummary()
{
ServerName = details.ServerName,
DatabaseName = details.DatabaseName,
UserName = details.UserName
},
ServerInfo = TestObjects.GetTestServerInfo()
};
}
private async Task RunAndVerify<T>(Func<RequestContext<T>, Task> test, Action<T> verify)
{
T result = default(T);
var contextMock = RequestContextMocks.Create<T>(r => result = r).AddErrorHandling(null);
await test(contextMock.Object);
VerifyResult(contextMock, verify, result);
}
private void VerifyResult<T>(Mock<RequestContext<T>> contextMock, Action<T> verify, T actual)
{
contextMock.Verify(c => c.SendResult(It.IsAny<T>()), Times.Once);
contextMock.Verify(c => c.SendError(It.IsAny<string>(), It.IsAny<int>()), Times.Never);
verify(actual);
}
private void VerifyErrorSent<T>(Mock<RequestContext<T>> contextMock)
{
contextMock.Verify(c => c.SendResult(It.IsAny<T>()), Times.Never);
contextMock.Verify(c => c.SendError(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
}
}
}

View File

@@ -1,45 +1,48 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Extensibility;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer
{
// Base class providing common test functionality for OE tests
public abstract class ObjectExplorerTestBase
{
protected RegisteredServiceProvider ServiceProvider
{
get;
set;
}
protected RegisteredServiceProvider CreateServiceProviderWithMinServices()
{
return CreateProvider()
.RegisterSingleService(new ConnectionService())
.RegisterSingleService(new ObjectExplorerService());
}
protected RegisteredServiceProvider CreateProvider()
{
ServiceProvider = new RegisteredServiceProvider();
return ServiceProvider;
}
protected ObjectExplorerService CreateOEService(ConnectionService connService)
{
CreateProvider()
.RegisterSingleService(connService)
.RegisterSingleService(new ObjectExplorerService());
// Create the service using the service provider, which will initialize dependencies
return ServiceProvider.GetService<ObjectExplorerService>();
}
}
}
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.SmoModel;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer
{
// Base class providing common test functionality for OE tests
public abstract class ObjectExplorerTestBase
{
protected RegisteredServiceProvider ServiceProvider
{
get;
set;
}
protected RegisteredServiceProvider CreateServiceProviderWithMinServices()
{
return CreateProvider()
.RegisterSingleService(new ConnectionService())
.RegisterSingleService(new ObjectExplorerService());
}
protected RegisteredServiceProvider CreateProvider()
{
ServiceProvider = new RegisteredServiceProvider();
return ServiceProvider;
}
protected ObjectExplorerService CreateOEService(ConnectionService connService)
{
CreateProvider()
.RegisterSingleService(connService)
.RegisterSingleService(new ObjectExplorerService())
.RegisterSingleService<ChildFactory>(new ServerChildFactory());
// Create the service using the service provider, which will initialize dependencies
return ServiceProvider.GetService<ObjectExplorerService>();
}
}
}