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

@@ -0,0 +1,53 @@
//
// 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.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Contracts
{
/// <summary>
/// Information returned from a <see cref="CloseSessionRequest"/>.
/// Contains success information, a <see cref="SessionId"/> to be used when
/// requesting closing an existing session.
/// </summary>
public class CloseSessionResponse
{
/// <summary>
/// Boolean indicating if the session was closed successfully
/// </summary>
public bool Success { get; set; }
/// <summary>
/// Unique ID to use when sending any requests for objects in the
/// tree under the node
/// </summary>
public string SessionId { get; set; }
}
/// <summary>
/// Parameters to the <see cref="CloseSessionRequest"/>.
/// </summary>
public class CloseSessionParams
{
/// <summary>
/// The Id returned from a <see cref="CreateSessionRequest"/>. This
/// is used to disambiguate between different trees.
/// </summary>
public string SessionId { get; set; }
}
/// <summary>
/// Establishes an Object Explorer tree session for a specific connection.
/// This will create a connection to a specific server or database, register
/// it for use in the
/// </summary>
public class CloseSessionRequest
{
public static readonly
RequestType<CloseSessionParams, CloseSessionResponse> Type =
RequestType<CloseSessionParams, CloseSessionResponse>.Create("objectexplorer/closesession");
}
}

View File

@@ -1,39 +1,56 @@
// //
// Copyright (c) Microsoft. All rights reserved. // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
// //
using Microsoft.SqlTools.Hosting.Protocol.Contracts; using Microsoft.SqlTools.Hosting.Protocol.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Contracts namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Contracts
{ {
/// <summary> /// <summary>
/// Parameters to the <see cref="ExpandRequest"/>. /// Information returned from a <see cref="RefreshRequest"/>.
/// </summary> /// </summary>
public class RefreshParams public class RefreshResponse
{ {
/// <summary> /// <summary>
/// The Id returned from a <see cref="CreateSessionRequest"/>. This /// Unique ID to use when sending any requests for objects in the
/// is used to disambiguate between different trees. /// tree under the node
/// </summary> /// </summary>
public string SessionId { get; set; } public string SessionId { get; set; }
/// <summary> /// <summary>
/// Path identifying the node to expand. See <see cref="NodeInfo.NodePath"/> for details /// Information describing the expanded nodes in the tree
/// </summary> /// </summary>
public string[] NodePath { get; set; } public NodeInfo[] Nodes { get; set; }
} }
/// <summary> /// <summary>
/// A request to expand a /// Parameters to the <see cref="ExpandRequest"/>.
/// </summary> /// </summary>
public class RefreshRequest public class RefreshParams
{ {
/// <summary> /// <summary>
/// Returns children of a given node as a <see cref="NodeInfo"/> array. /// The Id returned from a <see cref="CreateSessionRequest"/>. This
/// </summary> /// is used to disambiguate between different trees.
public static readonly /// </summary>
RequestType<ExpandParams, NodeInfo[]> Type = public string SessionId { get; set; }
RequestType<ExpandParams, NodeInfo[]>.Create("objectexplorer/refresh");
} /// <summary>
} /// Path identifying the node to refresh. See <see cref="NodeInfo.NodePath"/> for details
/// </summary>
public string NodePath { get; set; }
}
/// <summary>
/// A request to expand a
/// </summary>
public class RefreshRequest
{
/// <summary>
/// Returns children of a given node as a <see cref="NodeInfo"/> array.
/// </summary>
public static readonly
RequestType<RefreshParams, RefreshResponse> Type =
RequestType<RefreshParams, RefreshResponse>.Create("objectexplorer/refresh");
}
}

View File

@@ -74,7 +74,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes
{ {
proeprtyValue = (int)Convert.ChangeType(value, Type); proeprtyValue = (int)Convert.ChangeType(value, Type);
} }
string orPrefix = i == 0 ? "" : "or"; string orPrefix = i == 0 ? string.Empty : "or";
filter = $"{filter} {orPrefix} @{Property} = {proeprtyValue}"; filter = $"{filter} {orPrefix} @{Property} = {proeprtyValue}";
} }
} }
@@ -91,8 +91,8 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes
{ {
var value = list[i]; var value = list[i];
string orPrefix = i == 0 ? "" : "and"; string andPrefix = i == 0 ? string.Empty : "and";
filter = $"{filter} {orPrefix} {value.ToPropertyFilterString()}"; filter = $"{filter} {andPrefix} {value.ToPropertyFilterString()}";
} }
filter = $"[{filter}]"; filter = $"[{filter}]";

View File

@@ -195,6 +195,17 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes
return children; return children;
} }
/// <summary>
/// Refresh this node and returns its children
/// </summary>
/// <returns>Children as an IList. This is the raw children collection, not a copy</returns>
public IList<TreeNode> Refresh()
{
// TODO consider why solution explorer has separate Children and Items options
PopulateChildren();
return children;
}
/// <summary> /// <summary>
/// Gets a readonly view of the currently defined children for this node. /// Gets a readonly view of the currently defined children for this node.
/// This does not expand the node at all /// This does not expand the node at all
@@ -242,7 +253,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes
{ {
return Parent as T; return Parent as T;
} }
protected void PopulateChildren() protected void PopulateChildren()
{ {
Debug.Assert(IsAlwaysLeaf == false); Debug.Assert(IsAlwaysLeaf == false);

View File

@@ -4,7 +4,9 @@
// //
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Composition; using System.Composition;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
@@ -33,7 +35,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
// Instance of the connection service, used to get the connection info for a given owner URI // Instance of the connection service, used to get the connection info for a given owner URI
private ConnectionService connectionService; private ConnectionService connectionService;
private IProtocolEndpoint serviceHost; private IProtocolEndpoint serviceHost;
private Dictionary<string, ObjectExplorerSession> sessionMap; private ConcurrentDictionary<string, ObjectExplorerSession> sessionMap;
private readonly Lazy<Dictionary<string, HashSet<ChildFactory>>> applicableNodeChildFactories; private readonly Lazy<Dictionary<string, HashSet<ChildFactory>>> applicableNodeChildFactories;
private IMultiServiceProvider serviceProvider; private IMultiServiceProvider serviceProvider;
@@ -42,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
/// </summary> /// </summary>
public ObjectExplorerService() public ObjectExplorerService()
{ {
sessionMap = new Dictionary<string, ObjectExplorerSession>(); sessionMap = new ConcurrentDictionary<string, ObjectExplorerSession>();
applicableNodeChildFactories = new Lazy<Dictionary<string, HashSet<ChildFactory>>>(() => PopulateFactories()); applicableNodeChildFactories = new Lazy<Dictionary<string, HashSet<ChildFactory>>>(() => PopulateFactories());
} }
@@ -62,6 +64,17 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
return applicableNodeChildFactories.Value; return applicableNodeChildFactories.Value;
} }
} }
/// <summary>
/// Returns the session ids
/// </summary>
internal IReadOnlyCollection<string> SessionIds
{
get
{
return new ReadOnlyCollection<string>(sessionMap.Keys.ToList());
}
}
/// <summary> /// <summary>
/// As an <see cref="IComposableService"/>, this will be set whenever the service is initialized /// As an <see cref="IComposableService"/>, this will be set whenever the service is initialized
@@ -86,6 +99,8 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
// Register handlers for requests // Register handlers for requests
serviceHost.SetRequestHandler(CreateSessionRequest.Type, HandleCreateSessionRequest); serviceHost.SetRequestHandler(CreateSessionRequest.Type, HandleCreateSessionRequest);
serviceHost.SetRequestHandler(ExpandRequest.Type, HandleExpandRequest); serviceHost.SetRequestHandler(ExpandRequest.Type, HandleExpandRequest);
serviceHost.SetRequestHandler(RefreshRequest.Type, HandleRefreshRequest);
serviceHost.SetRequestHandler(CloseSessionRequest.Type, HandleCloseSessionRequest);
} }
public void CloseSession(string uri) public void CloseSession(string uri)
@@ -94,7 +109,11 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
if (sessionMap.TryGetValue(uri, out session)) if (sessionMap.TryGetValue(uri, out session))
{ {
// Establish a connection to the specified server/database // Establish a connection to the specified server/database
sessionMap.Remove(session.Uri); sessionMap.TryRemove(session.Uri, out session);
connectionService.Disconnect(new DisconnectParams()
{
OwnerUri = uri
});
} }
} }
@@ -136,7 +155,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
await HandleRequestAsync(doCreateSession, context, "HandleCreateSessionRequest"); await HandleRequestAsync(doCreateSession, context, "HandleCreateSessionRequest");
} }
internal async Task<NodeInfo[]> ExpandNode(ObjectExplorerSession session, string nodePath) internal async Task<NodeInfo[]> ExpandNode(ObjectExplorerSession session, string nodePath, bool forceRefresh = false)
{ {
return await Task.Factory.StartNew(() => return await Task.Factory.StartNew(() =>
{ {
@@ -144,7 +163,14 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
TreeNode node = session.Root.FindNodeByPath(nodePath); TreeNode node = session.Root.FindNodeByPath(nodePath);
if(node != null) if(node != null)
{ {
nodes = node.Expand().Select(x => x.ToNodeInfo()).ToArray(); if (forceRefresh)
{
nodes = node.Refresh().Select(x => x.ToNodeInfo()).ToArray();
}
else
{
nodes = node.Expand().Select(x => x.ToNodeInfo()).ToArray();
}
} }
return nodes; return nodes;
}); });
@@ -167,7 +193,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
} }
session = ObjectExplorerSession.CreateSession(connectionResult, serviceProvider); session = ObjectExplorerSession.CreateSession(connectionResult, serviceProvider);
sessionMap[uri] = session; sessionMap.AddOrUpdate(uri, session, (key, oldSession) => session);
return session; return session;
} }
@@ -212,30 +238,87 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
string uri = expandParams.SessionId; string uri = expandParams.SessionId;
ObjectExplorerSession session = null; ObjectExplorerSession session = null;
NodeInfo[] nodes = null; NodeInfo[] nodes = null;
if (sessionMap.ContainsKey(uri)) ExpandResponse response;
if (!sessionMap.TryGetValue(uri, out session))
{ {
session = sessionMap[uri]; Logger.Write(LogLevel.Verbose, $"Cannot expand object explorer node. Couldn't find session for uri. {uri} ");
}
else
{
//TODO: error
} }
if (session != null) if (session != null)
{ {
// Establish a connection to the specified server/database // expand the nodes for given node path
nodes = await ExpandNode(session, expandParams.NodePath); nodes = await ExpandNode(session, expandParams.NodePath);
} }
ExpandResponse response;
response = new ExpandResponse() { Nodes = nodes, SessionId = uri }; response = new ExpandResponse() { Nodes = nodes, SessionId = uri };
return response; return response;
}; };
await HandleRequestAsync(expandNode, context, "HandleExpandRequest"); await HandleRequestAsync(expandNode, context, "HandleExpandRequest");
} }
internal async Task HandleRefreshRequest(RefreshParams refreshParams, RequestContext<RefreshResponse> context)
{
Logger.Write(LogLevel.Verbose, "HandleRefreshRequest");
Func<Task<RefreshResponse>> refreshNode = async () =>
{
Validate.IsNotNull(nameof(refreshParams), refreshParams);
Validate.IsNotNull(nameof(context), context);
string uri = refreshParams.SessionId;
ObjectExplorerSession session = null;
NodeInfo[] nodes = null;
RefreshResponse response;
if (!sessionMap.TryGetValue(uri, out session))
{
Logger.Write(LogLevel.Verbose, $"Cannot refresh object explorer node. Couldn't find session for uri. {uri} ");
}
if (session != null)
{
// refresh the nodes for given node path
nodes = await ExpandNode(session, refreshParams.NodePath, true);
}
response = new RefreshResponse() { Nodes = nodes, SessionId = uri };
return response;
};
await HandleRequestAsync(refreshNode, context, "HandleRefreshRequest");
}
internal async Task HandleCloseSessionRequest(CloseSessionParams closeSessionParams, RequestContext<CloseSessionResponse> context)
{
Validate.IsNotNull(nameof(closeSessionParams), closeSessionParams);
Validate.IsNotNull(nameof(context), context);
Logger.Write(LogLevel.Verbose, "HandleCloseSessionRequest");
Func<Task<CloseSessionResponse>> closeSession = () =>
{
return Task.Factory.StartNew(() =>
{
string uri = closeSessionParams.SessionId;
ObjectExplorerSession session = null;
bool success = false;
if (!sessionMap.TryGetValue(uri, out session))
{
Logger.Write(LogLevel.Verbose, $"Cannot close object explorer session. Couldn't find session for uri. {uri} ");
}
if (session != null)
{
// refresh the nodes for given node path
CloseSession(uri);
success = true;
}
var response = new CloseSessionResponse() {Success = success, SessionId = uri};
return response;
});
};
await HandleRequestAsync(closeSession, context, "HandleCloseSessionRequest");
}
private async Task HandleRequestAsync<T>(Func<Task<T>> handler, RequestContext<T> requestContext, string requestType) private async Task HandleRequestAsync<T>(Func<Task<T>> handler, RequestContext<T> requestContext, string requestType)
{ {
Logger.Write(LogLevel.Verbose, requestType); Logger.Write(LogLevel.Verbose, requestType);

View File

@@ -64,28 +64,31 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer.SmoModel
WriteLine(string.Format("if ({0} != null)", parentVar)); WriteLine(string.Format("if ({0} != null)", parentVar));
WriteLine("{"); WriteLine("{");
PushIndent(indent); PushIndent(indent);
WriteLine("bool hasFilter = !string.IsNullOrEmpty(filter);");
string navigationPath = GetNavigationPath(nodeElement, xmlFile, nodeName, parentType); string navigationPath = GetNavigationPath(nodeElement, xmlFile, nodeName, parentType);
WriteLine(string.Format("var retValue = {0}.{1};", parentVar, navigationPath)); WriteLine(string.Format("var retValue = {0}.{1};", parentVar, navigationPath));
WriteLine("bool hasFilter = !string.IsNullOrEmpty(filter);");
WriteLine("HashSet<string> urns = null;");
WriteLine("if (hasFilter)");
WriteLine("{");
PushIndent(indent);
WriteLine(string.Format("string urn = $\"{{{0}.Urn.ToString()}}/{1}\" + filter;", parentVar, nodeType));
WriteLine("Enumerator en = new Enumerator();");
WriteLine("Request request = new Request(new Urn(urn));");
WriteLine("ServerConnection serverConnection = new ServerConnection(context.Server.ConnectionContext.SqlConnectionObject);");
WriteLine("EnumResult result = en.Process(serverConnection, request);");
WriteLine("urns = GetUrns(result);");
PopIndent();
WriteLine("}");
WriteLine("if (retValue != null)"); WriteLine("if (retValue != null)");
WriteLine("{"); WriteLine("{");
PushIndent(indent); PushIndent(indent);
if (IsCollection(nodeElement)) if (IsCollection(nodeElement))
{ {
WriteLine("HashSet<string> urns = null;");
WriteLine("if (hasFilter)");
WriteLine("{");
PushIndent(indent);
WriteLine(string.Format("string urn = $\"{{{0}.Urn.ToString()}}/{1}\" + filter;", parentVar, nodeType));
WriteLine("Enumerator en = new Enumerator();");
WriteLine("Request request = new Request(new Urn(urn));");
WriteLine("ServerConnection serverConnection = new ServerConnection(context.Server.ConnectionContext.SqlConnectionObject);");
WriteLine("EnumResult result = en.Process(serverConnection, request);");
WriteLine("urns = GetUrns(result);");
PopIndent();
WriteLine("}");
WriteLine("if (hasFilter && urns != null)"); WriteLine("if (hasFilter && urns != null)");
WriteLine("{"); WriteLine("{");
PushIndent(indent); PushIndent(indent);

View File

@@ -92,7 +92,7 @@ gulp.task('ext:nuget-restore', function() {
gulp.task('ext:code-coverage', function(done) { 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) { if (err) {
throw new gutil.PluginError('ext:code-coverage', 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"); string outputString = output.ToString().Replace("\r\n", "\n");
Console.WriteLine(baselineFilename); //Console.WriteLine(baselineFilename);
if (string.Compare(baseline, outputString, StringComparison.Ordinal) != 0) if (string.Compare(baseline, outputString, StringComparison.Ordinal) != 0)
{ {

View File

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

View File

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

View File

@@ -9,6 +9,7 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Xunit; using Xunit;
using System.Data.SqlClient; using System.Data.SqlClient;
using System.Threading.Tasks;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{ {
@@ -59,16 +60,29 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
string databaseName = null, string databaseName = null,
string query = null, string query = null,
string dbNamePrefix = 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(); SqlTestDb testDb = new SqlTestDb();
databaseName = databaseName ?? GetUniqueDBName(dbNamePrefix); databaseName = databaseName ?? GetUniqueDBName(dbNamePrefix);
string createDatabaseQuery = Scripts.CreateDatabaseQuery.Replace("#DatabaseName#", databaseName); 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)); Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Test database '{0}' is created", databaseName));
if (!string.IsNullOrEmpty(query)) 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)); Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Test database '{0}' SQL types are created", databaseName));
} }
testDb.DatabaseName = databaseName; testDb.DatabaseName = databaseName;
@@ -107,6 +121,11 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
} }
public void Cleanup() public void Cleanup()
{
CleanupAsync().Wait();
}
public async Task CleanupAsync()
{ {
try try
{ {
@@ -116,7 +135,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
(ServerType == TestServerType.Azure ? Scripts.DropDatabaseIfExistAzure : Scripts.DropDatabaseIfExist), DatabaseName); (ServerType == TestServerType.Azure ? Scripts.DropDatabaseIfExistAzure : Scripts.DropDatabaseIfExist), DatabaseName);
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Cleaning up database {0}", 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) 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) /// Runs a query by calling the services directly (not using the test driver)
/// </summary> /// </summary>
public void RunQuery(TestServerType serverType, string databaseName, string queryText, bool throwOnError = false) 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 = ""; string uri = "";
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -88,7 +97,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
ConnectionInfo connInfo = InitLiveConnectionInfo(serverType, databaseName, uri); ConnectionInfo connInfo = InitLiveConnectionInfo(serverType, databaseName, uri);
Query query = new Query(queryText, connInfo, new QueryExecutionSettings(), MemoryFileSystem.GetFileStreamFactory()); Query query = new Query(queryText, connInfo, new QueryExecutionSettings(), MemoryFileSystem.GetFileStreamFactory());
query.Execute(); query.Execute();
query.ExecutionTask.Wait(); await query.ExecutionTask;
if (throwOnError) if (throwOnError)
{ {

View File

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