Add tests to improve code coverage (#187)

* DbColumn and ReliableConnection tests

* More retry connection tests

* More tests

* Fix broken peek definition integration tests

* Fix test bug

* Add a couple batch tests

* Add some more tests

* More tests for code coverage.

* Validation and Diagnostic tests

* A few more tests

* A few mote test changes.

* Update file path tests to run on Windows only
This commit is contained in:
Karl Burtram
2016-12-14 13:49:42 -08:00
committed by GitHub
parent e9398f7182
commit dd41e0545a
29 changed files with 921 additions and 99 deletions

View File

@@ -536,6 +536,17 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
Assert.True(connectionString.Contains(connectionStringMarker));
}
/// <summary>
/// Build connection string with an invalid auth type
/// </summary>
[Fact]
public void BuildConnectionStringWithInvalidAuthType()
{
ConnectionDetails details = TestObjects.GetTestConnectionDetails();
details.AuthenticationType = "NotAValidAuthType";
Assert.Throws<ArgumentException>(() => ConnectionService.BuildConnectionString(details));
}
/// <summary>
/// Verify that a connection changed event is fired when the database context changes.
/// </summary>
@@ -892,6 +903,29 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
});
}
// <summary>
/// Test that cancel connection with a null connection parameter
/// </summary>
[Fact]
public void TestCancelConnectionNullParam()
{
var service = TestObjects.GetTestConnectionService();
Assert.False(service.CancelConnect(null));
}
// <summary>
/// Test that cancel connection with a null connection parameter
/// </summary>
[Fact]
public void TestListDatabasesInvalidParams()
{
var service = TestObjects.GetTestConnectionService();
var listParams = new ListDatabasesParams();
Assert.Throws<ArgumentException>(() => service.ListDatabases(listParams));
listParams.OwnerUri = "file://notmyfile.sql";
Assert.Throws<Exception>(() => service.ListDatabases(listParams));
}
/// <summary>
/// Test that the connection complete notification type can be created.
/// </summary>

View File

@@ -10,8 +10,11 @@ using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Threading;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
@@ -70,6 +73,11 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
{
return ShouldRetryImpl(retryStateObj);
}
public void DoOnIgnoreErrorOccurred(RetryState retryState)
{
OnIgnoreErrorOccurred(retryState);
}
}
internal class TestProgressiveRetryPolicy : ProgressiveRetryPolicy
@@ -126,10 +134,46 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
strategy: new NetworkConnectivityErrorDetectionStrategy(),
maxRetryCount: 3,
intervalBetweenRetries: TimeSpan.FromMilliseconds(100));
bool shouldRety = policy.InvokeShouldRetryImpl(new RetryStateEx());
var retryState = new RetryStateEx();
bool shouldRety = policy.InvokeShouldRetryImpl(retryState);
policy.DoOnIgnoreErrorOccurred(retryState);
Assert.True(shouldRety);
}
[Fact]
public void FixedDelayPolicyExecuteActionTest()
{
TestFixedDelayPolicy policy = new TestFixedDelayPolicy(
strategy: new NetworkConnectivityErrorDetectionStrategy(),
maxRetryCount: 3,
intervalBetweenRetries: TimeSpan.FromMilliseconds(20));
// execute an action that throws a retry limit exception
CancellationToken token = new CancellationToken();
Assert.Equal(policy.ExecuteAction<int>((s) => { throw new RetryLimitExceededException(); }, token), default(int));
// execute an action that throws a retry limit exeception with an inner exception
Assert.Throws<Exception>(() =>
{
policy.ExecuteAction<int>((s) =>
{
var e = new RetryLimitExceededException("retry", new Exception());
throw e;
});
});
}
[Fact]
public void IsRetryableExceptionTest()
{
TestFixedDelayPolicy policy = new TestFixedDelayPolicy(
strategy: new NetworkConnectivityErrorDetectionStrategy(),
maxRetryCount: 3,
intervalBetweenRetries: TimeSpan.FromMilliseconds(20));
Assert.False(policy.IsRetryableException(new Exception()));
}
[Fact]
public void ProgressiveRetryPolicyTest()
{
@@ -140,6 +184,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
increment: TimeSpan.FromMilliseconds(100));
bool shouldRety = policy.InvokeShouldRetryImpl(new RetryStateEx());
Assert.True(shouldRety);
Assert.NotNull(policy.CommandTimeoutInSeconds);
policy.ShouldIgnoreOnFirstTry = false;
Assert.False(policy.ShouldIgnoreOnFirstTry);
}
[Fact]
@@ -157,6 +204,13 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
Assert.True(shouldRety);
}
[Fact]
public void GetErrorNumberWithNullExceptionTest()
{
Assert.Null(RetryPolicy.GetErrorNumber(null));
}
/// <summary>
/// Environment variable that stores the name of the test server hosting the SQL Server instance.
/// </summary>
@@ -260,6 +314,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
Assert.True(serverInfo.ServerEdition == serverInfo2.ServerEdition);
Assert.True(serverInfo.IsCloud == serverInfo2.IsCloud);
Assert.True(serverInfo.AzureVersion == serverInfo2.AzureVersion);
Assert.True(serverInfo.IsAzureV1 == serverInfo2.IsAzureV1);
}
});
}
@@ -290,6 +345,15 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
Assert.False(isReadOnly);
}
/// <summary>
/// /// Tests ReliableConnectionHelper.IsDatabaseReadonly() with null builder parameter
/// </summary>
[Fact]
public void TestIsDatabaseReadonlyWithNullBuilder()
{
Assert.Throws<ArgumentNullException>(() => ReliableConnectionHelper.IsDatabaseReadonly(null));
}
/// <summary>
/// Verify ANSI_NULL and QUOTED_IDENTIFIER settings can be set and retrieved for a session
/// </summary>
@@ -475,6 +539,18 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
});
}
/// <summary>
/// Test that TryGetServerVersion() fails with invalid connection string
/// </summary>
[Fact]
public void TestTryGetServerVersionInvalidConnectionString()
{
TestUtils.RunIfWindows(() =>
{
ReliableConnectionHelper.ServerInfo info = null;
Assert.False(ReliableConnectionHelper.TryGetServerVersion("this is not a valid connstr", out info));
});
}
/// <summary>
/// Validate ambient static settings
@@ -561,6 +637,28 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
data.TraceSettings();
}
[Fact]
public void RaiseAmbientRetryMessageTest()
{
bool handlerCalled = false;
var data = new AmbientSettings.AmbientData();
data.ConnectionRetryMessageHandler = (a) => handlerCalled = true;
AmbientSettings._defaultSettings = data;
RetryPolicyUtils.RaiseAmbientRetryMessage(new RetryStateEx() { LastError = new Exception() }, 100);
Assert.True(handlerCalled);
}
[Fact]
public void RaiseAmbientIgnoreMessageTest()
{
bool handlerCalled = false;
var data = new AmbientSettings.AmbientData();
data.ConnectionRetryMessageHandler = (a) => handlerCalled = true;
AmbientSettings._defaultSettings = data;
RetryPolicyUtils.RaiseAmbientIgnoreMessage(new RetryStateEx() { LastError = new Exception() }, 100);
Assert.True(handlerCalled);
}
[Fact]
public void RetryPolicyFactoryTest()
{
@@ -681,6 +779,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
var detectionStrategy2 = new TestSqlAzureTemporaryAndIgnorableErrorDetectionStrategy();
Assert.NotNull(detectionStrategy2.InvokeCanRetrySqlException(sqlException));
Assert.NotNull(detectionStrategy2.InvokeShouldIgnoreSqlException(sqlException));
Batch batch = new Batch(Common.StandardQuery, Common.SubsectionDocument, Common.Ordinal, Common.GetFileStreamFactory(null));
batch.UnwrapDbException(sqlException);
}
var unknownCodeReason = RetryPolicy.ThrottlingReason.FromReasonCode(-1);
@@ -736,6 +837,119 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
Assert.Equal(exception, args.Exception);
Assert.Equal(timespan, args.Delay);
}
[Fact]
public void CheckStaticVariables()
{
Assert.NotNull(ReliableConnectionHelper.BuilderWithDefaultApplicationName);
}
[Fact]
public void SetLockAndCommandTimeoutThrowsOnNull()
{
Assert.Throws(typeof(ArgumentNullException), () => ReliableConnectionHelper.SetLockAndCommandTimeout(null));
}
[Fact]
public void StandardExceptionHandlerTests()
{
Assert.True(ReliableConnectionHelper.StandardExceptionHandler(new InvalidCastException()));
Assert.False(ReliableConnectionHelper.StandardExceptionHandler(new Exception()));
}
[Fact]
public void GetConnectionStringBuilderNullConnectionString()
{
SqlConnectionStringBuilder builder;
Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder(null, out builder));
}
[Fact]
public void GetConnectionStringBuilderExceptionTests()
{
SqlConnectionStringBuilder builder;
// throws ArgumentException
Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder("IntegratedGoldFish=True", out builder));
// throws FormatException
Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder("rabbits**frogs**lizards", out builder));
}
[Fact]
public void GetCompleteServerNameTests()
{
Assert.Null(ReliableConnectionHelper.GetCompleteServerName(null));
Assert.NotNull(ReliableConnectionHelper.GetCompleteServerName("localhost"));
Assert.NotNull(ReliableConnectionHelper.GetCompleteServerName("mytestservername"));
}
[Fact]
public void ReliableSqlCommandConstructorTests()
{
// verify default constructor doesn't throw
Assert.NotNull(new ReliableSqlConnection.ReliableSqlCommand());
// verify constructor with null connection doesn't throw
Assert.NotNull(new ReliableSqlConnection.ReliableSqlCommand(null));
}
[Fact]
public void ReliableSqlCommandProperties()
{
var command = new ReliableSqlConnection.ReliableSqlCommand();
command.CommandText = "SELECT 1";
Assert.Equal(command.CommandText, "SELECT 1");
Assert.NotNull(command.CommandTimeout);
Assert.NotNull(command.CommandType);
command.DesignTimeVisible = true;
Assert.True(command.DesignTimeVisible);
command.UpdatedRowSource = UpdateRowSource.None;
Assert.Equal(command.UpdatedRowSource, UpdateRowSource.None);
Assert.NotNull(command.GetUnderlyingCommand());
Assert.Throws<InvalidOperationException>(() => command.ValidateConnectionIsSet());
command.Prepare();
Assert.NotNull(command.CreateParameter());
command.Cancel();
}
[Fact]
public void ReliableConnectionResourcesTests()
{
Assert.NotNull(Resources.ConnectionPassedToIsCloudShouldBeOpen);
Assert.NotNull(Resources.ExceptionCannotBeRetried);
Assert.NotNull(Resources.FailedToCacheIsCloud);
Assert.NotNull(Resources.FailedToParseConnectionString);
Assert.NotNull(Resources.InvalidCommandType);
Assert.NotNull(Resources.InvalidConnectionType);
Assert.NotNull(Resources.OnlyReliableConnectionSupported);
Assert.NotNull(Resources.UnableToAssignValue);
Assert.NotNull(Resources.UnableToRetrieveAzureSessionId);
}
[Fact]
public void CalcExponentialRetryDelayWithSchemaDefaultsTest()
{
Assert.NotNull(RetryPolicyUtils.CalcExponentialRetryDelayWithSchemaDefaults(1));
}
[Fact]
public void IsSupportedCommandNullCommandTest()
{
Assert.False(DbCommandWrapper.IsSupportedCommand(null));
}
[Fact]
public void StatementCompletedTests()
{
bool handlerCalled = false;
StatementCompletedEventHandler handler = (s, e) => handlerCalled = true;
var command = new DbCommandWrapper(new SqlCommand());
command.StatementCompleted += handler;
command.StatementCompleted -= handler;
}
}
}

View File

@@ -39,8 +39,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
private Mock<RequestContext<CompletionItem[]>> requestContext;
private Mock<ScriptFile> scriptFile;
private Mock<IBinder> binder;
private ScriptParseInfo scriptParseInfo;
private TextDocumentPosition textDocument;
private void InitializeTestObjects()
@@ -60,14 +64,14 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
WorkspaceService<SqlToolsSettings>.Instance.CurrentSettings = new SqlToolsSettings();
// set up file for returning the query
var fileMock = new Mock<ScriptFile>();
fileMock.SetupGet(file => file.Contents).Returns(Common.StandardQuery);
fileMock.SetupGet(file => file.ClientFilePath).Returns(this.testScriptUri);
scriptFile = new Mock<ScriptFile>();
scriptFile.SetupGet(file => file.Contents).Returns(Common.StandardQuery);
scriptFile.SetupGet(file => file.ClientFilePath).Returns(this.testScriptUri);
// set up workspace mock
workspaceService = new Mock<WorkspaceService<SqlToolsSettings>>();
workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny<string>()))
.Returns(fileMock.Object);
.Returns(scriptFile.Object);
// setup binding queue mock
bindingQueue = new Mock<ConnectedBindingQueue>();
@@ -93,16 +97,113 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
It.IsAny<string>(),
It.IsAny<BindMode>()));
var testScriptParseInfo = new ScriptParseInfo();
LanguageService.Instance.AddOrUpdateScriptParseInfo(this.testScriptUri, testScriptParseInfo);
testScriptParseInfo.IsConnected = true;
testScriptParseInfo.ConnectionKey = LanguageService.Instance.BindingQueue.AddConnectionContext(connectionInfo);
scriptParseInfo = new ScriptParseInfo();
LanguageService.Instance.AddOrUpdateScriptParseInfo(this.testScriptUri, scriptParseInfo);
scriptParseInfo.IsConnected = true;
scriptParseInfo.ConnectionKey = LanguageService.Instance.BindingQueue.AddConnectionContext(connectionInfo);
// setup the binding context object
ConnectedBindingContext bindingContext = new ConnectedBindingContext();
bindingContext.Binder = binder.Object;
bindingContext.MetadataDisplayInfoProvider = new MetadataDisplayInfoProvider();
LanguageService.Instance.BindingQueue.BindingContextMap.Add(testScriptParseInfo.ConnectionKey, bindingContext);
LanguageService.Instance.BindingQueue.BindingContextMap.Add(scriptParseInfo.ConnectionKey, bindingContext);
}
[Fact]
public void HandleCompletionRequestDisabled()
{
InitializeTestObjects();
WorkspaceService<SqlToolsSettings>.Instance.CurrentSettings.SqlTools.IntelliSense.EnableIntellisense = false;
Assert.NotNull(LanguageService.HandleCompletionRequest(null, null));
}
[Fact]
public void HandleCompletionResolveRequestDisabled()
{
InitializeTestObjects();
WorkspaceService<SqlToolsSettings>.Instance.CurrentSettings.SqlTools.IntelliSense.EnableIntellisense = false;
Assert.NotNull(LanguageService.HandleCompletionResolveRequest(null, null));
}
[Fact]
public void HandleSignatureHelpRequestDisabled()
{
InitializeTestObjects();
WorkspaceService<SqlToolsSettings>.Instance.CurrentSettings.SqlTools.IntelliSense.EnableIntellisense = false;
Assert.NotNull(LanguageService.HandleSignatureHelpRequest(null, null));
}
[Fact]
public void AddOrUpdateScriptParseInfoNullUri()
{
InitializeTestObjects();
LanguageService.Instance.AddOrUpdateScriptParseInfo("abracadabra", scriptParseInfo);
Assert.True(LanguageService.Instance.ScriptParseInfoMap.ContainsKey("abracadabra"));
}
[Fact]
public void GetDefinitionInvalidTextDocument()
{
InitializeTestObjects();
textDocument.TextDocument.Uri = "invaliduri";
Assert.Null(LanguageService.Instance.GetDefinition(textDocument, null, null));
}
[Fact]
public void RemoveScriptParseInfoNullUri()
{
InitializeTestObjects();
Assert.False(LanguageService.Instance.RemoveScriptParseInfo("abc123"));
}
[Fact]
public void IsPreviewWindowNullScriptFileTest()
{
InitializeTestObjects();
Assert.False(LanguageService.Instance.IsPreviewWindow(null));
}
[Fact]
public void GetCompletionItemsInvalidTextDocument()
{
InitializeTestObjects();
textDocument.TextDocument.Uri = "somethinggoeshere";
Assert.True(LanguageService.Instance.GetCompletionItems(textDocument, scriptFile.Object, null).Length > 0);
}
[Fact]
public void GetDiagnosticFromMarkerTest()
{
var scriptFileMarker = new ScriptFileMarker()
{
Message = "Message",
Level = ScriptFileMarkerLevel.Error,
ScriptRegion = new ScriptRegion()
{
File = "file://nofile.sql",
StartLineNumber = 1,
StartColumnNumber = 1,
StartOffset = 0,
EndLineNumber = 1,
EndColumnNumber = 1,
EndOffset = 0
}
};
var diagnostic = DiagnosticsHelper.GetDiagnosticFromMarker(scriptFileMarker);
Assert.Equal(diagnostic.Message, scriptFileMarker.Message);
}
[Fact]
public void MapDiagnosticSeverityTest()
{
var level = ScriptFileMarkerLevel.Error;
Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Error);
level = ScriptFileMarkerLevel.Warning;
Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Warning);
level = ScriptFileMarkerLevel.Information;
Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Information);
level = (ScriptFileMarkerLevel)100;
Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Error);
}
/// <summary>

View File

@@ -3,8 +3,10 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlServer.Management.SqlParser.Parser;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
@@ -143,6 +145,56 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServer
Assert.Null(signatureHelp);
}
[Fact]
public void EmptyCompletionListTest()
{
Assert.Equal(AutoCompleteHelper.EmptyCompletionList.Length, 0);
}
[Fact]
public void SetWorkspaceServiceInstanceTest()
{
AutoCompleteHelper.WorkspaceServiceInstance = null;
// workspace will be recreated if it's set to null
Assert.NotNull(AutoCompleteHelper.WorkspaceServiceInstance);
}
internal class TestScriptDocumentInfo : ScriptDocumentInfo
{
public TestScriptDocumentInfo(TextDocumentPosition textDocumentPosition, ScriptFile scriptFile, ScriptParseInfo scriptParseInfo)
:base(textDocumentPosition, scriptFile, scriptParseInfo)
{
}
public override string TokenText
{
get
{
return "doesntmatchanythingintheintellisensedefaultlist";
}
}
}
[Fact]
public void GetDefaultCompletionListWithNoMatchesTest()
{
var scriptFile = new ScriptFile();
scriptFile.SetFileContents("koko wants a bananas");
ScriptParseInfo scriptInfo = new ScriptParseInfo { IsConnected = false };
var scriptDocumentInfo = new TestScriptDocumentInfo(
new TextDocumentPosition()
{
TextDocument = new TextDocumentIdentifier() { Uri = TestObjects.ScriptUri },
Position = new Position() { Line = 0, Character = 0 }
}, scriptFile, scriptInfo);
AutoCompleteHelper.GetDefaultCompletionItems(scriptDocumentInfo, false);
}
private TextDocumentPosition CreateDummyDocPosition()
{
return new TextDocumentPosition
@@ -180,11 +232,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServer
connInfo = TestObjects.InitLiveConnectionInfo(out scriptFile);
}
/// <summary>
/// Test the service initialization code path and verify nothing throws
/// </summary>
// Test is causing failures in build lab..investigating to reenable
[Fact]
public void ServiceInitialization()
{
@@ -200,12 +251,11 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServer
Assert.True(LanguageService.ConnectionServiceInstance != null);
Assert.True(LanguageService.Instance.CurrentSettings != null);
Assert.True(LanguageService.Instance.CurrentWorkspace != null);
}
}
/// <summary>
/// Test the service initialization code path and verify nothing throws
/// </summary>
// Test is causing failures in build lab..investigating to reenable
[Fact]
public void PrepopulateCommonMetadata()
{

View File

@@ -197,9 +197,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
public void GetValidTableDefinitionTest()
{
// Get live connectionInfo
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
PeekDefinition peekDefinition = new PeekDefinition(connInfo);
string objectName = "test_table";
PeekDefinition peekDefinition = new PeekDefinition(TestObjects.InitLiveConnectionInfoForDefinition());
string objectName = "spt_monitor";
string schemaName = null;
string objectType = "TABLE";
@@ -216,8 +215,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
public void GetTableDefinitionInvalidObjectTest()
{
// Get live connectionInfo
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
PeekDefinition peekDefinition = new PeekDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(TestObjects.InitLiveConnectionInfoForDefinition());
string objectName = "test_invalid";
string schemaName = null;
string objectType = "TABLE";
@@ -234,9 +232,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
public void GetTableDefinitionWithSchemaTest()
{
// Get live connectionInfo
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
PeekDefinition peekDefinition = new PeekDefinition(connInfo);
string objectName = "test_table";
PeekDefinition peekDefinition = new PeekDefinition(TestObjects.InitLiveConnectionInfoForDefinition());
string objectName = "spt_monitor";
string schemaName = "dbo";
string objectType = "TABLE";
@@ -279,9 +276,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
/// </summary>
[Fact]
public void GetValidViewDefinitionTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
PeekDefinition peekDefinition = new PeekDefinition(connInfo);
{
PeekDefinition peekDefinition = new PeekDefinition(TestObjects.InitLiveConnectionInfoForDefinition());
string objectName = "objects";
string schemaName = "sys";
string objectType = "VIEW";
@@ -297,8 +293,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
[Fact]
public void GetViewDefinitionInvalidObjectTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
PeekDefinition peekDefinition = new PeekDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(TestObjects.InitLiveConnectionInfoForDefinition());
string objectName = "objects";
string schemaName = null;
string objectType = "VIEW";
@@ -313,9 +308,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
[Fact]
public void GetStoredProcedureDefinitionTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
PeekDefinition peekDefinition = new PeekDefinition(connInfo);
string objectName = "SP1";
PeekDefinition peekDefinition = new PeekDefinition(TestObjects.InitLiveConnectionInfoForDefinition());
string objectName = "sp_MSrepl_startup";
string schemaName = "dbo";
string objectType = "PROCEDURE";
@@ -330,8 +324,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
[Fact]
public void GetStoredProcedureDefinitionFailureTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
PeekDefinition peekDefinition = new PeekDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(TestObjects.InitLiveConnectionInfoForDefinition());
string objectName = "SP2";
string schemaName = "dbo";
string objectType = "PROCEDURE";
@@ -346,9 +339,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
[Fact]
public void GetStoredProcedureDefinitionWithoutSchemaTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
PeekDefinition peekDefinition = new PeekDefinition(connInfo);
string objectName = "SP1";
PeekDefinition peekDefinition = new PeekDefinition(TestObjects.InitLiveConnectionInfoForDefinition());
string objectName = "sp_MSrepl_startup";
string schemaName = null;
string objectType = "PROCEDURE";

View File

@@ -0,0 +1,88 @@
//
// 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.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Channel;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Contracts;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Messaging
{
public class MessageDispatcherTests
{
[Fact]
public void SetRequestHandlerWithOverrideTest()
{
RequestType<int, int> requestType = RequestType<int, int>.Create("test/requestType");
var dispatcher = new MessageDispatcher(new Mock<ChannelBase>().Object);
dispatcher.SetRequestHandler<int, int>(
requestType,
(i, j) =>
{
return Task.FromResult(0);
},
true);
Assert.True(dispatcher.requestHandlers.Count > 0);
}
[Fact]
public void SetEventHandlerTest()
{
EventType<int> eventType = EventType<int>.Create("test/eventType");
var dispatcher = new MessageDispatcher(new Mock<ChannelBase>().Object);
dispatcher.SetEventHandler<int>(
eventType,
(i, j) =>
{
return Task.FromResult(0);
});
Assert.True(dispatcher.eventHandlers.Count > 0);
}
[Fact]
public void SetEventHandlerWithOverrideTest()
{
EventType<int> eventType = EventType<int>.Create("test/eventType");
var dispatcher = new MessageDispatcher(new Mock<ChannelBase>().Object);
dispatcher.SetEventHandler<int>(
eventType,
(i, j) =>
{
return Task.FromResult(0);
},
true);
Assert.True(dispatcher.eventHandlers.Count > 0);
}
[Fact]
public void OnListenTaskCompletedFaultedTaskTest()
{
Task t = null;
try
{
t = Task.Run(() =>
{
throw new Exception();
});
t.Wait();
}
catch
{
}
finally
{
bool handlerCalled = false;
var dispatcher = new MessageDispatcher(new Mock<ChannelBase>().Object);
dispatcher.UnhandledException += (s, e) => handlerCalled = true;
dispatcher.OnListenTaskCompleted(t);
Assert.True(handlerCalled);
}
}
}
}

View File

@@ -7,7 +7,9 @@ using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Serializers;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Messaging
@@ -21,6 +23,40 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Messaging
this.messageSerializer = new V8MessageSerializer();
}
[Fact]
public void SerializeMessageTest()
{
// serialize\deserialize a request
var message = new Message();
message.MessageType = MessageType.Request;
message.Id = "id";
message.Method = "method";
message.Contents = null;
var serializedMessage = this.messageSerializer.SerializeMessage(message);
Assert.NotNull(serializedMessage);
var deserializedMessage = this.messageSerializer.DeserializeMessage(serializedMessage);
Assert.Equal(message.Id, deserializedMessage.Id);
// serialize\deserialize a response
message.MessageType = MessageType.Response;
serializedMessage = this.messageSerializer.SerializeMessage(message);
Assert.NotNull(serializedMessage);
deserializedMessage = this.messageSerializer.DeserializeMessage(serializedMessage);
Assert.Equal(message.Id, deserializedMessage.Id);
// serialize\deserialize a response with an error
message.Error = JToken.FromObject("error");
serializedMessage = this.messageSerializer.SerializeMessage(message);
Assert.NotNull(serializedMessage);
deserializedMessage = this.messageSerializer.DeserializeMessage(serializedMessage);
Assert.Equal(message.Error, deserializedMessage.Error);
// serialize\deserialize an unknown response type
serializedMessage.Remove("type");
serializedMessage.Add("type", JToken.FromObject("dontknowthisone"));
Assert.Equal(this.messageSerializer.DeserializeMessage(serializedMessage).MessageType, MessageType.Unknown);
}
[Fact]
public async Task WritesMessage()
{

View File

@@ -5,6 +5,7 @@
#if LIVE_CONNECTION_TESTS
using System;
using System.Data.Common;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
@@ -60,8 +61,13 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.DataStorage
reader.Read();
Assert.False(storageReader.IsDBNull(0));
Assert.NotNull(storageReader.GetValue(0));
string shortName = storageReader.GetCharsWithMaxCapacity(0, 2);
Assert.True(shortName.Length == 2);
Assert.Throws<ArgumentOutOfRangeException>(() => storageReader.GetBytesWithMaxCapacity(0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => storageReader.GetCharsWithMaxCapacity(0, 0));
}
/// <summary>
@@ -88,10 +94,15 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.DataStorage
[Fact]
public void StringWriterWithMaxCapacityTest()
{
var writer = new StorageDataReader.StringWriterWithMaxCapacity(null, 100);
var writer = new StorageDataReader.StringWriterWithMaxCapacity(null, 4);
string output = "...";
writer.Write(output);
Assert.True(writer.ToString().Equals(output));
writer.Write('.');
Assert.True(writer.ToString().Equals(output + '.'));
writer.Write(output);
writer.Write('.');
Assert.True(writer.ToString().Equals(output + '.'));
}
}
}

View File

@@ -5,7 +5,9 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -388,8 +390,22 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// Then:
// ... It should throw an exception
Assert.Throws<ArgumentOutOfRangeException>(() => new Batch("stuff", Common.SubsectionDocument, -1, Common.GetFileStreamFactory(null)));
}
}
[Fact]
public void StatementCompletedHandlerTest()
{
// If:
// ... I call the StatementCompletedHandler
// Then:
// ... a ResultMaessage should be logged in the resultsMessages collection
Batch batch = new Batch(Common.StandardQuery, Common.SubsectionDocument, Common.Ordinal, Common.GetFileStreamFactory(null));
batch.StatementCompletedHandler(null, new StatementCompletedEventArgs(1));
Assert.True(batch.ResultMessages.Count() == 1);
batch.StatementCompletedHandler(null, new StatementCompletedEventArgs(2));
Assert.True(batch.ResultMessages.Count() == 2);
}
private static DbConnection GetConnection(ConnectionInfo info)
{
return info.Factory.CreateSqlConnection(ConnectionService.BuildConnectionString(info.ConnectionDetails));

View File

@@ -0,0 +1,114 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Data.Common;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
/// <summary>
/// DbColumnWrapper tests
/// </summary>
public class DbColumnWrapperTests
{
/// <summary>
/// Test DbColumn derived class
/// </summary>
class TestColumn : DbColumn
{
public TestColumn(
string dataTypeName = null,
int? columnSize = null,
string columnName = null,
string udtAssemblyQualifiedName = null)
{
if (!string.IsNullOrEmpty(dataTypeName))
{
this.DataTypeName = dataTypeName;
}
if (columnSize.HasValue)
{
this.ColumnSize = columnSize;
}
if (!string.IsNullOrEmpty(columnName))
{
this.ColumnName = columnName;
}
if (!string.IsNullOrEmpty(udtAssemblyQualifiedName))
{
this.UdtAssemblyQualifiedName = udtAssemblyQualifiedName;
}
}
}
/// <summary>
/// Basic data type and properites test
/// </summary>
[Fact]
public void DataTypeAndPropertiesTest()
{
// check that data types array contains items
var serverDataTypes = DbColumnWrapper.AllServerDataTypes;
Assert.True(serverDataTypes.Count > 0);
// check default constructor doesn't throw
Assert.NotNull(new DbColumnWrapper());
// check various properties are either null or not null
var column = new TestColumn();
var wrapper = new DbColumnWrapper(column);
Assert.NotNull(wrapper.DataType);
Assert.Null(wrapper.AllowDBNull);
Assert.Null(wrapper.BaseCatalogName);
Assert.Null(wrapper.BaseColumnName);
Assert.Null(wrapper.BaseServerName);
Assert.Null(wrapper.BaseTableName);
Assert.Null(wrapper.ColumnOrdinal);
Assert.Null(wrapper.ColumnSize);
Assert.Null(wrapper.IsAliased);
Assert.Null(wrapper.IsAutoIncrement);
Assert.Null(wrapper.IsExpression);
Assert.Null(wrapper.IsHidden);
Assert.Null(wrapper.IsIdentity);
Assert.Null(wrapper.IsKey);
Assert.Null(wrapper. IsReadOnly);
Assert.Null(wrapper.IsUnique);
Assert.Null(wrapper.NumericPrecision);
Assert.Null(wrapper.NumericScale);
Assert.Null(wrapper.UdtAssemblyQualifiedName);
Assert.Null(wrapper.DataTypeName);
}
/// <summary>
/// constructor test
/// </summary>
[Fact]
public void DbColumnConstructorTests()
{
// check that various constructor parameters initial the wrapper correctly
var w1 = new DbColumnWrapper(new TestColumn("varchar", int.MaxValue, "Microsoft SQL Server 2005 XML Showplan"));
Assert.True(w1.IsXml);
var w2 = new DbColumnWrapper(new TestColumn("binary"));
Assert.True(w2.IsBytes);
var w3 = new DbColumnWrapper(new TestColumn("varbinary", int.MaxValue));
Assert.True(w3.IsBytes);
var w4 = new DbColumnWrapper(new TestColumn("sql_variant"));
Assert.True(w4.IsSqlVariant);
var w5 = new DbColumnWrapper(new TestColumn("my_udt"));
Assert.True(w5.IsUdt);
var w6 = new DbColumnWrapper(new TestColumn("my_hieracrchy", null, null, "MICROSOFT.SQLSERVER.TYPES.SQLHIERARCHYID"));
Assert.True(w6.IsUdt);
}
}
}

View File

@@ -25,5 +25,34 @@ namespace Microsoft.SqlTools.Test.Utility
longList.RemoveAt(0);
Assert.True(longList.Count == 0);
}
/// <summary>
/// Add and remove and item in a LongList causing an expansion
/// </summary>
[Fact]
public void LongListExpandTest()
{
var longList = new LongList<int>();
longList.ExpandListSize = 3;
for (int i = 0; i < 6; ++i)
{
longList.Add(i);
}
Assert.Equal(longList.Count, 6);
Assert.NotNull(longList.GetItem(4));
bool didEnum = false;
foreach (var j in longList)
{
didEnum = true;
break;
}
Assert.True(didEnum);
longList.RemoveAt(4);
Assert.Equal(longList.Count, 5);
}
}
}

View File

@@ -0,0 +1,27 @@
//
// 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.ServiceLayer;
using Xunit;
namespace Microsoft.SqlTools.Test.Utility
{
public class SrTests
{
/// <summary>
/// Add and remove and item in a LongList
/// </summary>
[Fact]
public void SrPropertiesTest()
{
Assert.NotNull(new SR());
Assert.NotNull(SR.QueryServiceSubsetBatchNotCompleted);
Assert.NotNull(SR.QueryServiceFileWrapperWriteOnly);
Assert.NotNull(SR.QueryServiceFileWrapperNotInitialized);
Assert.NotNull(SR.QueryServiceColumnNull);
Assert.NotNull(new SR.Keys());
}
}
}

View File

@@ -7,8 +7,10 @@ using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Credentials;
@@ -192,7 +194,7 @@ namespace Microsoft.SqlTools.Test.Utility
return connInfo;
}
public static ConnectionInfo InitLiveConnectionInfoForDefinition()
public static ServerConnection InitLiveConnectionInfoForDefinition()
{
TestObjects.InitializeTestServices();
@@ -210,7 +212,9 @@ namespace Microsoft.SqlTools.Test.Utility
ConnectionInfo connInfo = null;
connectionService.TryFindConnection(ownerUri, out connInfo);
return connInfo;
SqlConnection sqlConn = new SqlConnection(ConnectionService.BuildConnectionString(connInfo.ConnectionDetails));
return new ServerConnection(sqlConn);
}
}

View File

@@ -0,0 +1,38 @@
//
// 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 Microsoft.SqlTools.ServiceLayer.Utility;
using Xunit;
namespace Microsoft.SqlTools.Test.Utility
{
public class ValidateTests
{
[Fact]
public void IsWithinRangeTest()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Validate.IsWithinRange("parameterName", 1, 2, 3));
}
[Fact]
public void IsLessThanTest()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Validate.IsLessThan("parameterName", 2, 1));
}
[Fact]
public void IsNotEqualTest()
{
Assert.Throws<ArgumentException>(() => Validate.IsNotEqual<int>("parameterName", 1, 1));
}
[Fact]
public void IsNullOrWhiteSpaceTest()
{
Assert.Throws<ArgumentException>(() => Validate.IsNotNullOrWhitespaceString("parameterName", null));
}
}
}

View File

@@ -3,10 +3,12 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
@@ -90,5 +92,58 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Workspace
Assert.Empty(workspace.GetOpenedFiles());
Assert.False(callbackCalled);
}
[Fact]
public void BufferRangeNoneNotNull()
{
Assert.NotNull(BufferRange.None);
}
[Fact]
public void BufferRangeStartGreaterThanEnd()
{
Assert.Throws<ArgumentException>(() =>
new BufferRange(new BufferPosition(2, 2), new BufferPosition(1, 1)));
}
[Fact]
public void BufferRangeEquals()
{
var range = new BufferRange(new BufferPosition(1, 1), new BufferPosition(2, 2));
Assert.False(range.Equals(null));
Assert.True(range.Equals(range));
Assert.NotNull(range.GetHashCode());
}
[Fact]
public void UnescapePath()
{
Assert.NotNull(Microsoft.SqlTools.ServiceLayer.Workspace.Workspace.UnescapePath("`/path/`"));
}
[Fact]
public void GetBaseFilePath()
{
TestUtils.RunIfWindows(() =>
{
using (var workspace = new ServiceLayer.Workspace.Workspace())
{
Assert.Throws<InvalidOperationException>(() => workspace.GetBaseFilePath("path"));
Assert.NotNull(workspace.GetBaseFilePath(@"c:\path\file.sql"));
Assert.Equal(workspace.GetBaseFilePath("tsqloutput://c:/path/file.sql"), workspace.WorkspacePath);
}
});
}
[Fact]
public void ResolveRelativeScriptPath()
{
TestUtils.RunIfWindows(() =>
{
var workspace = new ServiceLayer.Workspace.Workspace();
Assert.NotNull(workspace.ResolveRelativeScriptPath(null, @"c:\path\file.sql"));
Assert.NotNull(workspace.ResolveRelativeScriptPath(@"c:\path\", "file.sql"));
});
}
}
}