Convert most tools service tests to nunit (#1037)

* Remove xunit dependency from testdriver

* swap expected/actual as needed

* Convert Test.Common to nunit

* port hosting unit tests to nunit

* port batchparser integration tests to nunit

* port testdriver.tests to nunit

* fix target to copy dependency

* port servicelayer unittests to nunit

* more unit test fixes

* port integration tests to nunit

* fix test method type

* try using latest windows build for PRs

* reduce test memory use
This commit is contained in:
David Shiflet
2020-08-05 13:43:14 -04:00
committed by GitHub
parent bf4911795f
commit 839acf67cd
205 changed files with 4146 additions and 4329 deletions
+2
View File
@@ -23,6 +23,8 @@
<PackageReference Update="Moq" Version="4.8.2" /> <PackageReference Update="Moq" Version="4.8.2" />
<PackageReference Update="NUnit" Version="3.12.0" /> <PackageReference Update="NUnit" Version="3.12.0" />
<PackageReference Update="nunit3TestAdapter" Version="3.17.0" />
<PackageReference Update="nunit.console" version="3.11.1" />
<PackageReference Update="xunit" Version="2.4.1" /> <PackageReference Update="xunit" Version="2.4.1" />
<PackageReference Update="xunit.runner.visualstudio" Version="2.4.1" /> <PackageReference Update="xunit.runner.visualstudio" Version="2.4.1" />
<PackageReference Update="Microsoft.NET.Test.Sdk" Version="16.6.1" /> <PackageReference Update="Microsoft.NET.Test.Sdk" Version="16.6.1" />
+1 -1
View File
@@ -1,5 +1,5 @@
pool: pool:
name: Hosted VS2017 vmImage: 'windows-latest'
demands: demands:
- Cmd - Cmd
- npm - npm
@@ -683,23 +683,23 @@ namespace Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode
DbConnectionWrapper connectionWrapper = new DbConnectionWrapper(connection); DbConnectionWrapper connectionWrapper = new DbConnectionWrapper(connection);
connectionWrapper.InfoMessage += messageHandler; connectionWrapper.InfoMessage += messageHandler;
IDbCommand command = connection.CreateCommand(); IDbCommand localCommand = connection.CreateCommand();
command.CommandText = script; localCommand.CommandText = script;
command.CommandTimeout = execTimeout; localCommand.CommandTimeout = execTimeout;
DbCommandWrapper commandWrapper = null; DbCommandWrapper commandWrapper = null;
if (isScriptExecutionTracked && DbCommandWrapper.IsSupportedCommand(command)) if (isScriptExecutionTracked && DbCommandWrapper.IsSupportedCommand(localCommand))
{ {
statementCompletedHandler = new StatementCompletedEventHandler(OnStatementExecutionFinished); statementCompletedHandler = new StatementCompletedEventHandler(OnStatementExecutionFinished);
commandWrapper = new DbCommandWrapper(command); commandWrapper = new DbCommandWrapper(localCommand);
commandWrapper.StatementCompleted += statementCompletedHandler; commandWrapper.StatementCompleted += statementCompletedHandler;
} }
lock (this) lock (this)
{ {
state = BatchState.Executing; state = BatchState.Executing;
this.command = command; command = localCommand;
command = null; localCommand = null;
} }
try try
@@ -20,7 +20,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.SqlServer.DACFx" /> <PackageReference Include="Microsoft.SqlServer.DACFx" />
<PackageReference Include="Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider" /> <PackageReference Include="Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider" />
<PackageReference Include="System.Text.Encoding.CodePages" /> <PackageReference Include="System.Text.Encoding.CodePages" />
</ItemGroup> </ItemGroup>
@@ -45,4 +45,23 @@
<ItemGroup> <ItemGroup>
<EmbeddedResource Include=".\Agent\NotebookResources\NotebookJobScript.ps1" /> <EmbeddedResource Include=".\Agent\NotebookResources\NotebookJobScript.ps1" />
</ItemGroup> </ItemGroup>
<!-- this target enables dependency files to be copied as part of the output of ProjectReference.
https://github.com/dotnet/sdk/issues/1675
-->
<Target Name="AddRuntimeDependenciesToContent"
Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"
BeforeTargets="GetCopyToOutputDirectoryItems"
DependsOnTargets="GenerateBuildDependencyFile;
GenerateBuildRuntimeConfigurationFiles">
<ItemGroup>
<ContentWithTargetPath Include="$(ProjectDepsFilePath)"
Condition="'$(GenerateDependencyFile)' == 'true'"
CopyToOutputDirectory="PreserveNewest"
TargetPath="$(ProjectDepsFileName)" />
<ContentWithTargetPath Include="$(ProjectRuntimeConfigFilePath)"
Condition="'$(GenerateRuntimeConfigurationFiles)' == 'true'"
CopyToOutputDirectory="PreserveNewest"
TargetPath="$(ProjectRuntimeConfigFileName)" />
</ItemGroup>
</Target>
</Project> </Project>
@@ -8,7 +8,8 @@ using Microsoft.SqlTools.Hosting.Contracts;
using Microsoft.SqlTools.Hosting.Contracts.Internal; using Microsoft.SqlTools.Hosting.Contracts.Internal;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using NUnit.Framework.Interfaces;
namespace Microsoft.SqlTools.Hosting.UnitTests namespace Microsoft.SqlTools.Hosting.UnitTests
{ {
public static class CommonObjects public static class CommonObjects
@@ -51,6 +52,15 @@ namespace Microsoft.SqlTools.Hosting.UnitTests
&& Number == other.Number; && Number == other.Number;
} }
public override bool Equals(object obj)
{
return Equals(obj as TestMessageContents);
}
public override int GetHashCode()
{
return SomeField.GetHashCode() ^ Number;
}
public static bool operator ==(TestMessageContents obj1, TestMessageContents obj2) public static bool operator ==(TestMessageContents obj1, TestMessageContents obj2)
{ {
bool bothNull = ReferenceEquals(obj1, null) && ReferenceEquals(obj2, null); bool bothNull = ReferenceEquals(obj1, null) && ReferenceEquals(obj2, null);
@@ -1,38 +1,39 @@
// //
// 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.DataProtocol.Contracts.Utilities; using Microsoft.SqlTools.DataProtocol.Contracts.Utilities;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
{ {
[TestFixture]
public class FlagsIntConverterTests public class FlagsIntConverterTests
{ {
[Fact] [Test]
public void NullableValueCanBeDeserialized() public void NullableValueCanBeDeserialized()
{ {
var jsonObject = JObject.Parse("{\"optionalValue\": [1, 2]}"); var jsonObject = JObject.Parse("{\"optionalValue\": [1, 2]}");
var contract = jsonObject.ToObject<DataContract>(); var contract = jsonObject.ToObject<DataContract>();
Assert.NotNull(contract); Assert.NotNull(contract);
Assert.NotNull(contract.OptionalValue); Assert.NotNull(contract.OptionalValue);
Assert.Equal(TestFlags.FirstItem | TestFlags.SecondItem, contract.OptionalValue); Assert.AreEqual(TestFlags.FirstItem | TestFlags.SecondItem, contract.OptionalValue);
} }
[Fact] [Test]
public void RegularValueCanBeDeserialized() public void RegularValueCanBeDeserialized()
{ {
var jsonObject = JObject.Parse("{\"Value\": [1, 3]}"); var jsonObject = JObject.Parse("{\"Value\": [1, 3]}");
var contract = jsonObject.ToObject<DataContract>(); var contract = jsonObject.ToObject<DataContract>();
Assert.NotNull(contract); Assert.NotNull(contract);
Assert.Equal(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value); Assert.AreEqual(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value);
} }
[Fact] [Test]
public void ExplicitNullCanBeDeserialized() public void ExplicitNullCanBeDeserialized()
{ {
var jsonObject = JObject.Parse("{\"optionalValue\": null}"); var jsonObject = JObject.Parse("{\"optionalValue\": null}");
@@ -42,7 +43,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
} }
[Flags] [Flags]
[JsonConverter(typeof(FlagsIntConverter))] [JsonConverter(typeof(FlagsIntConverter))]
private enum TestFlags private enum TestFlags
{ {
[FlagsIntConverter.SerializeValue(1)] [FlagsIntConverter.SerializeValue(1)]
@@ -52,7 +53,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
SecondItem = 1 << 1, SecondItem = 1 << 1,
[FlagsIntConverter.SerializeValue(3)] [FlagsIntConverter.SerializeValue(3)]
ThirdItem = 1 << 2, ThirdItem = 1 << 2,
} }
private class DataContract private class DataContract
@@ -1,38 +1,39 @@
// //
// 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 Microsoft.SqlTools.DataProtocol.Contracts.Utilities; using Microsoft.SqlTools.DataProtocol.Contracts.Utilities;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
{ {
[TestFixture]
public class FlagsStringConverterTests public class FlagsStringConverterTests
{ {
[Fact] [Test]
public void NullableValueCanBeDeserialized() public void NullableValueCanBeDeserialized()
{ {
var jsonObject = JObject.Parse("{\"optionalValue\": [\"First\", \"Second\"]}"); var jsonObject = JObject.Parse("{\"optionalValue\": [\"First\", \"Second\"]}");
var contract = jsonObject.ToObject<DataContract>(); var contract = jsonObject.ToObject<DataContract>();
Assert.NotNull(contract); Assert.NotNull(contract);
Assert.NotNull(contract.OptionalValue); Assert.NotNull(contract.OptionalValue);
Assert.Equal(TestFlags.FirstItem | TestFlags.SecondItem, contract.OptionalValue); Assert.AreEqual(TestFlags.FirstItem | TestFlags.SecondItem, contract.OptionalValue);
} }
[Fact] [Test]
public void RegularValueCanBeDeserialized() public void RegularValueCanBeDeserialized()
{ {
var jsonObject = JObject.Parse("{\"Value\": [\"First\", \"Third\"]}"); var jsonObject = JObject.Parse("{\"Value\": [\"First\", \"Third\"]}");
var contract = jsonObject.ToObject<DataContract>(); var contract = jsonObject.ToObject<DataContract>();
Assert.NotNull(contract); Assert.NotNull(contract);
Assert.Equal(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value); Assert.AreEqual(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value);
} }
[Fact] [Test]
public void ExplicitNullCanBeDeserialized() public void ExplicitNullCanBeDeserialized()
{ {
var jsonObject = JObject.Parse("{\"optionalValue\": null}"); var jsonObject = JObject.Parse("{\"optionalValue\": null}");
@@ -42,7 +43,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
} }
[Flags] [Flags]
[JsonConverter(typeof(FlagsStringConverter))] [JsonConverter(typeof(FlagsStringConverter))]
private enum TestFlags private enum TestFlags
{ {
[FlagsStringConverter.SerializeValue("First")] [FlagsStringConverter.SerializeValue("First")]
@@ -52,7 +53,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
SecondItem = 1 << 1, SecondItem = 1 << 1,
[FlagsStringConverter.SerializeValue("Third")] [FlagsStringConverter.SerializeValue("Third")]
ThirdItem = 1 << 2, ThirdItem = 1 << 2,
} }
private class DataContract private class DataContract
@@ -7,19 +7,23 @@ using System;
using System.Linq; using System.Linq;
using Microsoft.SqlTools.Hosting.Extensibility; using Microsoft.SqlTools.Hosting.Extensibility;
using Microsoft.SqlTools.Hosting.Utility; using Microsoft.SqlTools.Hosting.Utility;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
{ {
[TestFixture]
public class ServiceProviderTests public class ServiceProviderTests
{ {
private readonly RegisteredServiceProvider provider; private RegisteredServiceProvider provider;
public ServiceProviderTests()
[SetUp]
public void SetupServiceProviderTests()
{ {
provider = new RegisteredServiceProvider(); provider = new RegisteredServiceProvider();
} }
[Fact] [Test]
public void GetServiceShouldReturnNullIfNoServicesRegistered() public void GetServiceShouldReturnNullIfNoServicesRegistered()
{ {
// Given no service registered // Given no service registered
@@ -30,7 +34,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
} }
[Fact] [Test]
public void GetSingleServiceThrowsMultipleServicesRegistered() public void GetSingleServiceThrowsMultipleServicesRegistered()
{ {
// Given 2 services registered // Given 2 services registered
@@ -40,44 +44,43 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
Assert.Throws<InvalidOperationException>(() => provider.GetService<MyProviderService>()); Assert.Throws<InvalidOperationException>(() => provider.GetService<MyProviderService>());
} }
[Fact] [Test]
public void GetServicesShouldReturnEmptyIfNoServicesRegistered() public void GetServicesShouldReturnEmptyIfNoServicesRegistered()
{ {
// Given no service regisstered // Given no service regisstered
// When I call GetService // When I call GetService
var services = provider.GetServices<MyProviderService>(); var services = provider.GetServices<MyProviderService>();
// Then I expect empty enumerable to be returned Assert.That(services, Is.Empty, "provider.GetServices with no service registered");
Assert.NotNull(services);
Assert.Empty(services);
} }
[Fact] [Test]
public void GetServiceShouldReturnRegisteredService() public void GetServiceShouldReturnRegisteredService()
{ {
MyProviderService service = new MyProviderService(); MyProviderService service = new MyProviderService();
provider.RegisterSingleService(service); provider.RegisterSingleService(service);
var returnedService = provider.GetService<MyProviderService>(); var returnedService = provider.GetService<MyProviderService>();
Assert.Equal(service, returnedService); Assert.AreEqual(service, returnedService);
} }
[Fact] // DEVNOTE: The name of this test doesn't match the code, which is pretty much the same as the one above.
[Test]
public void GetServicesShouldReturnRegisteredServiceWhenMultipleServicesRegistered() public void GetServicesShouldReturnRegisteredServiceWhenMultipleServicesRegistered()
{ {
MyProviderService service = new MyProviderService(); MyProviderService service = new MyProviderService();
provider.RegisterSingleService(service); provider.RegisterSingleService(service);
var returnedServices = provider.GetServices<MyProviderService>(); var returnedServices = provider.GetServices<MyProviderService>();
Assert.Equal(service, returnedServices.Single()); Assert.AreEqual(service, returnedServices.Single());
} }
[Fact] [Test]
public void RegisterServiceProviderShouldThrowIfServiceIsIncompatible() public void RegisterServiceProviderShouldThrowIfServiceIsIncompatible()
{ {
MyProviderService service = new MyProviderService(); MyProviderService service = new MyProviderService();
Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(typeof(OtherService), service)); Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(typeof(OtherService), service));
} }
[Fact] [Test]
public void RegisterServiceProviderShouldThrowIfServiceAlreadyRegistered() public void RegisterServiceProviderShouldThrowIfServiceAlreadyRegistered()
{ {
MyProviderService service = new MyProviderService(); MyProviderService service = new MyProviderService();
@@ -86,7 +89,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(service)); Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(service));
} }
[Fact] [Test]
public void RegisterShouldThrowIfServiceAlreadyRegistered() public void RegisterShouldThrowIfServiceAlreadyRegistered()
{ {
MyProviderService service = new MyProviderService(); MyProviderService service = new MyProviderService();
@@ -95,7 +98,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
Assert.Throws<InvalidOperationException>(() => provider.Register(() => service.AsSingleItemEnumerable())); Assert.Throws<InvalidOperationException>(() => provider.Register(() => service.AsSingleItemEnumerable()));
} }
[Fact] [Test]
public void RegisterShouldThrowIfServicesAlreadyRegistered() public void RegisterShouldThrowIfServicesAlreadyRegistered()
{ {
provider.Register(() => new [] { new MyProviderService(), new MyProviderService() }); provider.Register(() => new [] { new MyProviderService(), new MyProviderService() });
@@ -7,8 +7,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Moq"/> <PackageReference Include="Moq"/>
<PackageReference Include="xunit"/> <PackageReference Include="nunit"/>
<PackageReference Include="xunit.runner.visualstudio" /> <PackageReference Include="nunit3testadapter"/>
<PackageReference Include="nunit.console"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src\Microsoft.SqlTools.DataProtocol.Contracts\Microsoft.SqlTools.DataProtocol.Contracts.csproj" /> <ProjectReference Include="..\..\src\Microsoft.SqlTools.DataProtocol.Contracts\Microsoft.SqlTools.DataProtocol.Contracts.csproj" />
@@ -4,14 +4,16 @@
// //
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Linq;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{ {
[TestFixture]
public class EventContextTests public class EventContextTests
{ {
[Fact] [Test]
public void SendEvent() public void SendEvent()
{ {
// Setup: Create collection // Setup: Create collection
@@ -20,11 +22,11 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I construct an event context with a message writer // If: I construct an event context with a message writer
// And send an event with it // And send an event with it
var eventContext = new EventContext(bc); var eventContext = new EventContext(bc);
eventContext.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance); eventContext.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message should be added to the queue // Then: The message should be added to the queue
Assert.Single(bc.ToArray()); var messages = bc.ToArray().Select(m => m.MessageType);
Assert.Equal(MessageType.Event, bc.ToArray()[0].MessageType); Assert.That(messages, Is.EqualTo(new[] { MessageType.Event }), "Single message of type event in the queue after SendEvent");
} }
} }
} }
@@ -12,13 +12,14 @@ using Microsoft.SqlTools.Hosting.Channels;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{ {
[TestFixture]
public class JsonRpcHostTests public class JsonRpcHostTests
{ {
[Fact] [Test]
public void ConstructWithNullProtocolChannel() public void ConstructWithNullProtocolChannel()
{ {
// If: I construct a JSON RPC host with a null protocol channel // If: I construct a JSON RPC host with a null protocol channel
@@ -28,7 +29,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
#region SetRequestHandler Tests #region SetRequestHandler Tests
[Fact] [Test]
public void SetAsyncRequestHandlerNullRequestType() public void SetAsyncRequestHandlerNullRequestType()
{ {
// If: I assign a request handler on the JSON RPC host with a null request type // If: I assign a request handler on the JSON RPC host with a null request type
@@ -38,7 +39,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
jh.SetAsyncRequestHandler<object, object>(null, (a, b) => Task.FromResult(false))); jh.SetAsyncRequestHandler<object, object>(null, (a, b) => Task.FromResult(false)));
} }
[Fact] [Test]
public void SetAsyncRequestHandlerNullRequestHandler() public void SetAsyncRequestHandlerNullRequestHandler()
{ {
// If: I assign a request handler on the JSON RPC host with a null request handler // If: I assign a request handler on the JSON RPC host with a null request handler
@@ -47,7 +48,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<ArgumentNullException>(() => jh.SetAsyncRequestHandler(CommonObjects.RequestType, null)); Assert.Throws<ArgumentNullException>(() => jh.SetAsyncRequestHandler(CommonObjects.RequestType, null));
} }
[Fact] [Test]
public void SetSyncRequestHandlerNullRequestHandler() public void SetSyncRequestHandlerNullRequestHandler()
{ {
// If: I assign a request handler on the JSON RPC host with a null request handler // If: I assign a request handler on the JSON RPC host with a null request handler
@@ -56,10 +57,8 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<ArgumentNullException>(() => jh.SetRequestHandler(CommonObjects.RequestType, null)); Assert.Throws<ArgumentNullException>(() => jh.SetRequestHandler(CommonObjects.RequestType, null));
} }
[Theory] [Test]
[InlineData(false)] public async Task SetAsyncRequestHandler([Values]bool nullContents)
[InlineData(true)]
public async Task SetAsyncRequestHandler(bool nullContents)
{ {
// Setup: Create a mock request handler // Setup: Create a mock request handler
var requestHandler = new Mock<Func<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>, Task>>(); var requestHandler = new Mock<Func<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>, Task>>();
@@ -69,11 +68,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I assign a request handler on the JSON RPC host // If: I assign a request handler on the JSON RPC host
var jh = new JsonRpcHost(GetChannelBase(null, null).Object); var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object); jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object);
// Then: It should be the only request handler set // Then: It should be the only request handler set
Assert.Single(jh.requestHandlers); Assert.That(jh.requestHandlers.Keys, Is.EqualTo(new[] { CommonObjects.RequestType.MethodName }), "requestHandlers.Keys after SetAsyncRequestHandler");
Assert.Contains(CommonObjects.RequestType.MethodName, jh.requestHandlers.Keys);
// If: I call the stored request handler // If: I call the stored request handler
await jh.requestHandlers[CommonObjects.RequestType.MethodName](message); await jh.requestHandlers[CommonObjects.RequestType.MethodName](message);
@@ -89,10 +87,8 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Exactly(2)); ), Times.Exactly(2));
} }
[Theory] [Test]
[InlineData(false)] public async Task SetSyncRequestHandler([Values]bool nullContents)
[InlineData(true)]
public async Task SetSyncRequestHandler(bool nullContents)
{ {
// Setup: Create a mock request handler // Setup: Create a mock request handler
var requestHandler = new Mock<Action<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>>>(); var requestHandler = new Mock<Action<CommonObjects.TestMessageContents, RequestContext<CommonObjects.TestMessageContents>>>();
@@ -102,13 +98,12 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I assign a request handler on the JSON RPC host // If: I assign a request handler on the JSON RPC host
var jh = new JsonRpcHost(GetChannelBase(null, null).Object); var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
jh.SetRequestHandler(CommonObjects.RequestType, requestHandler.Object); jh.SetRequestHandler(CommonObjects.RequestType, requestHandler.Object);
// Then: It should be the only request handler set // Then: It should be the only request handler set
Assert.Single(jh.requestHandlers); Assert.That(jh.requestHandlers.Keys, Is.EqualTo(new[] { CommonObjects.RequestType.MethodName }), "requestHandlers.Keys after SetRequestHandler");
Assert.Contains(CommonObjects.RequestType.MethodName, jh.requestHandlers.Keys);
// If: I call the stored request handler
// If: I call the stored request handler
await jh.requestHandlers[CommonObjects.RequestType.MethodName](message); await jh.requestHandlers[CommonObjects.RequestType.MethodName](message);
await jh.requestHandlers[CommonObjects.RequestType.MethodName](message); await jh.requestHandlers[CommonObjects.RequestType.MethodName](message);
@@ -122,7 +117,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Exactly(2)); ), Times.Exactly(2));
} }
[Fact] [Test]
public async Task SetAsyncRequestHandlerOverrideTrue() public async Task SetAsyncRequestHandlerOverrideTrue()
{ {
// Setup: Create two mock request handlers // Setup: Create two mock request handlers
@@ -137,8 +132,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler2.Object, true); jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler2.Object, true);
// Then: There should only be one request handler // Then: There should only be one request handler
Assert.Single(jh.requestHandlers); Assert.That(jh.requestHandlers.Keys, Is.EqualTo(new[] { CommonObjects.RequestType.MethodName }), "requestHandlers.Keys after SetAsyncRequestHandler with override");
Assert.Contains(CommonObjects.RequestType.MethodName, jh.requestHandlers.Keys);
// If: I call the stored request handler // If: I call the stored request handler
await jh.requestHandlers[CommonObjects.RequestType.MethodName](CommonObjects.RequestMessage); await jh.requestHandlers[CommonObjects.RequestType.MethodName](CommonObjects.RequestMessage);
@@ -154,7 +148,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Never); ), Times.Never);
} }
[Fact] [Test]
public void SetAsyncRequestHandlerOverrideFalse() public void SetAsyncRequestHandlerOverrideFalse()
{ {
// Setup: Create a mock request handler // Setup: Create a mock request handler
@@ -166,14 +160,14 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: I should get an exception // Then: I should get an exception
var jh = new JsonRpcHost(GetChannelBase(null, null).Object); var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object); jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object);
Assert.ThrowsAny<Exception>(() => jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object)); Assert.That(() => jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object), Throws.InstanceOf<Exception>(), "Reassign request handler without overriding");
} }
#endregion #endregion
#region SetEventHandler Tests #region SetEventHandler Tests
[Fact] [Test]
public void SetAsyncEventHandlerNullEventType() public void SetAsyncEventHandlerNullEventType()
{ {
// If: I assign an event handler on the JSON RPC host with a null event type // If: I assign an event handler on the JSON RPC host with a null event type
@@ -183,7 +177,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
jh.SetAsyncEventHandler<object>(null, (a, b) => Task.FromResult(false))); jh.SetAsyncEventHandler<object>(null, (a, b) => Task.FromResult(false)));
} }
[Fact] [Test]
public void SetAsyncEventHandlerNull() public void SetAsyncEventHandlerNull()
{ {
// If: I assign an event handler on the message gispatcher with a null event handler // If: I assign an event handler on the message gispatcher with a null event handler
@@ -191,7 +185,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<ArgumentNullException>(() => jh.SetAsyncEventHandler(CommonObjects.EventType, null)); Assert.Throws<ArgumentNullException>(() => jh.SetAsyncEventHandler(CommonObjects.EventType, null));
} }
[Fact] [Test]
public void SetSyncEventHandlerNull() public void SetSyncEventHandlerNull()
{ {
// If: I assign an event handler on the message gispatcher with a null event handler // If: I assign an event handler on the message gispatcher with a null event handler
@@ -199,10 +193,8 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<ArgumentNullException>(() => jh.SetEventHandler(CommonObjects.EventType, null)); Assert.Throws<ArgumentNullException>(() => jh.SetEventHandler(CommonObjects.EventType, null));
} }
[Theory] [Test]
[InlineData(true)] public async Task SetAsyncEventHandler([Values]bool nullContents)
[InlineData(false)]
public async Task SetAsyncEventHandler(bool nullContents)
{ {
// Setup: Create a mock request handler // Setup: Create a mock request handler
var eventHandler = new Mock<Func<CommonObjects.TestMessageContents, EventContext, Task>>(); var eventHandler = new Mock<Func<CommonObjects.TestMessageContents, EventContext, Task>>();
@@ -212,13 +204,12 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I assign an event handler on the JSON RPC host // If: I assign an event handler on the JSON RPC host
var jh = new JsonRpcHost(GetChannelBase(null, null).Object); var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object); jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object);
// Then: It should be the only event handler set // Then: It should be the only event handler set
Assert.Single(jh.eventHandlers); Assert.That(jh.eventHandlers.Keys, Is.EqualTo(new[] { CommonObjects.EventType.MethodName }), "eventHandlers.Keys after SetAsyncRequestHandler");
Assert.Contains(CommonObjects.EventType.MethodName, jh.eventHandlers.Keys);
// If: I call the stored event handler
// If: I call the stored event handler
await jh.eventHandlers[CommonObjects.EventType.MethodName](message); await jh.eventHandlers[CommonObjects.EventType.MethodName](message);
await jh.eventHandlers[CommonObjects.EventType.MethodName](message); await jh.eventHandlers[CommonObjects.EventType.MethodName](message);
@@ -232,10 +223,8 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Exactly(2)); ), Times.Exactly(2));
} }
[Theory] [Test]
[InlineData(true)] public async Task SetSyncEventHandler([Values]bool nullContents)
[InlineData(false)]
public async Task SetSyncEventHandler(bool nullContents)
{ {
// Setup: Create a mock request handler // Setup: Create a mock request handler
var eventHandler = new Mock<Action<CommonObjects.TestMessageContents, EventContext>>(); var eventHandler = new Mock<Action<CommonObjects.TestMessageContents, EventContext>>();
@@ -248,8 +237,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
jh.SetEventHandler(CommonObjects.EventType, eventHandler.Object); jh.SetEventHandler(CommonObjects.EventType, eventHandler.Object);
// Then: It should be the only event handler set // Then: It should be the only event handler set
Assert.Single(jh.eventHandlers); Assert.That(jh.eventHandlers.Keys, Is.EqualTo(new object[] { CommonObjects.EventType.MethodName }), "eventHandlers.Keys after SetEventHandler");
Assert.Contains(CommonObjects.EventType.MethodName, jh.eventHandlers.Keys);
// If: I call the stored event handler // If: I call the stored event handler
await jh.eventHandlers[CommonObjects.EventType.MethodName](message); await jh.eventHandlers[CommonObjects.EventType.MethodName](message);
@@ -265,7 +253,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Exactly(2)); ), Times.Exactly(2));
} }
[Fact] [Test]
public async Task SetAsyncEventHandlerOverrideTrue() public async Task SetAsyncEventHandlerOverrideTrue()
{ {
// Setup: Create two mock event handlers // Setup: Create two mock event handlers
@@ -281,8 +269,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler2.Object, true); jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler2.Object, true);
// Then: There should only be one event handler // Then: There should only be one event handler
Assert.Single(jh.eventHandlers); Assert.That(jh.eventHandlers.Keys, Is.EqualTo(new[] { CommonObjects.EventType.MethodName }), "requestHandlers.Keys after SetAsyncEventHandler with override");
Assert.Contains(CommonObjects.EventType.MethodName, jh.eventHandlers.Keys);
// If: I call the stored event handler // If: I call the stored event handler
await jh.eventHandlers[CommonObjects.EventType.MethodName](CommonObjects.EventMessage); await jh.eventHandlers[CommonObjects.EventType.MethodName](CommonObjects.EventMessage);
@@ -298,7 +285,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Never); ), Times.Never);
} }
[Fact] [Test]
public void SetAsyncEventHandlerOverrideFalse() public void SetAsyncEventHandlerOverrideFalse()
{ {
// Setup: Create a mock event handler // Setup: Create a mock event handler
@@ -310,14 +297,14 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: I should get an exception // Then: I should get an exception
var jh = new JsonRpcHost(GetChannelBase(null, null).Object); var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object); jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object);
Assert.ThrowsAny<Exception>(() => jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object)); Assert.That(() => jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object), Throws.InstanceOf<Exception>(), "SetAsyncEventHandler without overriding");
} }
#endregion #endregion
#region SendEvent Tests #region SendEvent Tests
[Fact] [Test]
public void SendEventNotConnected() public void SendEventNotConnected()
{ {
// If: I send an event when the protocol channel isn't connected // If: I send an event when the protocol channel isn't connected
@@ -326,36 +313,34 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<InvalidOperationException>(() => jh.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance)); Assert.Throws<InvalidOperationException>(() => jh.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance));
} }
[Fact] [Test]
public void SendEvent() public void SendEvent()
{ {
// Setup: Create a Json RPC Host with a connected channel // Setup: Create a Json RPC Host with a connected channel
var jh = new JsonRpcHost(GetChannelBase(null, null, true).Object); var jh = new JsonRpcHost(GetChannelBase(null, null, true).Object);
// If: I send an event // If: I send an event
jh.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance); jh.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message should be added to the output queue // Then: The message should be added to the output queue
Assert.Single(jh.outputQueue.ToArray()); Assert.That(jh.outputQueue.ToArray().Select(m => (m.Contents, m.Method)),
var m = jh.outputQueue.ToArray()[0]; Is.EqualTo(new[] { (CommonObjects.TestMessageContents.SerializedContents, CommonObjects.EventType.MethodName) }), "outputQueue after SendEvent");
Assert.Equal(CommonObjects.TestMessageContents.SerializedContents, m.Contents);
Assert.Equal(CommonObjects.EventType.MethodName, m.Method);
} }
#endregion #endregion
#region SendRequest Tests #region SendRequest Tests
[Fact] [Test]
public async Task SendRequestNotConnected() public async Task SendRequestNotConnected()
{ {
// If: I send an event when the protocol channel isn't connected // If: I send an event when the protocol channel isn't connected
// Then: I should get an exception // Then: I should get an exception
var jh = new JsonRpcHost(GetChannelBase(null, null).Object); var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
await Assert.ThrowsAsync<InvalidOperationException>(() => jh.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance)); Assert.ThrowsAsync<InvalidOperationException>(() => jh.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance));
} }
[Fact] [Test]
public async Task SendRequest() public async Task SendRequest()
{ {
// If: I send a request with the JSON RPC host // If: I send a request with the JSON RPC host
@@ -363,21 +348,21 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Task<CommonObjects.TestMessageContents> requestTask = jh.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance); Task<CommonObjects.TestMessageContents> requestTask = jh.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance);
// Then: There should be a pending request // Then: There should be a pending request
Assert.Single(jh.pendingRequests); Assert.That(jh.pendingRequests.Count, Is.EqualTo(1), "pendingRequests.Count after SendRequest");
// If: I then trick it into completing the request // If: I then trick it into completing the request
jh.pendingRequests.First().Value.SetResult(CommonObjects.ResponseMessage); jh.pendingRequests.First().Value.SetResult(CommonObjects.ResponseMessage);
var responseContents = await requestTask; var responseContents = await requestTask;
// Then: The returned results should be the contents of the message // Then: The returned results should be the contents of the message
Assert.Equal(CommonObjects.TestMessageContents.DefaultInstance, responseContents); Assert.AreEqual(CommonObjects.TestMessageContents.DefaultInstance, responseContents);
} }
#endregion #endregion
#region DispatchMessage Tests #region DispatchMessage Tests
[Fact] [Test]
public async Task DispatchMessageRequestWithoutHandler() public async Task DispatchMessageRequestWithoutHandler()
{ {
// Setup: Create a JSON RPC host without a request handler // Setup: Create a JSON RPC host without a request handler
@@ -385,10 +370,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I dispatch a request that doesn't have a handler // If: I dispatch a request that doesn't have a handler
// Then: I should get an exception // Then: I should get an exception
await Assert.ThrowsAsync<MethodHandlerDoesNotExistException>(() => jh.DispatchMessage(CommonObjects.RequestMessage)); Assert.ThrowsAsync<MethodHandlerDoesNotExistException>(() => jh.DispatchMessage(CommonObjects.RequestMessage));
} }
[Fact] [Test]
public async Task DispatchMessageRequestException() public async Task DispatchMessageRequestException()
{ {
// Setup: Create a JSON RPC host with a request handler that throws an unhandled exception every time // Setup: Create a JSON RPC host with a request handler that throws an unhandled exception every time
@@ -403,11 +388,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I dispatch a message whose handler throws // If: I dispatch a message whose handler throws
// Then: I should get an exception // Then: I should get an exception
await Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.RequestMessage)); Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.RequestMessage));
} }
[Theory] [TestCaseSource(nameof(DispatchMessageWithHandlerData))]
[MemberData(nameof(DispatchMessageWithHandlerData))]
public async Task DispatchMessageRequestWithHandler(Task result) public async Task DispatchMessageRequestWithHandler(Task result)
{ {
// Setup: Create a JSON RPC host with a request handler setup // Setup: Create a JSON RPC host with a request handler setup
@@ -429,7 +413,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Once); ), Times.Once);
} }
[Fact] [Test]
public async Task DispatchmessageResponseWithoutHandler() public async Task DispatchmessageResponseWithoutHandler()
{ {
// Setup: Create a new JSON RPC host without any pending requests // Setup: Create a new JSON RPC host without any pending requests
@@ -437,10 +421,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I dispatch a response that doesn't have a pending request // If: I dispatch a response that doesn't have a pending request
// Then: I should get an exception // Then: I should get an exception
await Assert.ThrowsAsync<MethodHandlerDoesNotExistException>(() => jh.DispatchMessage(CommonObjects.ResponseMessage)); Assert.ThrowsAsync<MethodHandlerDoesNotExistException>(() => jh.DispatchMessage(CommonObjects.ResponseMessage));
} }
[Fact] [Test]
public async Task DispatchMessageResponseWithHandler() public async Task DispatchMessageResponseWithHandler()
{ {
// Setup: Create a new JSON RPC host that has a pending request handler // Setup: Create a new JSON RPC host that has a pending request handler
@@ -453,10 +437,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: The task completion source should have completed with the message that was given // Then: The task completion source should have completed with the message that was given
await mockPendingRequest.Task.WithTimeout(TimeSpan.FromSeconds(1)); await mockPendingRequest.Task.WithTimeout(TimeSpan.FromSeconds(1));
Assert.Equal(CommonObjects.ResponseMessage, mockPendingRequest.Task.Result); Assert.AreEqual(CommonObjects.ResponseMessage, mockPendingRequest.Task.Result);
} }
[Fact] [Test]
public async Task DispatchMessageEventWithoutHandler() public async Task DispatchMessageEventWithoutHandler()
{ {
// Setup: Create a JSON RPC host without a request handler // Setup: Create a JSON RPC host without a request handler
@@ -464,10 +448,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I dispatch a request that doesn't have a handler // If: I dispatch a request that doesn't have a handler
// Then: I should get an exception // Then: I should get an exception
await Assert.ThrowsAsync<MethodHandlerDoesNotExistException>(() => jh.DispatchMessage(CommonObjects.EventMessage)); Assert.ThrowsAsync<MethodHandlerDoesNotExistException>(() => jh.DispatchMessage(CommonObjects.EventMessage));
} }
[Fact] [Test]
public async Task DispatchMessageEventException() public async Task DispatchMessageEventException()
{ {
// Setup: Create a JSON RPC host with a request handler that throws an unhandled exception every time // Setup: Create a JSON RPC host with a request handler that throws an unhandled exception every time
@@ -479,11 +463,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I dispatch a message whose handler throws // If: I dispatch a message whose handler throws
// Then: I should get an exception // Then: I should get an exception
await Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.EventMessage)); Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.EventMessage));
} }
[Theory] [TestCaseSource(nameof(DispatchMessageWithHandlerData))]
[MemberData(nameof(DispatchMessageWithHandlerData))]
public async Task DispatchMessageEventWithHandler(Task result) public async Task DispatchMessageEventWithHandler(Task result)
{ {
// Setup: Create a JSON RPC host with an event handler setup // Setup: Create a JSON RPC host with an event handler setup
@@ -519,7 +502,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
#region ConsumeInput Loop Tests #region ConsumeInput Loop Tests
[Fact] [Test]
public async Task ConsumeInput() public async Task ConsumeInput()
{ {
// Setup: // Setup:
@@ -554,7 +537,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
mr.Verify(o => o.ReadMessage(), Times.AtLeastOnce); mr.Verify(o => o.ReadMessage(), Times.AtLeastOnce);
} }
[Fact] [Test]
public async Task ConsumeInputEndOfStream() public async Task ConsumeInputEndOfStream()
{ {
// Setup: Create a message reader that will throw an end of stream exception on read // Setup: Create a message reader that will throw an end of stream exception on read
@@ -571,7 +554,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
mr.Verify(o => o.ReadMessage(), Times.Once); mr.Verify(o => o.ReadMessage(), Times.Once);
} }
[Fact] [Test]
public async Task ConsumeInputException() public async Task ConsumeInputException()
{ {
// Setup: // Setup:
@@ -591,32 +574,29 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
mr.Verify(o => o.ReadMessage(), Times.Exactly(2)); mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
} }
[Fact] [Test]
public async Task ConsumeInputRequestMethodNotFound() public async Task ConsumeInputRequestMethodNotFound()
{ {
// Setup: Create a message reader that will return a request with method that doesn't exist // Setup: Create a message reader that will return a request with method that doesn't exist
var mr = new Mock<MessageReader>(Stream.Null, null); var mr = new Mock<MessageReader>(Stream.Null, null);
mr.SetupSequence(o => o.ReadMessage()) mr.SetupSequence(o => o.ReadMessage())
.ReturnsAsync(CommonObjects.RequestMessage) .ReturnsAsync(CommonObjects.RequestMessage)
.Returns(Task.FromException<Message>(new EndOfStreamException())); .Returns(Task.FromException<Message>(new EndOfStreamException()));
// If: I start the input consumption loop // If: I start the input consumption loop
var jh = new JsonRpcHost(GetChannelBase(mr.Object, null).Object); var jh = new JsonRpcHost(GetChannelBase(mr.Object, null).Object);
await jh.ConsumeInput().WithTimeout(TimeSpan.FromSeconds(1)); await jh.ConsumeInput().WithTimeout(TimeSpan.FromSeconds(1));
// Then: // Then:
// ... Read message should have been called twice // ... Read message should have been called twice
mr.Verify(o => o.ReadMessage(), Times.Exactly(2)); mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
// ... There should be an outgoing message with the error // ...
var outgoing = jh.outputQueue.ToArray(); var outgoing = jh.outputQueue.ToArray();
Assert.Single(outgoing); Assert.That(outgoing.Select(m => (m.MessageType, m.Id, m.Contents.Value<int>("code"))), Is.EqualTo(new[] { (MessageType.ResponseError, CommonObjects.MessageId, -32601) }), "There should be an outgoing message with the error");
Assert.Equal(MessageType.ResponseError, outgoing[0].MessageType);
Assert.Equal(CommonObjects.MessageId, outgoing[0].Id);
Assert.Equal(-32601, outgoing[0].Contents.Value<int>("code"));
} }
[Fact] [Test]
public async Task ConsumeInputRequestException() public async Task ConsumeInputRequestException()
{ {
// Setup: // Setup:
@@ -641,16 +621,15 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// ... Read message should have been called twice // ... Read message should have been called twice
mr.Verify(o => o.ReadMessage(), Times.Exactly(2)); mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
// ... There should not be any outgoing messages
var outgoing = jh.outputQueue.ToArray(); var outgoing = jh.outputQueue.ToArray();
Assert.Empty(outgoing); Assert.That(outgoing, Is.Empty, "outputQueue after ConsumeInput should not have any outgoing messages");
} }
#endregion #endregion
#region ConsumeOutput Loop Tests #region ConsumeOutput Loop Tests
[Fact] [Test]
public async Task ConsumeOutput() public async Task ConsumeOutput()
{ {
// Setup: // Setup:
@@ -671,7 +650,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
mw.Verify(o => o.WriteMessage(CommonObjects.ResponseMessage), Times.Once); mw.Verify(o => o.WriteMessage(CommonObjects.ResponseMessage), Times.Once);
} }
[Fact] [Test]
public async Task ConsumeOutputCancelled() public async Task ConsumeOutputCancelled()
{ {
// NOTE: This test validates that the blocking collection breaks out when cancellation is requested // NOTE: This test validates that the blocking collection breaks out when cancellation is requested
@@ -693,7 +672,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
mw.Verify(o => o.WriteMessage(It.IsAny<Message>()), Times.Never); mw.Verify(o => o.WriteMessage(It.IsAny<Message>()), Times.Never);
} }
[Fact] [Test]
public async Task ConsumeOutputException() public async Task ConsumeOutputException()
{ {
// Setup: Create a mock message writer // Setup: Create a mock message writer
@@ -713,7 +692,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
#region Start/Stop Tests #region Start/Stop Tests
[Fact] [Test]
public async Task StartStop() public async Task StartStop()
{ {
// Setup: Create mocked message reader and writer // Setup: Create mocked message reader and writer
@@ -737,7 +716,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
cb.Verify(o => o.Stop(), Times.Once); cb.Verify(o => o.Stop(), Times.Once);
} }
[Fact] [Test]
public async Task StartMultiple() public async Task StartMultiple()
{ {
// Setup: Create mocked message reader and writer // Setup: Create mocked message reader and writer
@@ -759,7 +738,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
await Task.WhenAll(jh.consumeInputTask, jh.consumeOutputTask).WithTimeout(TimeSpan.FromSeconds(1)); await Task.WhenAll(jh.consumeInputTask, jh.consumeOutputTask).WithTimeout(TimeSpan.FromSeconds(1));
} }
[Fact] [Test]
public void StopMultiple() public void StopMultiple()
{ {
// Setup: Create json rpc host and start it // Setup: Create json rpc host and start it
@@ -774,7 +753,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<InvalidOperationException>(() => jh.Stop()); Assert.Throws<InvalidOperationException>(() => jh.Stop());
} }
[Fact] [Test]
public void StopBeforeStarting() public void StopBeforeStarting()
{ {
// If: I stop the JSON RPC host without starting it first // If: I stop the JSON RPC host without starting it first
@@ -783,7 +762,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<InvalidOperationException>(() => jh.Stop()); Assert.Throws<InvalidOperationException>(() => jh.Stop());
} }
[Fact] [Test]
public async Task WaitForExit() public async Task WaitForExit()
{ {
// Setup: Create json rpc host and start it // Setup: Create json rpc host and start it
@@ -801,7 +780,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
await waitForExit.WithTimeout(TimeSpan.FromSeconds(1)); await waitForExit.WithTimeout(TimeSpan.FromSeconds(1));
} }
[Fact] [Test]
public void WaitForExitNotStarted() public void WaitForExitNotStarted()
{ {
// If: I wait for exit on the JSON RPC host without starting it // If: I wait for exit on the JSON RPC host without starting it
@@ -10,15 +10,16 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{ {
[TestFixture]
public class MessageReaderTests public class MessageReaderTests
{ {
#region Construction Tests #region Construction Tests
[Fact] [Test]
public void CreateReaderNullStream() public void CreateReaderNullStream()
{ {
// If: I create a message reader with a null stream reader // If: I create a message reader with a null stream reader
@@ -26,35 +27,32 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<ArgumentNullException>(() => new MessageReader(null)); Assert.Throws<ArgumentNullException>(() => new MessageReader(null));
} }
[Fact] [Test]
public void CreateReaderStandardEncoding() public void CreateReaderStandardEncoding()
{ {
// If: I create a message reader without including a message encoding // If: I create a message reader without including a message encoding
var mr = new MessageReader(Stream.Null); var mr = new MessageReader(Stream.Null);
// Then: The reader's encoding should be UTF8 // Then: The reader's encoding should be UTF8
Assert.Equal(Encoding.UTF8, mr.MessageEncoding); Assert.AreEqual(Encoding.UTF8, mr.MessageEncoding);
} }
[Fact] [Test]
public void CreateReaderNonStandardEncoding() public void CreateReaderNonStandardEncoding()
{ {
// If: I create a message reader with a specific message encoding // If: I create a message reader with a specific message encoding
var mr = new MessageReader(Stream.Null, Encoding.ASCII); var mr = new MessageReader(Stream.Null, Encoding.ASCII);
// Then: The reader's encoding should be ASCII // Then: The reader's encoding should be ASCII
Assert.Equal(Encoding.ASCII, mr.MessageEncoding); Assert.AreEqual(Encoding.ASCII, mr.MessageEncoding);
} }
#endregion #endregion
#region ReadMessage Tests #region ReadMessage Tests
[Theory] [Test]
[InlineData(512)] // Buffer size can fit everything in one read public async Task ReadMessageSingleRead([Values(512,10,25)]int bufferSize)
[InlineData(10)] // Buffer size must use multiple reads to read the headers
[InlineData(25)] // Buffer size must use multiple reads to read the contents
public async Task ReadMessageSingleRead(int bufferSize)
{ {
// Setup: Reader with a stream that has an entire message in it // Setup: Reader with a stream that has an entire message in it
byte[] testBytes = Encoding.UTF8.GetBytes("Content-Length: 50\r\n\r\n{\"jsonrpc\": \"2.0\", \"method\":\"test\", \"params\":null}"); byte[] testBytes = Encoding.UTF8.GetBytes("Content-Length: 50\r\n\r\n{\"jsonrpc\": \"2.0\", \"method\":\"test\", \"params\":null}");
@@ -70,17 +68,19 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.NotNull(output); Assert.NotNull(output);
// ... The reader should be back in header mode // ... The reader should be back in header mode
Assert.Equal(MessageReader.ReadState.Headers, mr.CurrentState); Assert.AreEqual(MessageReader.ReadState.Headers, mr.CurrentState);
// ... The buffer should have been trimmed // ... The buffer should have been trimmed
Assert.Equal(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length); Assert.AreEqual(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
} }
} }
[Theory] [Test]
[InlineData("Content-Type: application/json\r\n\r\n")] // Missing content-length header public async Task ReadMessageInvalidHeaders(
[InlineData("Content-Length: abc\r\n\r\n")] // Content-length is not a number [Values(
public async Task ReadMessageInvalidHeaders(string testString) "Content-Type: application/json\r\n\r\n",// Missing content-length header
"Content-Length: abc\r\n\r\n"// Content-length is not a number
)]string testString)
{ {
// Setup: Reader with a stream that has an invalid header in it // Setup: Reader with a stream that has an invalid header in it
byte[] testBytes = Encoding.UTF8.GetBytes(testString); byte[] testBytes = Encoding.UTF8.GetBytes(testString);
@@ -90,14 +90,14 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I read a message with invalid headers // If: I read a message with invalid headers
// Then: ... I should get an exception // Then: ... I should get an exception
await Assert.ThrowsAnyAsync<MessageParseException>(() => mr.ReadMessage()); Assert.ThrowsAsync<MessageParseException>(() => mr.ReadMessage());
// ... The buffer should have been trashed (reset to it's original tiny size) // ... The buffer should have been trashed (reset to it's original tiny size)
Assert.Equal(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length); Assert.AreEqual(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
} }
} }
[Fact] [Test]
public async Task ReadMessageInvalidJson() public async Task ReadMessageInvalidJson()
{ {
// Setup: Reader with a stream that has an invalid json message in it // Setup: Reader with a stream that has an invalid json message in it
@@ -110,14 +110,14 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I read a message with an invalid JSON in it // If: I read a message with an invalid JSON in it
// Then: // Then:
// ... I should get an exception // ... I should get an exception
await Assert.ThrowsAnyAsync<JsonException>(() => mr.ReadMessage()); Assert.ThrowsAsync<JsonReaderException>(() => mr.ReadMessage());
// ... The buffer should have been trashed (reset to it's original tiny size) // ... The buffer should have been trashed (reset to it's original tiny size)
Assert.Equal(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length); Assert.AreEqual(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
} }
} }
[Fact] [Test]
public async Task ReadMultipleMessages() public async Task ReadMultipleMessages()
{ {
// Setup: Reader with a stream that has multiple messages in it // Setup: Reader with a stream that has multiple messages in it
@@ -141,7 +141,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
} }
} }
[Fact] [Test]
public async Task ReadMultipleMessagesBeforeWriting() public async Task ReadMultipleMessagesBeforeWriting()
{ {
// Setup: Reader with a stream that will have multiple messages in it // Setup: Reader with a stream that will have multiple messages in it
@@ -169,7 +169,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
} }
} }
[Fact] [Test]
public async Task ReadRecoverFromInvalidHeaderMessage() public async Task ReadRecoverFromInvalidHeaderMessage()
{ {
// Setup: Reader with a stream that has incorrect message formatting // Setup: Reader with a stream that has incorrect message formatting
@@ -182,7 +182,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I read a message with invalid headers // If: I read a message with invalid headers
// Then: I should get an exception // Then: I should get an exception
await Assert.ThrowsAnyAsync<MessageParseException>(() => mr.ReadMessage()); Assert.ThrowsAsync<MessageParseException>(() => mr.ReadMessage());
// If: I read another, valid, message // If: I read another, valid, message
var msg = await mr.ReadMessage(); var msg = await mr.ReadMessage();
@@ -192,7 +192,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
} }
} }
[Fact] [Test]
public async Task ReadRecoverFromInvalidContentMessage() public async Task ReadRecoverFromInvalidContentMessage()
{ {
// Setup: Reader with a stream that has incorrect message formatting // Setup: Reader with a stream that has incorrect message formatting
@@ -205,7 +205,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I read a message with invalid content // If: I read a message with invalid content
// Then: I should get an exception // Then: I should get an exception
await Assert.ThrowsAnyAsync<JsonException>(() => mr.ReadMessage()); Assert.ThrowsAsync<JsonReaderException>(() => mr.ReadMessage());
// If: I read another, valid, message // If: I read another, valid, message
var msg = await mr.ReadMessage(); var msg = await mr.ReadMessage();
@@ -8,15 +8,16 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{ {
[TestFixture]
public class MessageTests public class MessageTests
{ {
#region Construction/Serialization Tests #region Construction/Serialization Tests
[Fact] [Test]
public void CreateRequest() public void CreateRequest()
{ {
// If: I create a request // If: I create a request
@@ -36,7 +37,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
AssertPropertiesSet(expectedResults, message); AssertPropertiesSet(expectedResults, message);
} }
[Fact] [Test]
public void CreateError() public void CreateError()
{ {
// If: I create an error // If: I create an error
@@ -54,7 +55,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
AssertPropertiesSet(expectedResults, message); AssertPropertiesSet(expectedResults, message);
} }
[Fact] [Test]
public void CreateResponse() public void CreateResponse()
{ {
// If: I create a response // If: I create a response
@@ -72,7 +73,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
AssertPropertiesSet(expectedResults, message); AssertPropertiesSet(expectedResults, message);
} }
[Fact] [Test]
public void CreateEvent() public void CreateEvent()
{ {
// If: I create an event // If: I create an event
@@ -101,16 +102,16 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// JSON RPC Version // JSON RPC Version
List<string> expectedProperties = new List<string> {"jsonrpc"}; List<string> expectedProperties = new List<string> {"jsonrpc"};
Assert.Equal("2.0", jObject["jsonrpc"]); Assert.AreEqual("2.0", jObject["jsonrpc"].Value<string>());
// Message Type // Message Type
Assert.Equal(results.MessageType, message.MessageType); Assert.AreEqual(results.MessageType, message.MessageType);
// ID // ID
if (results.IdSet) if (results.IdSet)
{ {
Assert.Equal(CommonObjects.MessageId, message.Id); Assert.AreEqual(CommonObjects.MessageId, message.Id);
Assert.Equal(CommonObjects.MessageId, jObject["id"]); Assert.AreEqual(CommonObjects.MessageId, jObject["id"].Value<string>());
expectedProperties.Add("id"); expectedProperties.Add("id");
} }
else else
@@ -121,8 +122,8 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Method // Method
if (results.MethodSetAs != null) if (results.MethodSetAs != null)
{ {
Assert.Equal(results.MethodSetAs, message.Method); Assert.AreEqual(results.MethodSetAs, message.Method);
Assert.Equal(results.MethodSetAs, jObject["method"]); Assert.AreEqual(results.MethodSetAs, jObject["method"].Value<string>());
expectedProperties.Add("method"); expectedProperties.Add("method");
} }
else else
@@ -133,22 +134,22 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Contents // Contents
if (results.ContentsSetAs != null) if (results.ContentsSetAs != null)
{ {
Assert.Equal(CommonObjects.TestMessageContents.SerializedContents, message.Contents); Assert.AreEqual(CommonObjects.TestMessageContents.SerializedContents, message.Contents);
Assert.Equal(CommonObjects.TestMessageContents.SerializedContents, jObject[results.ContentsSetAs]); Assert.AreEqual(CommonObjects.TestMessageContents.SerializedContents, jObject[results.ContentsSetAs]);
expectedProperties.Add(results.ContentsSetAs); expectedProperties.Add(results.ContentsSetAs);
} }
// Error // Error
if (results.ErrorSet) if (results.ErrorSet)
{ {
Assert.Equal(CommonObjects.TestErrorContents.SerializedContents, message.Contents); Assert.AreEqual(CommonObjects.TestErrorContents.SerializedContents, message.Contents);
Assert.Equal(CommonObjects.TestErrorContents.SerializedContents, jObject["error"]); Assert.AreEqual(CommonObjects.TestErrorContents.SerializedContents, jObject["error"]);
expectedProperties.Add("error"); expectedProperties.Add("error");
} }
// Look for any extra properties set in the JObject // Look for any extra properties set in the JObject
IEnumerable<string> setProperties = jObject.Properties().Select(p => p.Name); IEnumerable<string> setProperties = jObject.Properties().Select(p => p.Name);
Assert.Empty(setProperties.Except(expectedProperties)); Assert.That(setProperties.Except(expectedProperties), Is.Empty, "extra properties in jObject");
} }
private class MessagePropertyResults private class MessagePropertyResults
@@ -164,7 +165,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
#region Deserialization Tests #region Deserialization Tests
[Fact] [Test]
public void DeserializeMissingJsonRpc() public void DeserializeMissingJsonRpc()
{ {
// If: I deserialize a json string that doesn't have a JSON RPC version // If: I deserialize a json string that doesn't have a JSON RPC version
@@ -172,7 +173,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<MessageParseException>(() => Message.Deserialize("{\"id\": 123}")); Assert.Throws<MessageParseException>(() => Message.Deserialize("{\"id\": 123}"));
} }
[Fact] [Test]
public void DeserializeEvent() public void DeserializeEvent()
{ {
// If: I deserialize an event json string // If: I deserialize an event json string
@@ -180,13 +181,13 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: I should get an event message back // Then: I should get an event message back
Assert.NotNull(m); Assert.NotNull(m);
Assert.Equal(MessageType.Event, m.MessageType); Assert.AreEqual(MessageType.Event, m.MessageType);
Assert.Equal("event", m.Method); Assert.AreEqual("event", m.Method);
Assert.NotNull(m.Contents); Assert.NotNull(m.Contents);
Assert.Null(m.Id); Assert.Null(m.Id);
} }
[Fact] [Test]
public void DeserializeEventMissingMethod() public void DeserializeEventMissingMethod()
{ {
// If: I deserialize an event json string that is missing a method // If: I deserialize an event json string that is missing a method
@@ -194,7 +195,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<MessageParseException>(() => Message.Deserialize("{\"jsonrpc\": \"2.0\", \"params\": {}}")); Assert.Throws<MessageParseException>(() => Message.Deserialize("{\"jsonrpc\": \"2.0\", \"params\": {}}"));
} }
[Fact] [Test]
public void DeserializeResponse() public void DeserializeResponse()
{ {
// If: I deserialize a response json string // If: I deserialize a response json string
@@ -202,13 +203,13 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: I should get a response message back // Then: I should get a response message back
Assert.NotNull(m); Assert.NotNull(m);
Assert.Equal(MessageType.Response, m.MessageType); Assert.AreEqual(MessageType.Response, m.MessageType);
Assert.Equal("123", m.Id); Assert.AreEqual("123", m.Id);
Assert.NotNull(m.Contents); Assert.NotNull(m.Contents);
Assert.Null(m.Method); Assert.Null(m.Method);
} }
[Fact] [Test]
public void DeserializeErrorResponse() public void DeserializeErrorResponse()
{ {
// If: I deserialize an error response // If: I deserialize an error response
@@ -216,13 +217,13 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: I should get an error response message back // Then: I should get an error response message back
Assert.NotNull(m); Assert.NotNull(m);
Assert.Equal(MessageType.ResponseError, m.MessageType); Assert.AreEqual(MessageType.ResponseError, m.MessageType);
Assert.Equal("123", m.Id); Assert.AreEqual("123", m.Id);
Assert.NotNull(m.Contents); Assert.NotNull(m.Contents);
Assert.Null(m.Method); Assert.Null(m.Method);
} }
[Fact] [Test]
public void DeserializeRequest() public void DeserializeRequest()
{ {
// If: I deserialize a request // If: I deserialize a request
@@ -230,13 +231,13 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: I should get a request message back // Then: I should get a request message back
Assert.NotNull(m); Assert.NotNull(m);
Assert.Equal(MessageType.Request, m.MessageType); Assert.AreEqual(MessageType.Request, m.MessageType);
Assert.Equal("123", m.Id); Assert.AreEqual("123", m.Id);
Assert.Equal("request", m.Method); Assert.AreEqual("request", m.Method);
Assert.NotNull(m.Contents); Assert.NotNull(m.Contents);
} }
[Fact] [Test]
public void DeserializeRequestMissingMethod() public void DeserializeRequestMissingMethod()
{ {
// If: I deserialize a request that doesn't have a method parameter // If: I deserialize a request that doesn't have a method parameter
@@ -244,7 +245,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<MessageParseException>(() => Message.Deserialize("{\"jsonrpc\": \"2.0\", \"params\": {}, \"id\": \"123\"}")); Assert.Throws<MessageParseException>(() => Message.Deserialize("{\"jsonrpc\": \"2.0\", \"params\": {}, \"id\": \"123\"}"));
} }
[Fact] [Test]
public void GetTypedContentsNull() public void GetTypedContentsNull()
{ {
// If: I have a message that has a null contents, and I get the typed contents of it // If: I have a message that has a null contents, and I get the typed contents of it
@@ -255,7 +256,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Null(c); Assert.Null(c);
} }
[Fact] [Test]
public void GetTypedContentsSimpleValue() public void GetTypedContentsSimpleValue()
{ {
// If: I have a message that has simple contents, and I get the typed contents of it // If: I have a message that has simple contents, and I get the typed contents of it
@@ -263,10 +264,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
var c = m.GetTypedContents<int>(); var c = m.GetTypedContents<int>();
// Then: I should get an int back // Then: I should get an int back
Assert.Equal(123, c); Assert.AreEqual(123, c);
} }
[Fact] [Test]
public void GetTypedContentsClassValue() public void GetTypedContentsClassValue()
{ {
// If: I have a message that has complex contents, and I get the typed contents of it // If: I have a message that has complex contents, and I get the typed contents of it
@@ -274,16 +275,16 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
var c = m.GetTypedContents<CommonObjects.TestMessageContents>(); var c = m.GetTypedContents<CommonObjects.TestMessageContents>();
// Then: I should get the default instance back // Then: I should get the default instance back
Assert.Equal(CommonObjects.TestMessageContents.DefaultInstance, c); Assert.AreEqual(CommonObjects.TestMessageContents.DefaultInstance, c);
} }
[Fact] [Test]
public void GetTypedContentsInvalid() public void GetTypedContentsInvalid()
{ {
// If: I have a message that has contents and I get incorrectly typed contents from it // If: I have a message that has contents and I get incorrectly typed contents from it
// Then: I should get an exception back // Then: I should get an exception back
var m = Message.CreateResponse(CommonObjects.MessageId, CommonObjects.TestMessageContents.DefaultInstance); var m = Message.CreateResponse(CommonObjects.MessageId, CommonObjects.TestMessageContents.DefaultInstance);
Assert.ThrowsAny<Exception>(() => m.GetTypedContents<int>()); Assert.Throws<ArgumentException>(() => m.GetTypedContents<int>());
} }
#endregion #endregion
@@ -10,15 +10,16 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{ {
[TestFixture]
public class MessageWriterTests public class MessageWriterTests
{ {
#region Construction Tests #region Construction Tests
[Fact] [Test]
public void ConstructMissingOutputStream() public void ConstructMissingOutputStream()
{ {
// If: I attempt to create a message writer without an output stream // If: I attempt to create a message writer without an output stream
@@ -30,17 +31,16 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
#region WriteMessageTests #region WriteMessageTests
[Fact] [Test]
public async Task WriteMessageNullMessage() public async Task WriteMessageNullMessage()
{ {
// If: I write a null message // If: I write a null message
// Then: I should get an exception // Then: I should get an exception
var mw = new MessageWriter(Stream.Null); var mw = new MessageWriter(Stream.Null);
await Assert.ThrowsAsync<ArgumentNullException>(() => mw.WriteMessage(null)); Assert.ThrowsAsync<ArgumentNullException>(() => mw.WriteMessage(null));
} }
[Theory] [TestCaseSource(nameof(WriteMessageData))]
[MemberData(nameof(WriteMessageData))]
public async Task WriteMessage(object contents, Dictionary<string, object> expectedDict) public async Task WriteMessage(object contents, Dictionary<string, object> expectedDict)
{ {
// NOTE: This technically tests the ability of the Message class to properly serialize // NOTE: This technically tests the ability of the Message class to properly serialize
@@ -53,11 +53,11 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{ {
// If: I write a message // If: I write a message
var mw = new MessageWriter(outputStream); var mw = new MessageWriter(outputStream);
await mw.WriteMessage(Message.CreateResponse(CommonObjects.MessageId, contents)); await mw.WriteMessage(Message.CreateResponse(CommonObjects.MessageId, contents));
// Then: // Then:
// ... The returned bytes on the stream should compose a valid message // ... The returned bytes on the stream should compose a valid message
Assert.NotEqual(0, outputStream.Position); Assert.That(outputStream.Position, Is.Not.EqualTo(0), "outputStream.Position after WriteMessage");
var messageDict = ValidateMessageHeaders(output, (int) outputStream.Position); var messageDict = ValidateMessageHeaders(output, (int) outputStream.Position);
// ... ID, Params, Method should be present // ... ID, Params, Method should be present
@@ -97,12 +97,12 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
expectedDict.Add("jsonrpc", "2.0"); expectedDict.Add("jsonrpc", "2.0");
// Make sure the number of elements in both dictionaries are the same // Make sure the number of elements in both dictionaries are the same
Assert.Equal(expectedDict.Count, messageDict.Count); Assert.AreEqual(expectedDict.Count, messageDict.Count);
// Make sure the elements match // Make sure the elements match
foreach (var kvp in expectedDict) foreach (var kvp in expectedDict)
{ {
Assert.Equal(expectedDict[kvp.Key], messageDict[kvp.Key]); Assert.AreEqual(expectedDict[kvp.Key], messageDict[kvp.Key]);
} }
} }
@@ -113,11 +113,11 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// There should be two sections to the message // There should be two sections to the message
string[] outputParts = outputString.Split("\r\n\r\n"); string[] outputParts = outputString.Split("\r\n\r\n");
Assert.Equal(2, outputParts.Length); Assert.AreEqual(2, outputParts.Length);
// The first section is the headers // The first section is the headers
string[] headers = outputParts[0].Split("\r\n"); string[] headers = outputParts[0].Split("\r\n");
Assert.Equal(2, outputParts.Length); Assert.AreEqual(2, outputParts.Length);
// There should be a content-type and a content-length // There should be a content-type and a content-length
int? contentLength = null; int? contentLength = null;
@@ -126,7 +126,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{ {
// Headers should look like "Header-Key: HeaderValue" // Headers should look like "Header-Key: HeaderValue"
string[] headerParts = header.Split(':'); string[] headerParts = header.Split(':');
Assert.Equal(2, headerParts.Length); Assert.AreEqual(2, headerParts.Length);
string headerKey = headerParts[0]; string headerKey = headerParts[0];
string headerValue = headerParts[1].Trim(); string headerValue = headerParts[1].Trim();
@@ -147,7 +147,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Make sure the headers are correct // Make sure the headers are correct
Assert.True(contentTypeCorrect); Assert.True(contentTypeCorrect);
Assert.Equal(outputParts[1].Length, contentLength); Assert.AreEqual(outputParts[1].Length, contentLength);
// Deserialize the body into a dictionary // Deserialize the body into a dictionary
return JsonConvert.DeserializeObject<Dictionary<string, object>>(outputParts[1]); return JsonConvert.DeserializeObject<Dictionary<string, object>>(outputParts[1]);
@@ -8,15 +8,16 @@ using System.Collections.Concurrent;
using System.Linq; using System.Linq;
using Microsoft.SqlTools.Hosting.Contracts.Internal; using Microsoft.SqlTools.Hosting.Contracts.Internal;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{ {
[TestFixture]
public class RequestContextTests public class RequestContextTests
{ {
#region Send Tests #region Send Tests
[Fact] [Test]
public void SendResult() public void SendResult()
{ {
// Setup: Create a blocking collection to collect the output // Setup: Create a blocking collection to collect the output
@@ -26,12 +27,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc); var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
rc.SendResult(CommonObjects.TestMessageContents.DefaultInstance); rc.SendResult(CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message writer should have sent a response Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.Response }), "The message writer should have sent a response");
Assert.Single(bc);
Assert.Equal(MessageType.Response, bc.First().MessageType);
} }
[Fact] [Test]
public void SendEvent() public void SendEvent()
{ {
// Setup: Create a blocking collection to collect the output // Setup: Create a blocking collection to collect the output
@@ -39,14 +38,12 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I write an event with the request context // If: I write an event with the request context
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc); var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
rc.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance); rc.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message writer should have sent an event Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.Event }), "The message writer should have sent an event");
Assert.Single(bc);
Assert.Equal(MessageType.Event, bc.First().MessageType);
} }
[Fact] [Test]
public void SendError() public void SendError()
{ {
// Setup: Create a blocking collection to collect the output // Setup: Create a blocking collection to collect the output
@@ -56,20 +53,17 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I write an error with the request context // If: I write an error with the request context
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc); var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
rc.SendError(errorMessage, errorCode); rc.SendError(errorMessage, errorCode);
// Then: Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.ResponseError }), "The message writer should have sent an error");
// ... The message writer should have sent an error
Assert.Single(bc); // ... The error object it built should have the reuired fields set
Assert.Equal(MessageType.ResponseError, bc.First().MessageType);
// ... The error object it built should have the reuired fields set
var contents = bc.ToArray()[0].GetTypedContents<Error>(); var contents = bc.ToArray()[0].GetTypedContents<Error>();
Assert.Equal(errorCode, contents.Code); Assert.AreEqual(errorCode, contents.Code);
Assert.Equal(errorMessage, contents.Message); Assert.AreEqual(errorMessage, contents.Message);
} }
[Fact] [Test]
public void SendException() public void SendException()
{ {
// Setup: Create a blocking collection to collect the output // Setup: Create a blocking collection to collect the output
@@ -79,18 +73,14 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
const string errorMessage = "error"; const string errorMessage = "error";
var e = new Exception(errorMessage); var e = new Exception(errorMessage);
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc); var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
rc.SendError(e); rc.SendError(e);
// Then: Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.ResponseError }), "The message writer should have sent an error");
// ... The message writer should have sent an error
Assert.Single(bc); // ... The error object it built should have the reuired fields set
var firstMessage = bc.First(); var contents = bc.First().GetTypedContents<Error>();
Assert.Equal(MessageType.ResponseError, firstMessage.MessageType); Assert.AreEqual(e.HResult, contents.Code);
Assert.AreEqual(errorMessage, contents.Message);
// ... The error object it built should have the reuired fields set
var contents = firstMessage.GetTypedContents<Error>();
Assert.Equal(e.HResult, contents.Code);
Assert.Equal(errorMessage, contents.Message);
} }
@@ -8,13 +8,14 @@ using Microsoft.SqlTools.Hosting.Channels;
using Microsoft.SqlTools.Hosting.Extensibility; using Microsoft.SqlTools.Hosting.Extensibility;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
{ {
[TestFixture]
public class ExtensibleServiceHostTest public class ExtensibleServiceHostTest
{ {
[Fact] [Test]
public void CreateExtensibleHostNullProvider() public void CreateExtensibleHostNullProvider()
{ {
// If: I create an extensible host with a null provider // If: I create an extensible host with a null provider
@@ -23,7 +24,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
Assert.Throws<ArgumentNullException>(() => new ExtensibleServiceHost(null, cb.Object)); Assert.Throws<ArgumentNullException>(() => new ExtensibleServiceHost(null, cb.Object));
} }
[Fact] [Test]
public void CreateExtensibleHost() public void CreateExtensibleHost()
{ {
// Setup: // Setup:
@@ -48,10 +49,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
// ... The service should have been initialized // ... The service should have been initialized
hs.Verify(o => o.InitializeService(esh), Times.Once()); hs.Verify(o => o.InitializeService(esh), Times.Once());
// ... The service host should have it's provider exposed // ... The service host should have it's provider exposed
Assert.Equal(sp.Object, esh.ServiceProvider); Assert.AreEqual(sp.Object, esh.ServiceProvider);
} }
[Fact] [Test]
public void CreateDefaultExtensibleHostNullAssemblyList() public void CreateDefaultExtensibleHostNullAssemblyList()
{ {
// If: I create a default server extensible host with a null provider // If: I create a default server extensible host with a null provider
@@ -60,7 +61,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
Assert.Throws<ArgumentNullException>(() => ExtensibleServiceHost.CreateDefaultExtensibleServer(".", null)); Assert.Throws<ArgumentNullException>(() => ExtensibleServiceHost.CreateDefaultExtensibleServer(".", null));
} }
[Fact] [Test]
public void CreateDefaultExtensibleHost() public void CreateDefaultExtensibleHost()
{ {
// If: I create a default server extensible host // If: I create a default server extensible host
@@ -70,10 +71,9 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
// ... The service provider should be setup // ... The service provider should be setup
Assert.NotNull(esh.ServiceProvider); Assert.NotNull(esh.ServiceProvider);
// ... The underlying rpc host should be using the stdio server channel
var jh = esh.jsonRpcHost as JsonRpcHost; var jh = esh.jsonRpcHost as JsonRpcHost;
Assert.NotNull(jh); Assert.NotNull(jh);
Assert.IsType<StdioServerChannel>(jh.protocolChannel); Assert.That(jh.protocolChannel, Is.InstanceOf<StdioServerChannel>(), "The underlying rpc host should be using the stdio server channel ");
Assert.False(jh.protocolChannel.IsConnected); Assert.False(jh.protocolChannel.IsConnected);
} }
} }
@@ -14,28 +14,28 @@ using Microsoft.SqlTools.Hosting.Contracts.Internal;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Moq; using Moq;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
{ {
[TestFixture]
public class ServiceHostTests public class ServiceHostTests
{ {
#region Construction Tests #region Construction Tests
[Fact] [Test]
public void ServiceHostConstructDefaultServer() public void ServiceHostConstructDefaultServer()
{ {
// If: I construct a default server service host // If: I construct a default server service host
var sh = ServiceHost.CreateDefaultServer(); var sh = ServiceHost.CreateDefaultServer();
// Then: The underlying json rpc host should be using the stdio server channel
var jh = sh.jsonRpcHost as JsonRpcHost; var jh = sh.jsonRpcHost as JsonRpcHost;
Assert.NotNull(jh); Assert.NotNull(jh);
Assert.IsType<StdioServerChannel>(jh.protocolChannel); Assert.That(jh.protocolChannel, Is.InstanceOf<StdioServerChannel>(), "The underlying json rpc host should be using the stdio server channel");
Assert.False(jh.protocolChannel.IsConnected); Assert.False(jh.protocolChannel.IsConnected);
} }
[Fact] [Test]
public void ServiceHostNullParameter() public void ServiceHostNullParameter()
{ {
// If: I create a service host with missing parameters // If: I create a service host with missing parameters
@@ -47,7 +47,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
#region IServiceHost Tests #region IServiceHost Tests
[Fact] [Test]
public void RegisterInitializeTask() public void RegisterInitializeTask()
{ {
// Setup: Create mock initialize handler // Setup: Create mock initialize handler
@@ -59,11 +59,11 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
sh.RegisterInitializeTask(mockHandler); sh.RegisterInitializeTask(mockHandler);
// Then: There should be two initialize tasks registered // Then: There should be two initialize tasks registered
Assert.Equal(2, sh.initCallbacks.Count); Assert.AreEqual(2, sh.initCallbacks.Count);
Assert.True(sh.initCallbacks.SequenceEqual(new[] {mockHandler, mockHandler})); Assert.True(sh.initCallbacks.SequenceEqual(new[] {mockHandler, mockHandler}));
} }
[Fact] [Test]
public void RegisterInitializeTaskNullHandler() public void RegisterInitializeTaskNullHandler()
{ {
// If: I register a null initialize task // If: I register a null initialize task
@@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
Assert.Throws<ArgumentNullException>(() => sh.RegisterInitializeTask(null)); Assert.Throws<ArgumentNullException>(() => sh.RegisterInitializeTask(null));
} }
[Fact] [Test]
public void RegisterShutdownTask() public void RegisterShutdownTask()
{ {
// Setup: Create mock initialize handler // Setup: Create mock initialize handler
@@ -84,11 +84,11 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
sh.RegisterShutdownTask(mockHandler); sh.RegisterShutdownTask(mockHandler);
// Then: There should be two initialize tasks registered // Then: There should be two initialize tasks registered
Assert.Equal(2, sh.shutdownCallbacks.Count); Assert.AreEqual(2, sh.shutdownCallbacks.Count);
Assert.True(sh.shutdownCallbacks.SequenceEqual(new[] {mockHandler, mockHandler})); Assert.True(sh.shutdownCallbacks.SequenceEqual(new[] {mockHandler, mockHandler}));
} }
[Fact] [Test]
public void RegisterShutdownTaskNullHandler() public void RegisterShutdownTaskNullHandler()
{ {
// If: I register a null initialize task // If: I register a null initialize task
@@ -101,7 +101,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
#region IJsonRpcHost Tests #region IJsonRpcHost Tests
[Fact] [Test]
public void SendEvent() public void SendEvent()
{ {
// If: I send an event // If: I send an event
@@ -113,7 +113,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance), Times.Once); jh.Verify(o => o.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance), Times.Once);
} }
[Fact] [Test]
public async Task SendRequest() public async Task SendRequest()
{ {
// If: I send a request // If: I send a request
@@ -125,7 +125,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance), Times.Once); jh.Verify(o => o.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance), Times.Once);
} }
[Fact] [Test]
public void SetAsyncEventHandler() public void SetAsyncEventHandler()
{ {
// If: I set an event handler // If: I set an event handler
@@ -137,7 +137,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.SetAsyncEventHandler(CommonObjects.EventType, null, true), Times.Once); jh.Verify(o => o.SetAsyncEventHandler(CommonObjects.EventType, null, true), Times.Once);
} }
[Fact] [Test]
public void SetSyncEventHandler() public void SetSyncEventHandler()
{ {
// If: I set an event handler // If: I set an event handler
@@ -149,7 +149,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.SetEventHandler(CommonObjects.EventType, null, true), Times.Once); jh.Verify(o => o.SetEventHandler(CommonObjects.EventType, null, true), Times.Once);
} }
[Fact] [Test]
public void SetAsyncRequestHandler() public void SetAsyncRequestHandler()
{ {
// If: I set a request handler // If: I set a request handler
@@ -161,7 +161,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.SetAsyncRequestHandler(CommonObjects.RequestType, null, true), Times.Once); jh.Verify(o => o.SetAsyncRequestHandler(CommonObjects.RequestType, null, true), Times.Once);
} }
[Fact] [Test]
public void SetSyncRequestHandler() public void SetSyncRequestHandler()
{ {
// If: I set a request handler // If: I set a request handler
@@ -173,7 +173,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.SetRequestHandler(CommonObjects.RequestType, null, true), Times.Once); jh.Verify(o => o.SetRequestHandler(CommonObjects.RequestType, null, true), Times.Once);
} }
[Fact] [Test]
public void Start() public void Start()
{ {
// If: I start a service host // If: I start a service host
@@ -186,7 +186,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.Start(), Times.Once); jh.Verify(o => o.Start(), Times.Once);
} }
[Fact] [Test]
public void Stop() public void Stop()
{ {
// If: I stop a service host // If: I stop a service host
@@ -198,7 +198,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.Stop(), Times.Once); jh.Verify(o => o.Stop(), Times.Once);
} }
[Fact] [Test]
public void WaitForExit() public void WaitForExit()
{ {
// If: I wait for service host to exit // If: I wait for service host to exit
@@ -214,7 +214,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
#region Request Handling Tests #region Request Handling Tests
[Fact] [Test]
public void HandleExitNotification() public void HandleExitNotification()
{ {
// If: I handle an exit notification // If: I handle an exit notification
@@ -226,7 +226,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.Stop(), Times.Once); jh.Verify(o => o.Stop(), Times.Once);
} }
[Fact] [Test]
public async Task HandleInitializeRequest() public async Task HandleInitializeRequest()
{ {
// Setup: // Setup:
@@ -255,14 +255,12 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
// ... The mock handler should have been called twice // ... The mock handler should have been called twice
mockHandler.Verify(h => h(initParams, mockContext), Times.Exactly(2)); mockHandler.Verify(h => h(initParams, mockContext), Times.Exactly(2));
// ... There should have been a response sent
var outgoing = bc.ToArray(); var outgoing = bc.ToArray();
Assert.Single(outgoing); Assert.That(outgoing.Select(m => m.Id), Is.EqualTo(new[] { CommonObjects.MessageId }), "There should have been a response sent");
Assert.Equal(CommonObjects.MessageId, outgoing[0].Id); Assert.AreEqual(JToken.FromObject(ir), JToken.FromObject(ir));
Assert.Equal(JToken.FromObject(ir), JToken.FromObject(ir));
} }
[Fact] [Test]
public async Task HandleShutdownRequest() public async Task HandleShutdownRequest()
{ {
// Setup: // Setup:
@@ -284,12 +282,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
// If: I handle a shutdown request // If: I handle a shutdown request
await sh.HandleShutdownRequest(shutdownParams, mockContext); await sh.HandleShutdownRequest(shutdownParams, mockContext);
// Then: mockHandler.Verify(h => h(shutdownParams, mockContext), Times.Exactly(2), "The mock handler should have been called twice");
// ... The mock handler should have been called twice
mockHandler.Verify(h => h(shutdownParams, mockContext), Times.Exactly(2));
Assert.That(bc.Count, Is.EqualTo(1), "There should have been a response sent");
// ... There should have been a response sent
Assert.Single(bc);
} }
#endregion #endregion
@@ -7,13 +7,14 @@ using System;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Utility; using Microsoft.SqlTools.Hosting.Utility;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
{ {
[TestFixture]
public class AsyncLockTests public class AsyncLockTests
{ {
[Fact] [Test]
public async Task AsyncLockSynchronizesAccess() public async Task AsyncLockSynchronizesAccess()
{ {
AsyncLock asyncLock = new AsyncLock(); AsyncLock asyncLock = new AsyncLock();
@@ -21,15 +22,15 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
Task<IDisposable> lockOne = asyncLock.LockAsync(); Task<IDisposable> lockOne = asyncLock.LockAsync();
Task<IDisposable> lockTwo = asyncLock.LockAsync(); Task<IDisposable> lockTwo = asyncLock.LockAsync();
Assert.Equal(TaskStatus.RanToCompletion, lockOne.Status); Assert.AreEqual(TaskStatus.RanToCompletion, lockOne.Status);
Assert.Equal(TaskStatus.WaitingForActivation, lockTwo.Status); Assert.AreEqual(TaskStatus.WaitingForActivation, lockTwo.Status);
lockOne.Result.Dispose(); lockOne.Result.Dispose();
await lockTwo; await lockTwo;
Assert.Equal(TaskStatus.RanToCompletion, lockTwo.Status); Assert.AreEqual(TaskStatus.RanToCompletion, lockTwo.Status);
} }
[Fact] [Test]
public void AsyncLockCancelsWhenRequested() public void AsyncLockCancelsWhenRequested()
{ {
CancellationTokenSource cts = new CancellationTokenSource(); CancellationTokenSource cts = new CancellationTokenSource();
@@ -42,8 +43,8 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
cts.Cancel(); cts.Cancel();
lockOne.Result.Dispose(); lockOne.Result.Dispose();
Assert.Equal(TaskStatus.RanToCompletion, lockOne.Status); Assert.AreEqual(TaskStatus.RanToCompletion, lockOne.Status);
Assert.Equal(TaskStatus.Canceled, lockTwo.Status); Assert.AreEqual(TaskStatus.Canceled, lockTwo.Status);
} }
} }
} }
@@ -7,10 +7,11 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using Microsoft.SqlTools.Hosting.Utility; using Microsoft.SqlTools.Hosting.Utility;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
{ {
[TestFixture]
/// <summary> /// <summary>
/// Logger test cases /// Logger test cases
/// </summary> /// </summary>
@@ -20,7 +21,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
/// <summary> /// <summary>
/// Test to verify that the logger initialization is generating a valid file /// Test to verify that the logger initialization is generating a valid file
/// </summary> /// </summary>
[Fact] [Test]
public void LoggerDefaultFile() public void LoggerDefaultFile()
{ {
// delete any existing log files from the current directory // delete any existing log files from the current directory
@@ -3,6 +3,4 @@
// 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 Xunit; [assembly: NUnit.Framework.NonParallelizable]
[assembly: CollectionBehavior(DisableTestParallelization = true)]
@@ -7,10 +7,11 @@ using System;
using System.IO; using System.IO;
using Microsoft.SqlTools.ServiceLayer.BatchParser; using Microsoft.SqlTools.ServiceLayer.BatchParser;
using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode; using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
{ {
[TestFixture]
public class BatchParserSqlCmdTests : IDisposable public class BatchParserSqlCmdTests : IDisposable
{ {
private BatchParserSqlCmd bpcmd; private BatchParserSqlCmd bpcmd;
@@ -41,62 +42,62 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
} }
} }
[Fact] [Test]
public void CheckSetVariable() public void CheckSetVariable()
{ {
Assert.Equal(bpcmd.InternalVariables.Count, 3); Assert.AreEqual(3, bpcmd.InternalVariables.Count);
bpcmd.SetVariable(testPOS, "variable4", "test4"); bpcmd.SetVariable(testPOS, "variable4", "test4");
bpcmd.SetVariable(testPOS, "variable5", "test5"); bpcmd.SetVariable(testPOS, "variable5", "test5");
bpcmd.SetVariable(testPOS, "variable6", "test6"); bpcmd.SetVariable(testPOS, "variable6", "test6");
Assert.Equal(bpcmd.InternalVariables.Count, 6); Assert.AreEqual(6, bpcmd.InternalVariables.Count);
} }
[Fact] [Test]
public void CheckSetNullValueVariable() public void CheckSetNullValueVariable()
{ {
Assert.Equal(bpcmd.InternalVariables.Count, 3); Assert.AreEqual(3, bpcmd.InternalVariables.Count);
bpcmd.SetVariable(testPOS, "variable4", "test4"); bpcmd.SetVariable(testPOS, "variable4", "test4");
Assert.Equal(bpcmd.InternalVariables.Count, 4); Assert.AreEqual(4, bpcmd.InternalVariables.Count);
bpcmd.SetVariable(testPOS, "variable4", null); bpcmd.SetVariable(testPOS, "variable4", null);
Assert.Equal(bpcmd.InternalVariables.Count, 3); Assert.AreEqual(3, bpcmd.InternalVariables.Count);
} }
[Fact] [Test]
public void CheckGetVariable() public void CheckGetVariable()
{ {
string value = bpcmd.GetVariable(testPOS, "variable1"); string value = bpcmd.GetVariable(testPOS, "variable1");
Assert.Equal("test1", value); Assert.AreEqual("test1", value);
value = bpcmd.GetVariable(testPOS, "variable2"); value = bpcmd.GetVariable(testPOS, "variable2");
Assert.Equal("test2", value); Assert.AreEqual("test2", value);
value = bpcmd.GetVariable(testPOS, "variable3"); value = bpcmd.GetVariable(testPOS, "variable3");
Assert.Equal("test3", value); Assert.AreEqual("test3", value);
} }
[Fact] [Test]
public void CheckGetNullVariable() public void CheckGetNullVariable()
{ {
Assert.Null(bpcmd.GetVariable(testPOS, "variable6")); Assert.Null(bpcmd.GetVariable(testPOS, "variable6"));
} }
[Fact] [Test]
public void CheckInclude() public void CheckInclude()
{ {
TextReader textReader = null; TextReader textReader = null;
string outString = "out"; string outString = "out";
var result = bpcmd.Include(null, out textReader, out outString); var result = bpcmd.Include(null, out textReader, out outString);
Assert.Equal(result, BatchParserAction.Abort); Assert.AreEqual(BatchParserAction.Abort, result);
} }
[Fact] [Test]
public void CheckOnError() public void CheckOnError()
{ {
var errorActionChanged = bpcmd.ErrorActionChanged; var errorActionChanged = bpcmd.ErrorActionChanged;
var action = new OnErrorAction(); var action = new OnErrorAction();
var result = bpcmd.OnError(null, action); var result = bpcmd.OnError(null, action);
Assert.Equal(result, BatchParserAction.Continue); Assert.AreEqual(BatchParserAction.Continue, result);
} }
[Fact] [Test]
public void CheckConnectionChangedDelegate() public void CheckConnectionChangedDelegate()
{ {
var initial = bpcmd.ConnectionChanged; var initial = bpcmd.ConnectionChanged;
@@ -104,7 +105,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
Assert.Null(bpcmd.ConnectionChanged); Assert.Null(bpcmd.ConnectionChanged);
} }
[Fact] [Test]
public void CheckVariableSubstitutionDisabled() public void CheckVariableSubstitutionDisabled()
{ {
bpcmd.DisableVariableSubstitution(); bpcmd.DisableVariableSubstitution();
@@ -14,12 +14,13 @@ using Microsoft.Data.SqlClient;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Text; using System.Text;
using Xunit; using NUnit.Framework;
using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.Connection;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
{ {
[TestFixture]
public class BatchParserTests : BaselinedTest public class BatchParserTests : BaselinedTest
{ {
public BatchParserTests() public BatchParserTests()
@@ -34,7 +35,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
TestInitialize(); TestInitialize();
} }
[Fact] [Test]
public void VerifyThrowOnUnresolvedVariable() public void VerifyThrowOnUnresolvedVariable()
{ {
string script = "print '$(NotDefined)'"; string script = "print '$(NotDefined)'";
@@ -59,7 +60,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
/// Variable parameter in powershell: Specifies, as a string array, a sqlcmd scripting variable /// Variable parameter in powershell: Specifies, as a string array, a sqlcmd scripting variable
/// for use in the sqlcmd script, and sets a value for the variable. /// for use in the sqlcmd script, and sets a value for the variable.
/// </summary> /// </summary>
[Fact] [Test]
public void VerifyVariableResolverUsingVaribleParameter() public void VerifyVariableResolverUsingVaribleParameter()
{ {
string query = @" Invoke-Sqlcmd -Query ""SELECT `$(calcOne)"" -Variable ""calcOne = 10 + 20"" "; string query = @" Invoke-Sqlcmd -Query ""SELECT `$(calcOne)"" -Variable ""calcOne = 10 + 20"" ";
@@ -79,7 +80,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
} }
// Verify the starting identifier of Both parameter and variable are same. // Verify the starting identifier of Both parameter and variable are same.
[Fact] [Test]
public void VerifyVariableResolverIsStartIdentifierChar() public void VerifyVariableResolverIsStartIdentifierChar()
{ {
// instead of using variable calcOne, I purposely used In-variable 0alcOne // instead of using variable calcOne, I purposely used In-variable 0alcOne
@@ -100,7 +101,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
} }
// Verify all the characters inside variable are valid Identifier. // Verify all the characters inside variable are valid Identifier.
[Fact] [Test]
public void VerifyVariableResolverIsIdentifierChar() public void VerifyVariableResolverIsIdentifierChar()
{ {
// instead of using variable calcOne, I purposely used In-variable 0alcOne // instead of using variable calcOne, I purposely used In-variable 0alcOne
@@ -121,7 +122,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
} }
// Verify the execution by passing long value , Except a exception. // Verify the execution by passing long value , Except a exception.
[Fact] [Test]
public void VerifyInvalidNumber() public void VerifyInvalidNumber()
{ {
string query = @" SELECT 1+1 string query = @" SELECT 1+1
@@ -144,7 +145,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
} }
// Verify the Batch execution is executed successfully. // Verify the Batch execution is executed successfully.
[Fact] [Test]
public void VerifyExecute() public void VerifyExecute()
{ {
Batch batch = new Batch(sqlText: "SELECT 1+1", isResultExpected: true, execTimeout: 15); Batch batch = new Batch(sqlText: "SELECT 1+1", isResultExpected: true, execTimeout: 15);
@@ -152,13 +153,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
{ {
var executionResult = batch.Execute(sqlConn, ShowPlanType.AllShowPlan); var executionResult = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
Assert.Equal<ScriptExecutionResult>(ScriptExecutionResult.Success, executionResult); Assert.AreEqual(ScriptExecutionResult.Success, executionResult);
} }
} }
// Verify the exeception is handled by passing invalid keyword. // Verify the exeception is handled by passing invalid keyword.
[Fact] [Test]
public void VerifyHandleExceptionMessage() public void VerifyHandleExceptionMessage()
{ {
Batch batch = new Batch(sqlText: "SEL@ECT 1+1", isResultExpected: true, execTimeout: 15); Batch batch = new Batch(sqlText: "SEL@ECT 1+1", isResultExpected: true, execTimeout: 15);
@@ -169,11 +170,11 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
} }
ScriptExecutionResult finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; ScriptExecutionResult finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure;
Assert.Equal<ScriptExecutionResult>(finalResult, ScriptExecutionResult.Failure); Assert.AreEqual(ScriptExecutionResult.Failure, finalResult);
} }
// Verify the passing query has valid text. // Verify the passing query has valid text.
[Fact] [Test]
public void VerifyHasValidText() public void VerifyHasValidText()
{ {
Batch batch = new Batch(sqlText: null, isResultExpected: true, execTimeout: 15); Batch batch = new Batch(sqlText: null, isResultExpected: true, execTimeout: 15);
@@ -185,11 +186,11 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
} }
finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure;
Assert.Equal<ScriptExecutionResult>(finalResult, ScriptExecutionResult.Failure); Assert.AreEqual(ScriptExecutionResult.Failure, finalResult);
} }
// Verify the cancel functionality is working fine. // Verify the cancel functionality is working fine.
[Fact] [Test]
public void VerifyCancel() public void VerifyCancel()
{ {
ScriptExecutionResult result = ScriptExecutionResult.All; ScriptExecutionResult result = ScriptExecutionResult.All;
@@ -200,14 +201,14 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
batch.Cancel(); batch.Cancel();
result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan); result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
} }
Assert.Equal<ScriptExecutionResult>(result, ScriptExecutionResult.Cancel); Assert.AreEqual(ScriptExecutionResult.Cancel, result);
} }
// //
/// <summary> /// <summary>
/// Verify whether lexer can consume token for SqlCmd variable /// Verify whether lexer can consume token for SqlCmd variable
/// </summary> /// </summary>
[Fact] [Test]
public void VerifyLexerSetState() public void VerifyLexerSetState()
{ {
try try
@@ -229,7 +230,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
// This test case is to verify that, Powershell's Invoke-SqlCmd handles ":!!if" in an inconsistent way // This test case is to verify that, Powershell's Invoke-SqlCmd handles ":!!if" in an inconsistent way
// Inconsistent way means, instead of throwing an exception as "Command Execute is not supported." it was throwing "Incorrect syntax near ':'." // Inconsistent way means, instead of throwing an exception as "Command Execute is not supported." it was throwing "Incorrect syntax near ':'."
[Fact] [Test]
public void VerifySqlCmdExecute() public void VerifySqlCmdExecute()
{ {
string query = ":!!if exist foo.txt del foo.txt"; string query = ":!!if exist foo.txt del foo.txt";
@@ -247,12 +248,12 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
var exception = Assert.Throws<BatchParserException>(() => p.Parse()); var exception = Assert.Throws<BatchParserException>(() => p.Parse());
// Verify the message should be "Command Execute is not supported." // Verify the message should be "Command Execute is not supported."
Assert.Equal("Command Execute is not supported.", exception.Message); Assert.AreEqual("Command Execute is not supported.", exception.Message);
} }
} }
// This test case is to verify that, Lexer type for :!!If was set to "Text" instead of "Execute" // This test case is to verify that, Lexer type for :!!If was set to "Text" instead of "Execute"
[Fact] [Test]
public void VerifyLexerTypeOfSqlCmdIFisExecute() public void VerifyLexerTypeOfSqlCmdIFisExecute()
{ {
string query = ":!!if exist foo.txt del foo.txt"; string query = ":!!if exist foo.txt del foo.txt";
@@ -264,33 +265,26 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
type = lexer.CurrentTokenType; type = lexer.CurrentTokenType;
} }
// we are expecting the lexer type should to be Execute. // we are expecting the lexer type should to be Execute.
Assert.Equal("Execute", type.ToString()); Assert.AreEqual("Execute", type.ToString());
} }
// Verify the custom exception functionality by raising user defined error. // Verify the custom exception functionality by raising user defined error.
[Fact] [Test]
public void VerifyCustomBatchParserException() public void VerifyCustomBatchParserException()
{ {
string message = "This is userDefined Error"; string message = "This is userDefined Error";
Token token = new Token(LexerTokenType.Text, new PositionStruct(), new PositionStruct(), message, "test"); Token token = new Token(LexerTokenType.Text, new PositionStruct(), new PositionStruct(), message, "test");
BatchParserException batchParserException = new BatchParserException(ErrorCode.VariableNotDefined, token, message); BatchParserException batchParserException = new BatchParserException(ErrorCode.VariableNotDefined, token, message);
try
{ Assert.AreEqual(batchParserException.ErrorCode.ToString(), ErrorCode.VariableNotDefined.ToString());
throw new BatchParserException(ErrorCode.UnrecognizedToken, token, "test"); Assert.AreEqual(message, batchParserException.Text);
} Assert.AreEqual(LexerTokenType.Text.ToString(), batchParserException.TokenType.ToString());
catch (Exception ex)
{
Assert.Equal(batchParserException.ErrorCode.ToString(), ErrorCode.VariableNotDefined.ToString());
Assert.Equal(message, batchParserException.Text);
Assert.Equal(LexerTokenType.Text.ToString(), batchParserException.TokenType.ToString());
Assert.IsType<BatchParserException>(ex);
}
} }
// Verify whether the executionEngine execute script // Verify whether the executionEngine execute script
[Fact] [Test]
public void VerifyExecuteScript() public void VerifyExecuteScript()
{ {
using (ExecutionEngine executionEngine = new ExecutionEngine()) using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -305,13 +299,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
ScriptExecutionResult result = (testExecutor.ExecutionResult == ScriptExecutionResult.Success) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; ScriptExecutionResult result = (testExecutor.ExecutionResult == ScriptExecutionResult.Success) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure;
Assert.Equal<ScriptExecutionResult>(ScriptExecutionResult.Success, result); Assert.AreEqual(ScriptExecutionResult.Success, result);
} }
} }
} }
// Verify whether the batchParser execute SqlCmd. // Verify whether the batchParser execute SqlCmd.
//[Fact] // This Testcase should execute and pass, But it is failing now. //[Test] // This Testcase should execute and pass, But it is failing now.
public void VerifyIsSqlCmd() public void VerifyIsSqlCmd()
{ {
using (ExecutionEngine executionEngine = new ExecutionEngine()) using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -330,7 +324,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
/// <summary> /// <summary>
/// Verify whether the batchParser execute SqlCmd successfully /// Verify whether the batchParser execute SqlCmd successfully
/// </summary> /// </summary>
[Fact] [Test]
public void VerifyRunSqlCmd() public void VerifyRunSqlCmd()
{ {
using (ExecutionEngine executionEngine = new ExecutionEngine()) using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -365,7 +359,7 @@ GO";
/// <summary> /// <summary>
/// Verify whether the batchParser parsed :connect command successfully /// Verify whether the batchParser parsed :connect command successfully
/// </summary> /// </summary>
[Fact] [Test]
public void VerifyConnectSqlCmd() public void VerifyConnectSqlCmd()
{ {
using (ExecutionEngine executionEngine = new ExecutionEngine()) using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -374,14 +368,15 @@ GO";
string serverName = liveConnection.ConnectionInfo.ConnectionDetails.ServerName; string serverName = liveConnection.ConnectionInfo.ConnectionDetails.ServerName;
string userName = liveConnection.ConnectionInfo.ConnectionDetails.UserName; string userName = liveConnection.ConnectionInfo.ConnectionDetails.UserName;
string password = liveConnection.ConnectionInfo.ConnectionDetails.Password; string password = liveConnection.ConnectionInfo.ConnectionDetails.Password;
var credentials = string.IsNullOrEmpty(userName) ? string.Empty : $"-U {userName} -P {password}";
string sqlCmdQuery = $@" string sqlCmdQuery = $@"
:Connect {serverName} -U {userName} -P {password} :Connect {serverName}{credentials}
GO GO
select * from sys.databases where name = 'master' select * from sys.databases where name = 'master'
GO"; GO";
string sqlCmdQueryIncorrect = $@" string sqlCmdQueryIncorrect = $@"
:Connect {serverName} -u {userName} -p {password} :Connect {serverName} -u uShouldbeUpperCase -p pShouldbeUpperCase
GO GO
select * from sys.databases where name = 'master' select * from sys.databases where name = 'master'
GO"; GO";
@@ -390,17 +385,23 @@ GO";
using (TestExecutor testExecutor = new TestExecutor(sqlCmdQuery, sqlConn, condition)) using (TestExecutor testExecutor = new TestExecutor(sqlCmdQuery, sqlConn, condition))
{ {
testExecutor.Run(); testExecutor.Run();
Assert.True(testExecutor.ParserExecutionError == false, "Parse Execution error should be false"); Assert.Multiple(() =>
Assert.True(testExecutor.ResultCountQueue.Count == 1, $"Unexpected number of ResultCount items - expected 1 but got {testExecutor.ResultCountQueue.Count}"); {
Assert.True(testExecutor.ErrorMessageQueue.Count == 0, $"Unexpected error messages from test executor : {string.Join(Environment.NewLine, testExecutor.ErrorMessageQueue)}"); Assert.That(testExecutor.ParserExecutionError, Is.False, "Parse Execution error should be false");
Assert.That(testExecutor.ResultCountQueue.Count, Is.EqualTo(1), "Unexpected number of ResultCount items");
Assert.That(testExecutor.ErrorMessageQueue, Is.Empty, "Unexpected error messages from test executor");
});
} }
using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
using (TestExecutor testExecutor = new TestExecutor(sqlCmdQueryIncorrect, sqlConn, condition)) using (TestExecutor testExecutor = new TestExecutor(sqlCmdQueryIncorrect, sqlConn, condition))
{ {
testExecutor.Run(); testExecutor.Run();
Assert.Multiple(() =>
Assert.True(testExecutor.ParserExecutionError == true, "Parse Execution error should be true"); {
Assert.True(testExecutor.ParserExecutionError, "Parse Execution error should be true");
Assert.That(testExecutor.ErrorMessageQueue, Has.Member("Incorrect syntax was encountered while -u was being parsed."), "error message expected");
});
} }
} }
} }
@@ -408,7 +409,7 @@ GO";
/// <summary> /// <summary>
/// Verify whether the batchParser parsed :on error successfully /// Verify whether the batchParser parsed :on error successfully
/// </summary> /// </summary>
[Fact] [Test]
public void VerifyOnErrorSqlCmd() public void VerifyOnErrorSqlCmd()
{ {
using (ExecutionEngine executionEngine = new ExecutionEngine()) using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -443,7 +444,7 @@ GO";
/// <summary> /// <summary>
/// Verify whether the batchParser parses Include command i.e. :r successfully /// Verify whether the batchParser parses Include command i.e. :r successfully
/// </summary> /// </summary>
[Fact] [Test]
public void VerifyIncludeSqlCmd() public void VerifyIncludeSqlCmd()
{ {
string file = "VerifyIncludeSqlCmd_test.sql"; string file = "VerifyIncludeSqlCmd_test.sql";
@@ -486,7 +487,7 @@ GO";
} }
// Verify whether the executionEngine execute Batch // Verify whether the executionEngine execute Batch
[Fact] [Test]
public void VerifyExecuteBatch() public void VerifyExecuteBatch()
{ {
using (ExecutionEngine executionEngine = new ExecutionEngine()) using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -498,7 +499,7 @@ GO";
var executionPromise = new TaskCompletionSource<bool>(); var executionPromise = new TaskCompletionSource<bool>();
executionEngine.BatchParserExecutionFinished += (object sender, BatchParserExecutionFinishedEventArgs e) => executionEngine.BatchParserExecutionFinished += (object sender, BatchParserExecutionFinishedEventArgs e) =>
{ {
Assert.Equal(ScriptExecutionResult.Success, e.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success, e.ExecutionResult);
executionPromise.SetResult(true); executionPromise.SetResult(true);
}; };
executionEngine.ExecuteBatch(new ScriptExecutionArgs(query, sqlConn, 15, new ExecutionEngineConditions(), new BatchParserMockEventHandler())); executionEngine.ExecuteBatch(new ScriptExecutionArgs(query, sqlConn, 15, new ExecutionEngineConditions(), new BatchParserMockEventHandler()));
@@ -508,7 +509,7 @@ GO";
} }
} }
[Fact] [Test]
public void CanceltheBatch() public void CanceltheBatch()
{ {
Batch batch = new Batch(); Batch batch = new Batch();
@@ -567,7 +568,7 @@ GO";
if (lexerError == false) if (lexerError == false)
{ {
// Verify that all text from tokens can be recombined into original string // Verify that all text from tokens can be recombined into original string
Assert.Equal<string>(inputText, roundtripTextBuilder.ToString()); Assert.AreEqual(inputText, roundtripTextBuilder.ToString());
} }
} }
} }
@@ -6,31 +6,32 @@
using System; using System;
using Microsoft.SqlTools.ServiceLayer.BatchParser; using Microsoft.SqlTools.ServiceLayer.BatchParser;
using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode; using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
{ {
[TestFixture]
public class BatchParserWrapperTests public class BatchParserWrapperTests
{ {
[Fact] [Test]
public void CheckSimpleSingleSQLBatchStatement() public void CheckSimpleSingleSQLBatchStatement()
{ {
using (BatchParserWrapper parserWrapper = new BatchParserWrapper()) using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
{ {
string sqlScript = "select * from sys.objects"; string sqlScript = "select * from sys.objects";
var batches = parserWrapper.GetBatches(sqlScript); var batches = parserWrapper.GetBatches(sqlScript);
Assert.Equal(1, batches.Count); Assert.AreEqual(1, batches.Count);
BatchDefinition batch = batches[0]; BatchDefinition batch = batches[0];
Assert.Equal(sqlScript, batch.BatchText); Assert.AreEqual(sqlScript, batch.BatchText);
Assert.Equal(1, batch.StartLine); Assert.AreEqual(1, batch.StartLine);
Assert.Equal(1, batch.StartColumn); Assert.AreEqual(1, batch.StartColumn);
Assert.Equal(2, batch.EndLine); Assert.AreEqual(2, batch.EndLine);
Assert.Equal(sqlScript.Length + 1, batch.EndColumn); Assert.AreEqual(sqlScript.Length + 1, batch.EndColumn);
Assert.Equal(1, batch.BatchExecutionCount); Assert.AreEqual(1, batch.BatchExecutionCount);
} }
} }
[Fact] [Test]
public void CheckSimpleMultipleQLBatchStatement() public void CheckSimpleMultipleQLBatchStatement()
{ {
using (BatchParserWrapper parserWrapper = new BatchParserWrapper()) using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
@@ -44,48 +45,48 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
SELECT 'LastLine'"; SELECT 'LastLine'";
var batches = parserWrapper.GetBatches(sqlScript); var batches = parserWrapper.GetBatches(sqlScript);
// Each select statement is one batch , so we are expecting 4 batches. // Each select statement is one batch , so we are expecting 4 batches.
Assert.Equal(4, batches.Count); Assert.AreEqual(4, batches.Count);
} }
} }
[Fact] [Test]
public void CheckSQLBatchStatementWithRepeatExecution() public void CheckSQLBatchStatementWithRepeatExecution()
{ {
using (BatchParserWrapper parserWrapper = new BatchParserWrapper()) using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
{ {
string sqlScript = "select * from sys.object" + Environment.NewLine + "GO 2"; string sqlScript = "select * from sys.object" + Environment.NewLine + "GO 2";
var batches = parserWrapper.GetBatches(sqlScript); var batches = parserWrapper.GetBatches(sqlScript);
Assert.Equal(1, batches.Count); Assert.AreEqual(1, batches.Count);
BatchDefinition batch = batches[0]; BatchDefinition batch = batches[0];
Assert.Equal(2, batch.BatchExecutionCount); Assert.AreEqual(2, batch.BatchExecutionCount);
} }
} }
[Fact] [Test]
public void CheckComment() public void CheckComment()
{ {
using (BatchParserWrapper parserWrapper = new BatchParserWrapper()) using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
{ {
string sqlScript = "-- this is a comment --"; string sqlScript = "-- this is a comment --";
var batches = parserWrapper.GetBatches(sqlScript); var batches = parserWrapper.GetBatches(sqlScript);
Assert.Equal(1, batches.Count); Assert.AreEqual(1, batches.Count);
BatchDefinition batch = batches[0]; BatchDefinition batch = batches[0];
Assert.Equal(sqlScript, batch.BatchText); Assert.AreEqual(sqlScript, batch.BatchText);
Assert.Equal(1, batch.StartLine); Assert.AreEqual(1, batch.StartLine);
Assert.Equal(1, batch.StartColumn); Assert.AreEqual(1, batch.StartColumn);
Assert.Equal(2, batch.EndLine); Assert.AreEqual(2, batch.EndLine);
Assert.Equal(sqlScript.Length + 1, batch.EndColumn); Assert.AreEqual(sqlScript.Length + 1, batch.EndColumn);
} }
} }
[Fact] [Test]
public void CheckNoOps() public void CheckNoOps()
{ {
using (BatchParserWrapper parserWrapper = new BatchParserWrapper()) using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
{ {
string sqlScript = "GO"; string sqlScript = "GO";
var batches = parserWrapper.GetBatches(sqlScript); var batches = parserWrapper.GetBatches(sqlScript);
Assert.Equal(0, batches.Count); Assert.AreEqual(0, batches.Count);
} }
} }
} }
@@ -19,8 +19,9 @@
<PackageReference Include="System.Net.Http"/> <PackageReference Include="System.Net.Http"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Moq" /> <PackageReference Include="Moq" />
<PackageReference Include="xunit" /> <PackageReference Include="nunit" />
<PackageReference Include="xunit.runner.visualstudio" /> <PackageReference Include="nunit3testadapter" />
<PackageReference Include="nunit.console" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
@@ -12,15 +12,16 @@ using Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode; using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode;
using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEngine namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEngine
{ {
[TestFixture]
/// <summary> /// <summary>
///This is a test class for Microsoft.Data.Tools.Schema.Common.ExecutionEngine.ExecutionEngine and is intended ///This is a test class for Microsoft.Data.Tools.Schema.Common.ExecutionEngine.ExecutionEngine and is intended
///to contain all Microsoft.Data.Tools.Schema.Common.ExecutionEngine.ExecutionEngine Unit Tests ///to contain all Microsoft.Data.Tools.Schema.Common.ExecutionEngine.ExecutionEngine Unit Tests
///</summary> ///</summary>
public class ExecutionEngineTest : IDisposable public class ExecutionEngineTest : IDisposable
{ {
private SqlConnection connection; private SqlConnection connection;
@@ -29,11 +30,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
#region Test Initialize And Cleanup #region Test Initialize And Cleanup
public ExecutionEngineTest() [SetUp]
{
TestInitialize();
}
// Initialize the tests // Initialize the tests
public void TestInitialize() public void TestInitialize()
{ {
@@ -80,7 +77,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
///A test for a simple SQL script ///A test for a simple SQL script
///</summary> ///</summary>
[Fact] [Test]
public void ExecutionEngineTest_SimpleTest() public void ExecutionEngineTest_SimpleTest()
{ {
string sqlStatement = "SELECT * FROM sysobjects"; string sqlStatement = "SELECT * FROM sysobjects";
@@ -97,15 +94,15 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
Assert.Equal(1, executor.BatchFinshedEventCounter); Assert.AreEqual(1, executor.BatchFinshedEventCounter);
} }
/// <summary> /// <summary>
/// Test with a valid script using default execution condition /// Test with a valid script using default execution condition
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_DefaultCondition_ValidScript() public void ExecutionEngineTest_DefaultCondition_ValidScript()
{ {
string sqlStatement = "select * from sysobjects\nGo\n"; string sqlStatement = "select * from sysobjects\nGo\n";
@@ -119,14 +116,14 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
} }
// <summary> // <summary>
// Test with multiple valid scripts in multiple batches // Test with multiple valid scripts in multiple batches
// </summary> // </summary>
[Fact] [Test]
public void ExecutionEngineTest_MultiValidScripts() public void ExecutionEngineTest_MultiValidScripts()
{ {
string sqlStatement = "select * from sys.databases\ngo\nselect name from sys.databases\ngo\nprint 'test'\ngo"; string sqlStatement = "select * from sys.databases\ngo\nselect name from sys.databases\ngo\nprint 'test'\ngo";
@@ -143,14 +140,14 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
} }
/// <summary> /// <summary>
/// Test with SQL comment /// Test with SQL comment
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_TestComment() public void ExecutionEngineTest_TestComment()
{ {
string sqlStatement = "/*test comments*/"; string sqlStatement = "/*test comments*/";
@@ -167,7 +164,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
} }
@@ -178,7 +175,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// Test with a invalid query using the default execution condition /// Test with a invalid query using the default execution condition
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_DefaultCondition_InvalidScript() public void ExecutionEngineTest_DefaultCondition_InvalidScript()
{ {
string sqlStatement = "select ** from sysobjects"; string sqlStatement = "select ** from sysobjects";
@@ -192,17 +189,17 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success | ScriptExecutionResult.Failure, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success | ScriptExecutionResult.Failure, executor.ExecutionResult);
Assert.True(!executor.ParserExecutionError); Assert.True(!executor.ParserExecutionError);
Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage)); Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
Assert.Equal(0, executor.BatchFinshedEventCounter); Assert.AreEqual(0, executor.BatchFinshedEventCounter);
} }
/// <summary> /// <summary>
/// Test with an invalid query using a defined execution condition /// Test with an invalid query using a defined execution condition
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_InvalidScriptWithCondition() public void ExecutionEngineTest_InvalidScriptWithCondition()
{ {
string sqlStatement = "select * from authors"; string sqlStatement = "select * from authors";
@@ -218,7 +215,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(executor.ExecutionResult, ScriptExecutionResult.Success | ScriptExecutionResult.Failure); Assert.AreEqual(executor.ExecutionResult, ScriptExecutionResult.Success | ScriptExecutionResult.Failure);
Assert.True(!executor.ParserExecutionError); Assert.True(!executor.ParserExecutionError);
Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage)); Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
@@ -227,7 +224,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// Test with multiple invalid scripts in multiple batches /// Test with multiple invalid scripts in multiple batches
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_MultipleInvalidScript() public void ExecutionEngineTest_MultipleInvalidScript()
{ {
string sqlStatement = "select ** from products \ngo\n insert into products values (1,'abc')\n go \n"; string sqlStatement = "select ** from products \ngo\n insert into products values (1,'abc')\n go \n";
@@ -244,7 +241,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(executor.ExecutionResult, ScriptExecutionResult.Success | ScriptExecutionResult.Failure); Assert.AreEqual(executor.ExecutionResult, ScriptExecutionResult.Success | ScriptExecutionResult.Failure);
Assert.True(!executor.ParserExecutionError); Assert.True(!executor.ParserExecutionError);
Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage)); Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
@@ -253,7 +250,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// Test with invalid scripts within a single batch /// Test with invalid scripts within a single batch
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_MultipleInvalidScript_SingleBatch() public void ExecutionEngineTest_MultipleInvalidScript_SingleBatch()
{ {
string sqlStatement = "select ** from products \n insert into products values (1,'abc')\n go \n"; string sqlStatement = "select ** from products \n insert into products values (1,'abc')\n go \n";
@@ -270,7 +267,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success | ScriptExecutionResult.Failure, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success | ScriptExecutionResult.Failure, executor.ExecutionResult);
Assert.True(!executor.ParserExecutionError); Assert.True(!executor.ParserExecutionError);
Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage)); Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
@@ -279,7 +276,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// Test with mixed valid and invalid scripts /// Test with mixed valid and invalid scripts
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_MixedValidandInvalidScript() public void ExecutionEngineTest_MixedValidandInvalidScript()
{ {
string sqlStatement = "SELECT * FROM Authors \n Go\n select * from sysobjects \n go\nif exists (select * from sysobjects where id = object_id('MyTab')) DROP TABLE MyTab2"; string sqlStatement = "SELECT * FROM Authors \n Go\n select * from sysobjects \n go\nif exists (select * from sysobjects where id = object_id('MyTab')) DROP TABLE MyTab2";
@@ -296,13 +293,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(executor.ExecutionResult, ScriptExecutionResult.Success | ScriptExecutionResult.Failure); Assert.AreEqual(executor.ExecutionResult, ScriptExecutionResult.Success | ScriptExecutionResult.Failure);
Assert.True(!executor.ParserExecutionError); Assert.True(!executor.ParserExecutionError);
Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage)); Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
} }
[Fact] [Test]
public void ExecutionEngineTest_DiscardConnection() public void ExecutionEngineTest_DiscardConnection()
{ {
ExecutionEngine engine = new ExecutionEngine(); ExecutionEngine engine = new ExecutionEngine();
@@ -316,14 +313,16 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// Test HaltOnError execution condition /// Test HaltOnError execution condition
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_HaltOnError() public void ExecutionEngineTest_HaltOnError()
{ {
string sqlStatement = "select * from authors\n go\n select * from sysbojects \n go \n"; string sqlStatement = "select * from authors\n go\n select * from sysbojects \n go \n";
ExecutionEngineConditions conditions = new ExecutionEngineConditions(); ExecutionEngineConditions conditions = new ExecutionEngineConditions
conditions.IsTransactionWrapped = true; {
conditions.IsParseOnly = false; IsTransactionWrapped = true,
conditions.IsHaltOnError = true; IsParseOnly = false,
IsHaltOnError = true
};
TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions); TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions);
executor.Run(); executor.Run();
@@ -332,7 +331,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Halted | ScriptExecutionResult.Failure, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Halted | ScriptExecutionResult.Failure, executor.ExecutionResult);
Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage)); Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
Assert.True(executor.ResultCountQueue.Count == 0); Assert.True(executor.ResultCountQueue.Count == 0);
@@ -341,7 +340,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// HaltOnError with a single batch /// HaltOnError with a single batch
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_HaltOnError_OneBatch() public void ExecutionEngineTest_HaltOnError_OneBatch()
{ {
string sqlStatement = "select * from authors\n go 30\n"; string sqlStatement = "select * from authors\n go 30\n";
@@ -357,17 +356,17 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Halted | ScriptExecutionResult.Failure, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Halted | ScriptExecutionResult.Failure, executor.ExecutionResult);
Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage)); Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
Assert.True(executor.ResultCountQueue.Count == 0); Assert.True(executor.ResultCountQueue.Count == 0);
Assert.Equal(0, executor.BatchFinshedEventCounter); Assert.AreEqual(0, executor.BatchFinshedEventCounter);
} }
/// <summary> /// <summary>
/// Test ParseOnly execution condition with valid scripts /// Test ParseOnly execution condition with valid scripts
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_ParseOnly_ValidScript() public void ExecutionEngineTest_ParseOnly_ValidScript()
{ {
string sqlStatement = "select * from sysobjects"; string sqlStatement = "select * from sysobjects";
@@ -379,15 +378,15 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions); TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions);
executor.Run(); executor.Run();
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(executor.ResultCountQueue.Count == 0); Assert.True(executor.ResultCountQueue.Count == 0);
Assert.Equal(0, executor.BatchFinshedEventCounter); Assert.AreEqual(0, executor.BatchFinshedEventCounter);
} }
/// <summary> /// <summary>
/// Test HaltOnError execution condition with invalid scripts /// Test HaltOnError execution condition with invalid scripts
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_ParseOnly_InvalidScript() public void ExecutionEngineTest_ParseOnly_InvalidScript()
{ {
string sqlStatement = "select ** from authors"; string sqlStatement = "select ** from authors";
@@ -403,7 +402,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success | ScriptExecutionResult.Failure, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success | ScriptExecutionResult.Failure, executor.ExecutionResult);
Assert.True(!executor.ParserExecutionError); Assert.True(!executor.ParserExecutionError);
Assert.True(executor.ResultCountQueue.Count == 0); Assert.True(executor.ResultCountQueue.Count == 0);
Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage)); Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
@@ -412,7 +411,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// Parse script only without transaction wrapper /// Parse script only without transaction wrapper
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_ParseOnly_ValidScriptWithoutTransaction() public void ExecutionEngineTest_ParseOnly_ValidScriptWithoutTransaction()
{ {
string sqlStatement = "select * from sysobjects"; string sqlStatement = "select * from sysobjects";
@@ -424,9 +423,9 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions); TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions);
executor.Run(); executor.Run();
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(executor.ResultCountQueue.Count == 0); Assert.True(executor.ResultCountQueue.Count == 0);
Assert.Equal(0, executor.BatchFinshedEventCounter); Assert.AreEqual(0, executor.BatchFinshedEventCounter);
} }
/// <summary> /// <summary>
@@ -443,13 +442,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions, -1); TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions, -1);
executor.Run(); executor.Run();
Assert.Equal(executor.ExecutionResult, ScriptExecutionResult.Success); Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
} }
/// <summary> /// <summary>
/// Test with invalid connection /// Test with invalid connection
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_InvalidConnection() public void ExecutionEngineTest_InvalidConnection()
{ {
string sqlStatement = "select * from sysobjects\n go 100\n"; string sqlStatement = "select * from sysobjects\n go 100\n";
@@ -470,7 +469,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// Test with multiple conditions true /// Test with multiple conditions true
/// </summary> /// </summary>
[Fact] [Test]
public void TestExecutionEngineConditions() public void TestExecutionEngineConditions()
{ {
string sqlStatement = "select * from sys.databases\ngo\nselect name from sys.databases\ngo\nprint 'test'\ngo"; string sqlStatement = "select * from sys.databases\ngo\nselect name from sys.databases\ngo\nprint 'test'\ngo";
@@ -486,7 +485,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts; List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection); ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
} }
@@ -497,7 +496,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// Test with SQL commands /// Test with SQL commands
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_SQLCmds() public void ExecutionEngineTest_SQLCmds()
{ {
string[] sqlStatements = { string[] sqlStatements = {
@@ -537,7 +536,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary> /// <summary>
/// Test synchronous cancel /// Test synchronous cancel
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_SyncCancel() public void ExecutionEngineTest_SyncCancel()
{ {
string sqlStatement = "waitfor delay '0:0:10'"; string sqlStatement = "waitfor delay '0:0:10'";
@@ -552,14 +551,14 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
executor.Run(); executor.Run();
Assert.NotNull(executor.ScriptExecuteThread); Assert.NotNull(executor.ScriptExecuteThread);
Assert.Equal(ScriptExecutionResult.Cancel, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Cancel, executor.ExecutionResult);
Assert.True(executor.CancelEventFired); Assert.True(executor.CancelEventFired);
} }
/// <summary> /// <summary>
/// Test asynchronous cancel /// Test asynchronous cancel
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_ASyncCancel() public void ExecutionEngineTest_ASyncCancel()
{ {
//string sqlStatement = "--This is a test\nSELECT * FROM sysobjects as t\nGO 50\n use pubsplus \n select * from titles\n go" ; //string sqlStatement = "--This is a test\nSELECT * FROM sysobjects as t\nGO 50\n use pubsplus \n select * from titles\n go" ;
@@ -578,7 +577,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Assert.NotNull(executor.ScriptExecuteThread); Assert.NotNull(executor.ScriptExecuteThread);
if (executor.ScriptExecuteThread != null) if (executor.ScriptExecuteThread != null)
Assert.True(!executor.ScriptExecuteThread.IsAlive); Assert.True(!executor.ScriptExecuteThread.IsAlive);
Assert.Equal(ScriptExecutionResult.Cancel, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Cancel, executor.ExecutionResult);
} }
/// <summary> /// <summary>
@@ -604,13 +603,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Assert.NotNull(executor.ScriptExecuteThread); Assert.NotNull(executor.ScriptExecuteThread);
if (executor.ScriptExecuteThread != null) if (executor.ScriptExecuteThread != null)
Assert.True(!executor.ScriptExecuteThread.IsAlive); Assert.True(!executor.ScriptExecuteThread.IsAlive);
Assert.Equal(ScriptExecutionResult.Success | ScriptExecutionResult.Cancel, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success | ScriptExecutionResult.Cancel, executor.ExecutionResult);
} }
/// <summary> /// <summary>
/// Test async cancel when the execution is done /// Test async cancel when the execution is done
/// </summary> /// </summary>
[Fact] [Test]
public void ExecutionEngineTest_ASyncCancelAfterExecutionDone() public void ExecutionEngineTest_ASyncCancelAfterExecutionDone()
{ {
string sqlStatement = "select 1"; string sqlStatement = "select 1";
@@ -628,13 +627,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Assert.NotNull(executor.ScriptExecuteThread); Assert.NotNull(executor.ScriptExecuteThread);
if (executor.ScriptExecuteThread != null) if (executor.ScriptExecuteThread != null)
Assert.True(!executor.ScriptExecuteThread.IsAlive); Assert.True(!executor.ScriptExecuteThread.IsAlive);
Assert.Equal(ScriptExecutionResult.Success | ScriptExecutionResult.Cancel, executor.ExecutionResult); Assert.AreEqual(ScriptExecutionResult.Success | ScriptExecutionResult.Cancel, executor.ExecutionResult);
} }
/// <summary> /// <summary>
/// Test multiple threads of execution engine with cancel operation /// Test multiple threads of execution engine with cancel operation
/// </summary> /// </summary>
[Fact] [Test]
public async Task ExecutionEngineTest_MultiThreading_WithCancel() public async Task ExecutionEngineTest_MultiThreading_WithCancel()
{ {
string[] sqlStatement = { "waitfor delay '0:0:10'", string[] sqlStatement = { "waitfor delay '0:0:10'",
@@ -693,7 +692,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
#region Get/Set Methods #region Get/Set Methods
[Fact] [Test]
public void TestShowStatements() public void TestShowStatements()
{ {
Assert.NotNull(ExecutionEngineConditions.ShowPlanXmlStatement(true)); Assert.NotNull(ExecutionEngineConditions.ShowPlanXmlStatement(true));
@@ -708,48 +707,48 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Assert.NotNull(ExecutionEngineConditions.ResetStatement); Assert.NotNull(ExecutionEngineConditions.ResetStatement);
} }
[Fact] [Test]
public void TestExecutionEngineConditionsSetMethods() public void TestExecutionEngineConditionsSetMethods()
{ {
ExecutionEngineConditions conditions = new ExecutionEngineConditions(); ExecutionEngineConditions conditions = new ExecutionEngineConditions();
bool getValue = conditions.IsScriptExecutionTracked; bool getValue = conditions.IsScriptExecutionTracked;
conditions.IsScriptExecutionTracked = !getValue; conditions.IsScriptExecutionTracked = !getValue;
Assert.Equal(conditions.IsScriptExecutionTracked, !getValue); Assert.AreEqual(conditions.IsScriptExecutionTracked, !getValue);
getValue = conditions.IsEstimatedShowPlan; getValue = conditions.IsEstimatedShowPlan;
conditions.IsEstimatedShowPlan = !getValue; conditions.IsEstimatedShowPlan = !getValue;
Assert.Equal(conditions.IsEstimatedShowPlan, !getValue); Assert.AreEqual(conditions.IsEstimatedShowPlan, !getValue);
getValue = conditions.IsActualShowPlan; getValue = conditions.IsActualShowPlan;
conditions.IsActualShowPlan = !getValue; conditions.IsActualShowPlan = !getValue;
Assert.Equal(conditions.IsActualShowPlan, !getValue); Assert.AreEqual(conditions.IsActualShowPlan, !getValue);
getValue = conditions.IsSuppressProviderMessageHeaders; getValue = conditions.IsSuppressProviderMessageHeaders;
conditions.IsSuppressProviderMessageHeaders = !getValue; conditions.IsSuppressProviderMessageHeaders = !getValue;
Assert.Equal(conditions.IsSuppressProviderMessageHeaders, !getValue); Assert.AreEqual(conditions.IsSuppressProviderMessageHeaders, !getValue);
getValue = conditions.IsNoExec; getValue = conditions.IsNoExec;
conditions.IsNoExec = !getValue; conditions.IsNoExec = !getValue;
Assert.Equal(conditions.IsNoExec, !getValue); Assert.AreEqual(conditions.IsNoExec, !getValue);
getValue = conditions.IsStatisticsIO; getValue = conditions.IsStatisticsIO;
conditions.IsStatisticsIO = !getValue; conditions.IsStatisticsIO = !getValue;
Assert.Equal(conditions.IsStatisticsIO, !getValue); Assert.AreEqual(conditions.IsStatisticsIO, !getValue);
getValue = conditions.IsShowPlanText; getValue = conditions.IsShowPlanText;
conditions.IsShowPlanText = !getValue; conditions.IsShowPlanText = !getValue;
Assert.Equal(conditions.IsShowPlanText, !getValue); Assert.AreEqual(conditions.IsShowPlanText, !getValue);
getValue = conditions.IsStatisticsTime; getValue = conditions.IsStatisticsTime;
conditions.IsStatisticsTime = !getValue; conditions.IsStatisticsTime = !getValue;
Assert.Equal(conditions.IsStatisticsTime, !getValue); Assert.AreEqual(conditions.IsStatisticsTime, !getValue);
getValue = conditions.IsSqlCmd; getValue = conditions.IsSqlCmd;
conditions.IsSqlCmd = !getValue; conditions.IsSqlCmd = !getValue;
Assert.Equal(conditions.IsSqlCmd, !getValue); Assert.AreEqual(conditions.IsSqlCmd, !getValue);
conditions.BatchSeparator = "GO"; conditions.BatchSeparator = "GO";
Assert.Equal(conditions.BatchSeparator, "GO"); Assert.AreEqual("GO", conditions.BatchSeparator);
} }
#endregion Get/Set Methods #endregion Get/Set Methods
@@ -9,7 +9,8 @@ using Microsoft.Data.SqlClient;
using System.Threading; using System.Threading;
using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode; using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode;
using Microsoft.SqlTools.Utility; using Microsoft.SqlTools.Utility;
using System.Runtime.CompilerServices;
namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEngine namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEngine
{ {
internal class TestExecutor : IDisposable internal class TestExecutor : IDisposable
@@ -17,9 +18,9 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
#region Private variables #region Private variables
private string sqlStatement; private string sqlStatement;
private ExecutionEngineConditions conditions = new ExecutionEngineConditions(); private readonly ExecutionEngineConditions conditions = new ExecutionEngineConditions();
private BatchEventHandler eventHandler = new BatchEventHandler(); private readonly BatchEventHandler eventHandler = new BatchEventHandler();
private SqlConnection connection = null; private readonly SqlConnection connection;
private static Thread _executionThread; private static Thread _executionThread;
private bool _syncCancel = true; private bool _syncCancel = true;
private bool _isFinished = false; private bool _isFinished = false;
@@ -31,12 +32,12 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
private List<int> resultCounts = new List<int>(); private List<int> resultCounts = new List<int>();
private List<string> sqlMessages = new List<string>(); private List<string> sqlMessages = new List<string>();
private List<string> errorMessage = new List<string>(); private readonly List<string> errorMessage = new List<string>();
private List<bool> batchFinished = new List<bool>(); private List<bool> batchFinished = new List<bool>();
private static ScriptExecutionResult execResult = ScriptExecutionResult.All; private static ScriptExecutionResult execResult = ScriptExecutionResult.All;
private static List<string> batchScripts = new List<string>(); private static List<string> batchScripts = new List<string>();
private static Thread exeThread = null; private static Thread exeThread = null;
private static bool parserExecutionError = false; private bool parserExecutionError = false;
#endregion Private variables #endregion Private variables
@@ -322,10 +323,14 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
private static void OnBatchParserExecutionFinished(object sender, BatchParserExecutionFinishedEventArgs e) private static void OnBatchParserExecutionFinished(object sender, BatchParserExecutionFinishedEventArgs e)
{ {
Console.WriteLine("ON_BATCH_PARSER_EXECUTION_FINISHED : Done executing batch \n\t{0}\n\t with result... {1} ", e.Batch.Text, e.ExecutionResult); Console.WriteLine("ON_BATCH_PARSER_EXECUTION_FINISHED : Done executing batch \n\t{0}\n\t with result... {1} ", e.Batch.Text, e.ExecutionResult);
if (execResult == ScriptExecutionResult.All) if (execResult == ScriptExecutionResult.All)
execResult = e.ExecutionResult; {
else execResult = e.ExecutionResult;
execResult = execResult | e.ExecutionResult; }
else
{
execResult |= e.ExecutionResult;
}
} }
/// <summary> /// <summary>
@@ -333,11 +338,12 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private static void OnBatchParserExecutionError(object sender, BatchParserExecutionErrorEventArgs e) private void OnBatchParserExecutionError(object sender, BatchParserExecutionErrorEventArgs e)
{ {
Console.WriteLine("ON_BATCH_PARSER_EXECUTION_ERROR : {0} found... at line {1}: {2}", e.MessageType.ToString(), e.Line.ToString(), e.Message); Console.WriteLine("ON_BATCH_PARSER_EXECUTION_ERROR : {0} found... at line {1}: {2}", e.MessageType.ToString(), e.Line.ToString(), e.Message);
Console.WriteLine("\t Error Description: " + e.Description); Console.WriteLine("\t Error Description: " + e.Description);
parserExecutionError = true; parserExecutionError = true;
errorMessage.Add(e.Description);
} }
/// <summary> /// <summary>
@@ -350,14 +356,18 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Console.WriteLine("ON_EXECUTION_FINISHED : Script execution done with result ..." + e.ExecutionResult); Console.WriteLine("ON_EXECUTION_FINISHED : Script execution done with result ..." + e.ExecutionResult);
_isFinished = true; _isFinished = true;
if (execResult == ScriptExecutionResult.All) if (execResult == ScriptExecutionResult.All)
execResult = e.ExecutionResult; {
else execResult = e.ExecutionResult;
execResult = execResult | e.ExecutionResult; }
else
{
execResult |= e.ExecutionResult;
}
resultCounts = eventHandler.ResultCounts; resultCounts = eventHandler.ResultCounts;
sqlMessages = eventHandler.SqlMessages; sqlMessages = eventHandler.SqlMessages;
errorMessage = eventHandler.ErrorMessages; errorMessage.AddRange(eventHandler.ErrorMessages);
} }
#endregion ParserEvent #endregion ParserEvent
@@ -8,7 +8,7 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.Utility namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.Utility
{ {
@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit; using NUnit.Framework;
using Moq; using Moq;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Admin.Contracts; using Microsoft.SqlTools.ServiceLayer.Admin.Contracts;
@@ -44,8 +44,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.AdminServices
/// <summary> /// <summary>
/// Validate creating a database with valid input /// Validate creating a database with valid input
/// </summary> /// </summary>
// [Fact] // [Test]
public async void CreateDatabaseWithValidInputTest() public async Task CreateDatabaseWithValidInputTest()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<CreateDatabaseResponse>>(); var requestContext = new Mock<RequestContext<CreateDatabaseResponse>>();
@@ -68,8 +68,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.AdminServices
/// <summary> /// <summary>
/// Get a default database info object /// Get a default database info object
/// </summary> /// </summary>
// [Fact] // [Test]
public async void GetDefaultDatebaseInfoTest() public async Task GetDefaultDatebaseInfoTest()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<DefaultDatabaseInfoResponse>>(); var requestContext = new Mock<RequestContext<DefaultDatabaseInfoResponse>>();
@@ -89,8 +89,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.AdminServices
/// Get database info test /// Get database info test
/// </summary> /// </summary>
/// Test is failing in code coverage runs. Reenable when stable. /// Test is failing in code coverage runs. Reenable when stable.
/// [Fact] /// [Test]
public async void GetDatabaseInfoTest() public async Task GetDatabaseInfoTest()
{ {
var results = GetLiveAutoCompleteTestObjects(); var results = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<GetDatabaseInfoResponse>>(); var requestContext = new Mock<RequestContext<GetDatabaseInfoResponse>>();
@@ -11,7 +11,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility; using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{ {
@@ -20,7 +20,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Verify default agent/alerts handlers /// Verify default agent/alerts handlers
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleAgentAlertsRequest() public async Task TestHandleAgentAlertsRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -42,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Verify the default "create agent alert" request handler with valid parameters /// Verify the default "create agent alert" request handler with valid parameters
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleCreateAgentAlertsRequest() public async Task TestHandleCreateAgentAlertsRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -86,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Verify the default "update agent alert" request handler with valid parameters /// Verify the default "update agent alert" request handler with valid parameters
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleUpdateAgentAlertsRequest() public async Task TestHandleUpdateAgentAlertsRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility; using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{ {
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleCreateAgentJobStepRequest /// TestHandleCreateAgentJobStepRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleCreateAgentJobStepRequest() public async Task TestHandleCreateAgentJobStepRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleUpdateAgentJobStepRequest /// TestHandleUpdateAgentJobStepRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleUpdateAgentJobStepRequest() public async Task TestHandleUpdateAgentJobStepRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -71,7 +71,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleDeleteAgentJobRequest /// TestHandleDeleteAgentJobRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleDeleteAgentJobStepRequest() public async Task TestHandleDeleteAgentJobStepRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility; using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{ {
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleCreateAgentJobRequest /// TestHandleCreateAgentJobRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleCreateAgentJobRequest() public async Task TestHandleCreateAgentJobRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -43,7 +43,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleUpdateAgentJobRequest /// TestHandleUpdateAgentJobRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleUpdateAgentJobRequest() public async Task TestHandleUpdateAgentJobRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -66,7 +66,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleDeleteAgentJobRequest /// TestHandleDeleteAgentJobRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleDeleteAgentJobRequest() public async Task TestHandleDeleteAgentJobRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -86,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestAgentJobDefaultsRequest /// TestAgentJobDefaultsRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestAgentJobDefaultsRequest() public async Task TestAgentJobDefaultsRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -8,7 +8,7 @@ using Microsoft.SqlTools.ServiceLayer.Utility;
using Microsoft.SqlTools.ServiceLayer.Management; using Microsoft.SqlTools.ServiceLayer.Management;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility; using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{ {
@@ -17,7 +17,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Test case for fetch notebook jobs Request Handler /// Test case for fetch notebook jobs Request Handler
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleAgentNotebooksRequest() public async Task TestHandleAgentNotebooksRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -40,16 +40,16 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Tests the create job helper function /// Tests the create job helper function
/// </summary> /// </summary>
[Fact] [Test]
internal async Task TestAgentNotebookCreateHelper() public async Task TestAgentNotebookCreateHelper()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath); var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);
AgentNotebookInfo notebook = AgentTestUtils.GetTestNotebookInfo("myTestNotebookJob" + Guid.NewGuid().ToString(), "master"); AgentNotebookInfo notebook = AgentTestUtils.GetTestNotebookInfo("myTestNotebookJob" + Guid.NewGuid().ToString(), "master");
Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result; notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook); await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook);
} }
} }
@@ -57,8 +57,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Tests the create job request handler with an invalid file path /// Tests the create job request handler with an invalid file path
/// </summary> /// </summary>
[Fact] [Test]
internal async Task TestHandleCreateAgentNotebookRequestWithInvalidTemplatePath() public async Task TestHandleCreateAgentNotebookRequestWithInvalidTemplatePath()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -75,15 +75,15 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
}, createNotebookContext.Object); }, createNotebookContext.Object);
createNotebookContext.Verify(x => x.SendResult(It.Is<CreateAgentNotebookResult>(p => p.Success == false))); createNotebookContext.Verify(x => x.SendResult(It.Is<CreateAgentNotebookResult>(p => p.Success == false)));
Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
} }
} }
/// <summary> /// <summary>
/// creating a job with duplicate name /// creating a job with duplicate name
/// </summary> /// </summary>
[Fact] [Test]
internal async Task TestDuplicateJobCreation() public async Task TestDuplicateJobCreation()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -114,8 +114,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Tests the create notebook job handler /// Tests the create notebook job handler
/// </summary> /// </summary>
[Fact] [Test]
internal async Task TestCreateAgentNotebookHandler() public async Task TestCreateAgentNotebookHandler()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -131,7 +131,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
TemplateFilePath = AgentTestUtils.CreateTemplateNotebookFile() TemplateFilePath = AgentTestUtils.CreateTemplateNotebookFile()
}, createNotebookContext.Object); }, createNotebookContext.Object);
createNotebookContext.Verify(x => x.SendResult(It.Is<CreateAgentNotebookResult>(p => p.Success == true))); createNotebookContext.Verify(x => x.SendResult(It.Is<CreateAgentNotebookResult>(p => p.Success == true)));
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
var createdNotebook = AgentTestUtils.GetNotebook(connectionResult, notebook.Name); var createdNotebook = AgentTestUtils.GetNotebook(connectionResult, notebook.Name);
await AgentTestUtils.CleanupNotebookJob(connectionResult, createdNotebook); await AgentTestUtils.CleanupNotebookJob(connectionResult, createdNotebook);
} }
@@ -140,8 +140,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Tests the delete notebook job handler /// Tests the delete notebook job handler
/// </summary> /// </summary>
[Fact] [Test]
internal async Task TestDeleteAgentNotebookHandler() public async Task TestDeleteAgentNotebookHandler()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -150,7 +150,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
//creating a notebook job //creating a notebook job
AgentNotebookInfo notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result; AgentNotebookInfo notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
//verifying it's getting created //verifying it's getting created
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
//deleting the notebook job //deleting the notebook job
var deleteNotebookContext = new Mock<RequestContext<ResultStatus>>(); var deleteNotebookContext = new Mock<RequestContext<ResultStatus>>();
deleteNotebookContext.Setup(x => x.SendResult(It.IsAny<ResultStatus>())).Returns(Task.FromResult(new object())); deleteNotebookContext.Setup(x => x.SendResult(It.IsAny<ResultStatus>())).Returns(Task.FromResult(new object()));
@@ -161,15 +161,15 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
}, deleteNotebookContext.Object); }, deleteNotebookContext.Object);
deleteNotebookContext.Verify(x => x.SendResult(It.Is<ResultStatus>(p => p.Success == true))); deleteNotebookContext.Verify(x => x.SendResult(It.Is<ResultStatus>(p => p.Success == true)));
//verifying if the job is deleted //verifying if the job is deleted
Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
} }
} }
/// <summary> /// <summary>
/// deleting a existing notebook job /// deleting a existing notebook job
/// </summary> /// </summary>
[Fact] [Test]
internal async Task TestDeleteNonExistentJob() public async Task TestDeleteNonExistentJob()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -193,8 +193,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// updating a non existing notebook job /// updating a non existing notebook job
/// </summary> /// </summary>
[Fact] [Test]
internal async Task TestUpdateNonExistentJob() public async Task TestUpdateNonExistentJob()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -219,8 +219,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// update notebook handler with garbage path /// update notebook handler with garbage path
/// </summary> /// </summary>
[Fact] [Test]
internal async Task TestUpdateWithGarbagePath() public async Task TestUpdateWithGarbagePath()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -230,7 +230,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
//seting up a temp notebook job //seting up a temp notebook job
var notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result; var notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
//verifying that the notebook is created //verifying that the notebook is created
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
var updateNotebookContext = new Mock<RequestContext<UpdateAgentNotebookResult>>(); var updateNotebookContext = new Mock<RequestContext<UpdateAgentNotebookResult>>();
updateNotebookContext.Setup(x => x.SendResult(It.IsAny<UpdateAgentNotebookResult>())).Returns(Task.FromResult(new object())); updateNotebookContext.Setup(x => x.SendResult(It.IsAny<UpdateAgentNotebookResult>())).Returns(Task.FromResult(new object()));
@@ -246,12 +246,12 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
//cleaning up the job //cleaning up the job
await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook); await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook);
Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
} }
} }
[Fact] [Test]
internal async Task TestDeletingUpdatedJob() public async Task TestDeletingUpdatedJob()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -261,13 +261,13 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
//seting up a temp notebook job //seting up a temp notebook job
var notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result; var notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
//verifying that the notebook is created //verifying that the notebook is created
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
var originalName = notebook.Name; var originalName = notebook.Name;
//Changing the notebookName //Changing the notebookName
notebook.Name = "myTestNotebookJob" + Guid.NewGuid().ToString(); notebook.Name = "myTestNotebookJob" + Guid.NewGuid().ToString();
Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
await AgentNotebookHelper.UpdateNotebook( await AgentNotebookHelper.UpdateNotebook(
service, service,
@@ -278,7 +278,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
ManagementUtils.asRunType(0) ManagementUtils.asRunType(0)
); );
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
//cleaning up the job //cleaning up the job
await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook); await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook);
@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.Agent.Contracts;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility; using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{ {
@@ -19,7 +19,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Verify default agent/operators handlers /// Verify default agent/operators handlers
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleAgentOperatorsRequest() public async Task TestHandleAgentOperatorsRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -41,7 +41,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Verify the default "create agent alert" request handler with valid parameters /// Verify the default "create agent alert" request handler with valid parameters
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleCreateAgentOperatorRequest() public async Task TestHandleCreateAgentOperatorRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -63,7 +63,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleUpdateAgentOperatorRequest /// TestHandleUpdateAgentOperatorRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleUpdateAgentOperatorRequest() public async Task TestHandleUpdateAgentOperatorRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -87,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleDeleteAgentOperatorRequest /// TestHandleDeleteAgentOperatorRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleDeleteAgentOperatorRequest() public async Task TestHandleDeleteAgentOperatorRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -14,7 +14,7 @@ using Microsoft.SqlTools.ServiceLayer.Security.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility; using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper; using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
@@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Verify default agent/proxies handlers /// Verify default agent/proxies handlers
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleAgentProxiesRequest() public async Task TestHandleAgentProxiesRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleCreateAgentProxyRequest /// TestHandleCreateAgentProxyRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleCreateAgentProxyRequest() public async Task TestHandleCreateAgentProxyRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Verify the default "update agent alert" request handler with valid parameters /// Verify the default "update agent alert" request handler with valid parameters
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleUpdateAgentProxyRequest() public async Task TestHandleUpdateAgentProxyRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -96,7 +96,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleDeleteAgentProxyRequest /// TestHandleDeleteAgentProxyRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleDeleteAgentProxyRequest() public async Task TestHandleDeleteAgentProxyRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -11,7 +11,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility; using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper; using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// HandleAgentSchedulesRequest /// HandleAgentSchedulesRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task HandleAgentSchedulesRequest() public async Task HandleAgentSchedulesRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleCreateAgentScheduleRequest /// TestHandleCreateAgentScheduleRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleCreateAgentScheduleRequest() public async Task TestHandleCreateAgentScheduleRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleUpdateAgentScheduleRequest /// TestHandleUpdateAgentScheduleRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleUpdateAgentScheduleRequest() public async Task TestHandleUpdateAgentScheduleRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -95,7 +95,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// TestHandleDeleteAgentScheduleRequest /// TestHandleDeleteAgentScheduleRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleDeleteAgentScheduleRequest() public async Task TestHandleDeleteAgentScheduleRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility; using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{ {
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Verify that a start profiling request starts a profiling session /// Verify that a start profiling request starts a profiling session
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleAgentJobsRequest() public async Task TestHandleAgentJobsRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -44,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary> /// <summary>
/// Verify that a job history request returns the job history /// Verify that a job history request returns the job history
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleJobHistoryRequests() public async Task TestHandleJobHistoryRequests()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -65,7 +65,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
} }
} }
[Fact] [Test]
public async Task TestHandleAgentJobActionRequest() public async Task TestHandleAgentJobActionRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -3,6 +3,6 @@
// 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 Xunit; using NUnit.Framework;
[assembly: CollectionBehavior(DisableTestParallelization = true)] [assembly: NonParallelizable]
@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq; using Moq;
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
{ {
@@ -37,8 +37,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
return connectParams; return connectParams;
} }
[Fact] [Test]
private async void TestAddCMS() public async Task TestAddCMS()
{ {
string name = "TestAddCMS" + DateTime.Now.ToString(); string name = "TestAddCMS" + DateTime.Now.ToString();
ConnectParams connectParams = CreateConnectParams(); ConnectParams connectParams = CreateConnectParams();
@@ -63,8 +63,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
requestContext.VerifyAll(); requestContext.VerifyAll();
} }
[Fact] [Test]
private async void TestAddRemoveRegisteredServer() public async Task TestAddRemoveRegisteredServer()
{ {
string name = "TestAddRemoveRegisteredServer" + DateTime.Now.ToString(); string name = "TestAddRemoveRegisteredServer" + DateTime.Now.ToString();
ConnectParams connectParams = await CreateAndConnectWithConnectParams(); ConnectParams connectParams = await CreateAndConnectWithConnectParams();
@@ -122,8 +122,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
requestContext3.VerifyAll(); requestContext3.VerifyAll();
} }
[Fact] [Test]
private async void TestAddRemoveServerGroup() public async Task TestAddRemoveServerGroup()
{ {
string name = "TestAddRemoveServerGroup" + DateTime.Now.ToString(); string name = "TestAddRemoveServerGroup" + DateTime.Now.ToString();
ConnectParams connectParams = await CreateAndConnectWithConnectParams(); ConnectParams connectParams = await CreateAndConnectWithConnectParams();
@@ -174,8 +174,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
requestContext3.VerifyAll(); requestContext3.VerifyAll();
} }
[Fact] [Test]
private async void TestAddRemoveNestedGroup() public async Task TestAddRemoveNestedGroup()
{ {
string name = "TestAddRemoveNestedGroup" + DateTime.Now.ToString(); string name = "TestAddRemoveNestedGroup" + DateTime.Now.ToString();
ConnectParams connectParams = await CreateAndConnectWithConnectParams(); ConnectParams connectParams = await CreateAndConnectWithConnectParams();
@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.SqlContext; using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
{ {
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// </summary> /// </summary>
public class ConnectionServiceTests public class ConnectionServiceTests
{ {
[Fact] [Test]
public void RunningMultipleQueriesCreatesOnlyOneConnection() public void RunningMultipleQueriesCreatesOnlyOneConnection()
{ {
// Connect/disconnect twice to ensure reconnection can occur // Connect/disconnect twice to ensure reconnection can occur
@@ -34,8 +34,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
string uri = connectionInfo.OwnerUri; string uri = connectionInfo.OwnerUri;
// We should see one ConnectionInfo and one DbConnection // We should see one ConnectionInfo and one DbConnection
Assert.Equal(1, connectionInfo.CountConnections); Assert.AreEqual(1, connectionInfo.CountConnections);
Assert.Equal(1, service.OwnerToConnectionMap.Count); Assert.AreEqual(1, service.OwnerToConnectionMap.Count);
// If we run a query // If we run a query
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -44,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
query.ExecutionTask.Wait(); query.ExecutionTask.Wait();
// We should see two DbConnections // We should see two DbConnections
Assert.Equal(2, connectionInfo.CountConnections); Assert.AreEqual(2, connectionInfo.CountConnections);
// If we run another query // If we run another query
query = new Query(Constants.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory); query = new Query(Constants.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory);
@@ -52,18 +52,18 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
query.ExecutionTask.Wait(); query.ExecutionTask.Wait();
// We should still have 2 DbConnections // We should still have 2 DbConnections
Assert.Equal(2, connectionInfo.CountConnections); Assert.AreEqual(2, connectionInfo.CountConnections);
// If we disconnect, we should remain in a consistent state to do it over again // If we disconnect, we should remain in a consistent state to do it over again
// e.g. loop and do it over again // e.g. loop and do it over again
service.Disconnect(new DisconnectParams() { OwnerUri = connectionInfo.OwnerUri }); service.Disconnect(new DisconnectParams() { OwnerUri = connectionInfo.OwnerUri });
// We should be left with an empty connection map // We should be left with an empty connection map
Assert.Equal(0, service.OwnerToConnectionMap.Count); Assert.AreEqual(0, service.OwnerToConnectionMap.Count);
} }
} }
[Fact] [Test]
public void DatabaseChangesAffectAllConnections() public void DatabaseChangesAffectAllConnections()
{ {
// If we make a connection to a live database // If we make a connection to a live database
@@ -87,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
{ {
if (connection != null && connection.State == ConnectionState.Open) if (connection != null && connection.State == ConnectionState.Open)
{ {
Assert.Equal(connection.Database, initialDatabaseName); Assert.AreEqual(connection.Database, initialDatabaseName);
} }
} }
@@ -101,7 +101,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
{ {
if (connection != null && connection.State == ConnectionState.Open) if (connection != null && connection.State == ConnectionState.Open)
{ {
Assert.Equal(connection.Database, newDatabaseName); Assert.AreEqual(connection.Database, newDatabaseName);
} }
} }
} }
@@ -109,8 +109,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Test HandleGetConnectionStringRequest /// Test HandleGetConnectionStringRequest
/// </summary> /// </summary>
[Fact] [Test]
public async void GetCurrentConnectionStringTest() public async Task GetCurrentConnectionStringTest()
{ {
// If we make a connection to a live database // If we make a connection to a live database
ConnectionService service = ConnectionService.Instance; ConnectionService service = ConnectionService.Instance;
@@ -14,7 +14,7 @@ using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection; using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility; using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.RetryPolicy; using static Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.RetryPolicy;
using static Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.RetryPolicy.TimeBasedRetryPolicy; using static Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.RetryPolicy.TimeBasedRetryPolicy;
using static Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.SqlSchemaModelErrorCodes; using static Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.SqlSchemaModelErrorCodes;
@@ -122,7 +122,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
} }
} }
[Fact] [Test]
public void FixedDelayPolicyTest() public void FixedDelayPolicyTest()
{ {
TestFixedDelayPolicy policy = new TestFixedDelayPolicy( TestFixedDelayPolicy policy = new TestFixedDelayPolicy(
@@ -135,7 +135,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(shouldRety); Assert.True(shouldRety);
} }
[Fact] [Test]
public void FixedDelayPolicyExecuteActionTest() public void FixedDelayPolicyExecuteActionTest()
{ {
TestFixedDelayPolicy policy = new TestFixedDelayPolicy( TestFixedDelayPolicy policy = new TestFixedDelayPolicy(
@@ -145,7 +145,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
// execute an action that throws a retry limit exception // execute an action that throws a retry limit exception
CancellationToken token = new CancellationToken(); CancellationToken token = new CancellationToken();
Assert.Equal(policy.ExecuteAction<int>((s) => { throw new RetryLimitExceededException(); }, token), default(int)); Assert.AreEqual(default(int), policy.ExecuteAction<int>((s) => { throw new RetryLimitExceededException(); }, token));
// execute an action that throws a retry limit exeception with an inner exception // execute an action that throws a retry limit exeception with an inner exception
Assert.Throws<Exception>(() => Assert.Throws<Exception>(() =>
@@ -158,7 +158,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
}); });
} }
[Fact] [Test]
public void IsRetryableExceptionTest() public void IsRetryableExceptionTest()
{ {
TestFixedDelayPolicy policy = new TestFixedDelayPolicy( TestFixedDelayPolicy policy = new TestFixedDelayPolicy(
@@ -169,7 +169,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.False(policy.IsRetryableException(new Exception())); Assert.False(policy.IsRetryableException(new Exception()));
} }
[Fact] [Test]
public void ProgressiveRetryPolicyTest() public void ProgressiveRetryPolicyTest()
{ {
TestProgressiveRetryPolicy policy = new TestProgressiveRetryPolicy( TestProgressiveRetryPolicy policy = new TestProgressiveRetryPolicy(
@@ -184,7 +184,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.False(policy.ShouldIgnoreOnFirstTry); Assert.False(policy.ShouldIgnoreOnFirstTry);
} }
[Fact] [Test]
public void TimeBasedRetryPolicyTest() public void TimeBasedRetryPolicyTest()
{ {
TestTimeBasedRetryPolicy policy = new TestTimeBasedRetryPolicy( TestTimeBasedRetryPolicy policy = new TestTimeBasedRetryPolicy(
@@ -200,7 +200,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
} }
[Fact] [Test]
public void GetErrorNumberWithNullExceptionTest() public void GetErrorNumberWithNullExceptionTest()
{ {
Assert.Null(RetryPolicy.GetErrorNumber(null)); Assert.Null(RetryPolicy.GetErrorNumber(null));
@@ -265,7 +265,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Test ReliableConnectionHelper.GetDefaultDatabaseFilePath() /// Test ReliableConnectionHelper.GetDefaultDatabaseFilePath()
/// </summary> /// </summary>
[Fact] [Test]
public void TestGetDefaultDatabaseFilePath() public void TestGetDefaultDatabaseFilePath()
{ {
@@ -293,7 +293,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Test ReliableConnectionHelper.GetServerVersion() /// Test ReliableConnectionHelper.GetServerVersion()
/// </summary> /// </summary>
[Fact] [Test]
public void TestGetServerVersion() public void TestGetServerVersion()
{ {
using (var connection = CreateTestConnection()) using (var connection = CreateTestConnection())
@@ -324,7 +324,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Tests ReliableConnectionHelper.GetCompleteServerName() /// Tests ReliableConnectionHelper.GetCompleteServerName()
/// </summary> /// </summary>
[Fact] [Test]
public void TestGetCompleteServerName() public void TestGetCompleteServerName()
{ {
string name = ReliableConnectionHelper.GetCompleteServerName(@".\SQL2008"); string name = ReliableConnectionHelper.GetCompleteServerName(@".\SQL2008");
@@ -337,7 +337,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Tests ReliableConnectionHelper.IsDatabaseReadonly() /// Tests ReliableConnectionHelper.IsDatabaseReadonly()
/// </summary> /// </summary>
[Fact] [Test]
public void TestIsDatabaseReadonly() public void TestIsDatabaseReadonly()
{ {
var connectionBuilder = CreateTestConnectionStringBuilder(); var connectionBuilder = CreateTestConnectionStringBuilder();
@@ -350,7 +350,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// /// Tests ReliableConnectionHelper.IsDatabaseReadonly() with null builder parameter /// /// Tests ReliableConnectionHelper.IsDatabaseReadonly() with null builder parameter
/// </summary> /// </summary>
[Fact] [Test]
public void TestIsDatabaseReadonlyWithNullBuilder() public void TestIsDatabaseReadonlyWithNullBuilder()
{ {
Assert.Throws<ArgumentNullException>(() => ReliableConnectionHelper.IsDatabaseReadonly(null, null)); Assert.Throws<ArgumentNullException>(() => ReliableConnectionHelper.IsDatabaseReadonly(null, null));
@@ -359,7 +359,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Verify ANSI_NULL and QUOTED_IDENTIFIER settings can be set and retrieved for a session /// Verify ANSI_NULL and QUOTED_IDENTIFIER settings can be set and retrieved for a session
/// </summary> /// </summary>
[Fact] [Test]
public void VerifyAnsiNullAndQuotedIdentifierSettingsReplayed() public void VerifyAnsiNullAndQuotedIdentifierSettingsReplayed()
{ {
using (ReliableSqlConnection conn = (ReliableSqlConnection) ReliableConnectionHelper.OpenConnection(CreateTestConnectionStringBuilder(), useRetry: true, azureAccountToken: null)) using (ReliableSqlConnection conn = (ReliableSqlConnection) ReliableConnectionHelper.OpenConnection(CreateTestConnectionStringBuilder(), useRetry: true, azureAccountToken: null))
@@ -395,11 +395,11 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
AssertSessionValues(cmd, ansiNullsValue: expectedSessionValue, quotedIdentifersValue: expectedSessionValue); AssertSessionValues(cmd, ansiNullsValue: expectedSessionValue, quotedIdentifersValue: expectedSessionValue);
// assert cached settings are correct // assert cached settings are correct
Assert.Equal("ANSI_NULLS", settings[0].Item1); Assert.AreEqual("ANSI_NULLS", settings[0].Item1);
Assert.Equal(expectedSessionValue, settings[0].Item2); Assert.AreEqual(expectedSessionValue, settings[0].Item2);
Assert.Equal("QUOTED_IDENTIFIER", settings[1].Item1); Assert.AreEqual("QUOTED_IDENTIFIER", settings[1].Item1);
Assert.Equal(expectedSessionValue, settings[1].Item2); Assert.AreEqual(expectedSessionValue, settings[1].Item2);
// invert session values and assert we reset them // invert session values and assert we reset them
@@ -433,8 +433,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(reader.Read(), "Missing session settings"); Assert.True(reader.Read(), "Missing session settings");
bool actualAnsiNullsOnValue = ((int)reader[0] == 1); bool actualAnsiNullsOnValue = ((int)reader[0] == 1);
bool actualQuotedIdentifierOnValue = ((int)reader[1] == 1); bool actualQuotedIdentifierOnValue = ((int)reader[1] == 1);
Assert.Equal(ansiNullsValue, actualAnsiNullsOnValue); Assert.AreEqual(ansiNullsValue, actualAnsiNullsOnValue);
Assert.Equal(quotedIdentifersValue, actualQuotedIdentifierOnValue); Assert.AreEqual(quotedIdentifersValue, actualQuotedIdentifierOnValue);
} }
} }
@@ -442,7 +442,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Test that the retry policy factory constructs all possible types of policies successfully. /// Test that the retry policy factory constructs all possible types of policies successfully.
/// </summary> /// </summary>
[Fact] [Test]
public void RetryPolicyFactoryConstructsPoliciesSuccessfully() public void RetryPolicyFactoryConstructsPoliciesSuccessfully()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -468,7 +468,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// ReliableConnectionHelper.IsCloud() should be false for a local server /// ReliableConnectionHelper.IsCloud() should be false for a local server
/// </summary> /// </summary>
[Fact] [Test]
public void TestIsCloudIsFalseForLocalServer() public void TestIsCloudIsFalseForLocalServer()
{ {
using (var connection = CreateTestConnection()) using (var connection = CreateTestConnection())
@@ -483,7 +483,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Tests that ReliableConnectionHelper.OpenConnection() opens a connection if it is closed /// Tests that ReliableConnectionHelper.OpenConnection() opens a connection if it is closed
/// </summary> /// </summary>
[Fact] [Test]
public void TestOpenConnectionOpensConnection() public void TestOpenConnectionOpensConnection()
{ {
using (var connection = CreateTestConnection()) using (var connection = CreateTestConnection())
@@ -499,7 +499,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Tests that ReliableConnectionHelper.ExecuteNonQuery() runs successfully /// Tests that ReliableConnectionHelper.ExecuteNonQuery() runs successfully
/// </summary> /// </summary>
[Fact] [Test]
public void TestExecuteNonQuery() public void TestExecuteNonQuery()
{ {
var result = ReliableConnectionHelper.ExecuteNonQuery( var result = ReliableConnectionHelper.ExecuteNonQuery(
@@ -516,7 +516,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Test that TryGetServerVersion() gets server information /// Test that TryGetServerVersion() gets server information
/// </summary> /// </summary>
[Fact] [Test]
public void TestTryGetServerVersion() public void TestTryGetServerVersion()
{ {
ReliableConnectionHelper.ServerInfo info = null; ReliableConnectionHelper.ServerInfo info = null;
@@ -524,14 +524,13 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(ReliableConnectionHelper.TryGetServerVersion(connBuilder.ConnectionString, out info, null)); Assert.True(ReliableConnectionHelper.TryGetServerVersion(connBuilder.ConnectionString, out info, null));
Assert.NotNull(info); Assert.NotNull(info);
Assert.NotNull(info.ServerVersion); Assert.That(info.ServerVersion, Is.Not.Null.Or.Empty);
Assert.NotEmpty(info.ServerVersion);
} }
/// <summary> /// <summary>
/// Test that TryGetServerVersion() fails with invalid connection string /// Test that TryGetServerVersion() fails with invalid connection string
/// </summary> /// </summary>
[Fact] [Test]
public void TestTryGetServerVersionInvalidConnectionString() public void TestTryGetServerVersionInvalidConnectionString()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -544,7 +543,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Validate ambient static settings /// Validate ambient static settings
/// </summary> /// </summary>
[Fact] [Test]
public void AmbientSettingsStaticPropertiesTest() public void AmbientSettingsStaticPropertiesTest()
{ {
var defaultSettings = AmbientSettings.DefaultSettings; var defaultSettings = AmbientSettings.DefaultSettings;
@@ -578,7 +577,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary> /// <summary>
/// Validate ambient settings populate /// Validate ambient settings populate
/// </summary> /// </summary>
[Fact] [Test]
public void AmbientSettingsPopulateTest() public void AmbientSettingsPopulateTest()
{ {
var data = new AmbientSettings.AmbientData(); var data = new AmbientSettings.AmbientData();
@@ -626,7 +625,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
data.TraceSettings(); data.TraceSettings();
} }
[Fact] [Test]
public void RaiseAmbientRetryMessageTest() public void RaiseAmbientRetryMessageTest()
{ {
bool handlerCalled = false; bool handlerCalled = false;
@@ -637,7 +636,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(handlerCalled); Assert.True(handlerCalled);
} }
[Fact] [Test]
public void RaiseAmbientIgnoreMessageTest() public void RaiseAmbientIgnoreMessageTest()
{ {
bool handlerCalled = false; bool handlerCalled = false;
@@ -648,7 +647,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(handlerCalled); Assert.True(handlerCalled);
} }
[Fact] [Test]
public void RetryPolicyFactoryTest() public void RetryPolicyFactoryTest()
{ {
Assert.NotNull(RetryPolicyFactory.NoRetryPolicy); Assert.NotNull(RetryPolicyFactory.NoRetryPolicy);
@@ -673,7 +672,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.False(transientPolicy.ShouldIgnoreError(new Exception())); Assert.False(transientPolicy.ShouldIgnoreError(new Exception()));
} }
[Fact] [Test]
public void ReliableConnectionHelperTest() public void ReliableConnectionHelperTest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -700,7 +699,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
} }
} }
[Fact] [Test]
public void DataSchemaErrorTests() public void DataSchemaErrorTests()
{ {
var error = new DataSchemaError(); var error = new DataSchemaError();
@@ -722,7 +721,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(DataSchemaError.FormatErrorCode("ex", 1)); Assert.NotNull(DataSchemaError.FormatErrorCode("ex", 1));
} }
[Fact] [Test]
public void InitReliableSqlConnectionTest() public void InitReliableSqlConnectionTest()
{ {
var result = LiveConnectionHelper.InitLiveConnectionInfo(); var result = LiveConnectionHelper.InitLiveConnectionInfo();
@@ -743,7 +742,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
connection.ClearPool(); connection.ClearPool();
} }
[Fact] [Test]
public void ThrottlingReasonTests() public void ThrottlingReasonTests()
{ {
var reason = RetryPolicy.ThrottlingReason.Unknown; var reason = RetryPolicy.ThrottlingReason.Unknown;
@@ -794,7 +793,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(codeReason.ToString()); Assert.NotNull(codeReason.ToString());
} }
[Fact] [Test]
public void RetryErrorsTest() public void RetryErrorsTest()
{ {
var sqlServerRetryError = new SqlServerRetryError( var sqlServerRetryError = new SqlServerRetryError(
@@ -817,7 +816,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(SqlSchemaModelErrorCodes.IsStatementFilterError(StatementFilter.StatementFilterBaseCode + 1)); Assert.True(SqlSchemaModelErrorCodes.IsStatementFilterError(StatementFilter.StatementFilterBaseCode + 1));
} }
[Fact] [Test]
public void RetryCallbackEventArgsTest() public void RetryCallbackEventArgsTest()
{ {
var exception = new Exception(); var exception = new Exception();
@@ -828,38 +827,38 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
// If I check the properties on the object // If I check the properties on the object
// Then I expect the values to be the same as the values I passed into the constructor // Then I expect the values to be the same as the values I passed into the constructor
Assert.Equal(5, args.RetryCount); Assert.AreEqual(5, args.RetryCount);
Assert.Equal(exception, args.Exception); Assert.AreEqual(exception, args.Exception);
Assert.Equal(timespan, args.Delay); Assert.AreEqual(timespan, args.Delay);
} }
[Fact] [Test]
public void CheckStaticVariables() public void CheckStaticVariables()
{ {
Assert.NotNull(ReliableConnectionHelper.BuilderWithDefaultApplicationName); Assert.NotNull(ReliableConnectionHelper.BuilderWithDefaultApplicationName);
} }
[Fact] [Test]
public void SetLockAndCommandTimeoutThrowsOnNull() public void SetLockAndCommandTimeoutThrowsOnNull()
{ {
Assert.Throws(typeof(ArgumentNullException), () => ReliableConnectionHelper.SetLockAndCommandTimeout(null)); Assert.Throws(typeof(ArgumentNullException), () => ReliableConnectionHelper.SetLockAndCommandTimeout(null));
} }
[Fact] [Test]
public void StandardExceptionHandlerTests() public void StandardExceptionHandlerTests()
{ {
Assert.True(ReliableConnectionHelper.StandardExceptionHandler(new InvalidCastException())); Assert.True(ReliableConnectionHelper.StandardExceptionHandler(new InvalidCastException()));
Assert.False(ReliableConnectionHelper.StandardExceptionHandler(new Exception())); Assert.False(ReliableConnectionHelper.StandardExceptionHandler(new Exception()));
} }
[Fact] [Test]
public void GetConnectionStringBuilderNullConnectionString() public void GetConnectionStringBuilderNullConnectionString()
{ {
SqlConnectionStringBuilder builder; SqlConnectionStringBuilder builder;
Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder(null, out builder)); Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder(null, out builder));
} }
[Fact] [Test]
public void GetConnectionStringBuilderExceptionTests() public void GetConnectionStringBuilderExceptionTests()
{ {
SqlConnectionStringBuilder builder; SqlConnectionStringBuilder builder;
@@ -871,7 +870,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder("rabbits**frogs**lizards", out builder)); Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder("rabbits**frogs**lizards", out builder));
} }
[Fact] [Test]
public void GetCompleteServerNameTests() public void GetCompleteServerNameTests()
{ {
Assert.Null(ReliableConnectionHelper.GetCompleteServerName(null)); Assert.Null(ReliableConnectionHelper.GetCompleteServerName(null));
@@ -881,7 +880,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(ReliableConnectionHelper.GetCompleteServerName("mytestservername")); Assert.NotNull(ReliableConnectionHelper.GetCompleteServerName("mytestservername"));
} }
[Fact] [Test]
public void ReliableSqlCommandConstructorTests() public void ReliableSqlCommandConstructorTests()
{ {
// verify default constructor doesn't throw // verify default constructor doesn't throw
@@ -891,18 +890,18 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(new ReliableSqlConnection.ReliableSqlCommand(null)); Assert.NotNull(new ReliableSqlConnection.ReliableSqlCommand(null));
} }
[Fact] [Test]
public void ReliableSqlCommandProperties() public void ReliableSqlCommandProperties()
{ {
var command = new ReliableSqlConnection.ReliableSqlCommand(); var command = new ReliableSqlConnection.ReliableSqlCommand();
command.CommandText = "SELECT 1"; command.CommandText = "SELECT 1";
Assert.Equal(command.CommandText, "SELECT 1"); Assert.AreEqual("SELECT 1", command.CommandText);
Assert.NotNull(command.CommandTimeout); Assert.NotNull(command.CommandTimeout);
Assert.NotNull(command.CommandType); Assert.NotNull(command.CommandType);
command.DesignTimeVisible = true; command.DesignTimeVisible = true;
Assert.True(command.DesignTimeVisible); Assert.True(command.DesignTimeVisible);
command.UpdatedRowSource = UpdateRowSource.None; command.UpdatedRowSource = UpdateRowSource.None;
Assert.Equal(command.UpdatedRowSource, UpdateRowSource.None); Assert.AreEqual(UpdateRowSource.None, command.UpdatedRowSource);
Assert.NotNull(command.GetUnderlyingCommand()); Assert.NotNull(command.GetUnderlyingCommand());
Assert.Throws<InvalidOperationException>(() => command.ValidateConnectionIsSet()); Assert.Throws<InvalidOperationException>(() => command.ValidateConnectionIsSet());
command.Prepare(); command.Prepare();
@@ -910,7 +909,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
command.Cancel(); command.Cancel();
} }
[Fact] [Test]
public void ReliableConnectionResourcesTests() public void ReliableConnectionResourcesTests()
{ {
Assert.NotNull(Resources.ConnectionPassedToIsCloudShouldBeOpen); Assert.NotNull(Resources.ConnectionPassedToIsCloudShouldBeOpen);
@@ -924,19 +923,19 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(Resources.UnableToRetrieveAzureSessionId); Assert.NotNull(Resources.UnableToRetrieveAzureSessionId);
} }
[Fact] [Test]
public void CalcExponentialRetryDelayWithSchemaDefaultsTest() public void CalcExponentialRetryDelayWithSchemaDefaultsTest()
{ {
Assert.NotNull(RetryPolicyUtils.CalcExponentialRetryDelayWithSchemaDefaults(1)); Assert.NotNull(RetryPolicyUtils.CalcExponentialRetryDelayWithSchemaDefaults(1));
} }
[Fact] [Test]
public void IsSupportedCommandNullCommandTest() public void IsSupportedCommandNullCommandTest()
{ {
Assert.False(DbCommandWrapper.IsSupportedCommand(null)); Assert.False(DbCommandWrapper.IsSupportedCommand(null));
} }
[Fact] [Test]
public void StatementCompletedTests() public void StatementCompletedTests()
{ {
StatementCompletedEventHandler handler = (s, e) => { }; StatementCompletedEventHandler handler = (s, e) => { };
@@ -17,8 +17,8 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.SchemaCompare.Contracts; using Microsoft.SqlTools.ServiceLayer.SchemaCompare.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices; using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using NUnit.Framework;
using Moq; using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DacFx namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DacFx
{ {
@@ -71,8 +71,8 @@ RETURN 0
/// <summary> /// <summary>
/// Verify the export bacpac request /// Verify the export bacpac request
/// </summary> /// </summary>
[Fact] [Test]
public async void ExportBacpac() public async Task ExportBacpac()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest"); SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest");
@@ -102,8 +102,8 @@ RETURN 0
/// <summary> /// <summary>
/// Verify the import bacpac request /// Verify the import bacpac request
/// </summary> /// </summary>
[Fact] [Test]
public async void ImportBacpac() public async Task ImportBacpac()
{ {
// first export a bacpac // first export a bacpac
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
@@ -150,8 +150,8 @@ RETURN 0
/// <summary> /// <summary>
/// Verify the extract dacpac request /// Verify the extract dacpac request
/// </summary> /// </summary>
[Fact] [Test]
public async void ExtractDacpac() public async Task ExtractDacpac()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExtractTest"); SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExtractTest");
@@ -183,8 +183,8 @@ RETURN 0
/// <summary> /// <summary>
/// Verify the extract request to create Sql file /// Verify the extract request to create Sql file
/// </summary> /// </summary>
[Fact] [Test]
public async void ExtractDBToFileTarget() public async Task ExtractDBToFileTarget()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, doNotCleanupDb: false, databaseName: null, query: SourceScript, dbNamePrefix: "DacFxExtractDBToFileTarget"); SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, doNotCleanupDb: false, databaseName: null, query: SourceScript, dbNamePrefix: "DacFxExtractDBToFileTarget");
@@ -217,8 +217,8 @@ RETURN 0
/// <summary> /// <summary>
/// Verify the extract request to create a Flat file structure /// Verify the extract request to create a Flat file structure
/// </summary> /// </summary>
[Fact] [Test]
public async void ExtractDBToFlatTarget() public async Task ExtractDBToFlatTarget()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, doNotCleanupDb: false, databaseName: null, query: SourceScript, dbNamePrefix: "DacFxExtractDBToFlatTarget"); SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, doNotCleanupDb: false, databaseName: null, query: SourceScript, dbNamePrefix: "DacFxExtractDBToFlatTarget");
@@ -243,7 +243,7 @@ RETURN 0
// Verify two sql files are generated in the target folder path // Verify two sql files are generated in the target folder path
// for dev-servers where there are more users/permissions present on server - the extract might have more files than just 2 expected tables, so check only for tables // for dev-servers where there are more users/permissions present on server - the extract might have more files than just 2 expected tables, so check only for tables
int actualCnt = Directory.GetFiles(folderPath, "table*.sql", SearchOption.AllDirectories).Length; int actualCnt = Directory.GetFiles(folderPath, "table*.sql", SearchOption.AllDirectories).Length;
Assert.Equal(2, actualCnt); Assert.AreEqual(2, actualCnt);
} }
finally finally
{ {
@@ -259,8 +259,8 @@ RETURN 0
/// <summary> /// <summary>
/// Verify the deploy dacpac request /// Verify the deploy dacpac request
/// </summary> /// </summary>
[Fact] [Test]
public async void DeployDacpac() public async Task DeployDacpac()
{ {
// first extract a db to have a dacpac to import later // first extract a db to have a dacpac to import later
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
@@ -305,13 +305,14 @@ RETURN 0
targetDb.Cleanup(); targetDb.Cleanup();
} }
} }
return;
} }
/// <summary> /// <summary>
/// Verify the export request being cancelled /// Verify the export request being cancelled
/// </summary> /// </summary>
[Fact] [Test]
public async void ExportBacpacCancellationTest() public async Task ExportBacpacCancellationTest()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest"); SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest");
@@ -353,8 +354,8 @@ RETURN 0
/// <summary> /// <summary>
/// Verify the generate deploy script request /// Verify the generate deploy script request
/// </summary> /// </summary>
[Fact] [Test]
public async void GenerateDeployScript() public async Task GenerateDeployScript()
{ {
// first extract a dacpac // first extract a dacpac
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
@@ -378,8 +379,8 @@ RETURN 0
service.PerformOperation(generateScriptOperation, TaskExecutionMode.Script); service.PerformOperation(generateScriptOperation, TaskExecutionMode.Script);
// Verify script was generated // Verify script was generated
Assert.NotEmpty(generateScriptOperation.Result.DatabaseScript); Assert.That(generateScriptOperation.Result.DatabaseScript, Is.Not.Empty);
Assert.Contains("CREATE TABLE", generateScriptOperation.Result.DatabaseScript); Assert.That(generateScriptOperation.Result.DatabaseScript, Does.Contain("CREATE TABLE"));
VerifyAndCleanup(dacpacPath); VerifyAndCleanup(dacpacPath);
} }
@@ -393,8 +394,8 @@ RETURN 0
/// <summary> /// <summary>
/// Verify the generate deploy plan request /// Verify the generate deploy plan request
/// </summary> /// </summary>
[Fact] [Test]
public async void GenerateDeployPlan() public async Task GenerateDeployPlan()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "DacFxGenerateDeployPlanTest"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "DacFxGenerateDeployPlanTest");
@@ -418,9 +419,12 @@ RETURN 0
service.PerformOperation(generateDeployPlanOperation, TaskExecutionMode.Execute); service.PerformOperation(generateDeployPlanOperation, TaskExecutionMode.Execute);
string report = generateDeployPlanOperation.DeployReport; string report = generateDeployPlanOperation.DeployReport;
Assert.NotNull(report); Assert.NotNull(report);
Assert.Contains("Create", report); Assert.Multiple(() =>
Assert.Contains("Drop", report); {
Assert.Contains("Alter", report); Assert.That(report, Does.Contain("Create"));
Assert.That(report, Does.Contain("Drop"));
Assert.That(report, Does.Contain("Alter"));
});
VerifyAndCleanup(dacpacPath); VerifyAndCleanup(dacpacPath);
} }
@@ -437,8 +441,8 @@ RETURN 0
// <summary> // <summary>
/// Verify that SqlCmdVars are set correctly for a deploy request /// Verify that SqlCmdVars are set correctly for a deploy request
/// </summary> /// </summary>
[Fact] [Test]
public async void DeployWithSqlCmdVariables() public async Task DeployWithSqlCmdVariables()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: storedProcScript, dbNamePrefix: "DacFxDeploySqlCmdVarsTest"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: storedProcScript, dbNamePrefix: "DacFxDeploySqlCmdVarsTest");
@@ -482,8 +486,8 @@ RETURN 0
} }
} }
Assert.Contains(deployParams.SqlCommandVariableValues[databaseRefVarName], deployedProc); Assert.That(deployedProc, Does.Contain(deployParams.SqlCommandVariableValues[databaseRefVarName]));
Assert.Contains(deployParams.SqlCommandVariableValues[filterValueVarName], deployedProc); Assert.That(deployedProc, Does.Contain(deployParams.SqlCommandVariableValues[filterValueVarName]));
VerifyAndCleanup(dacpacPath); VerifyAndCleanup(dacpacPath);
} }
@@ -500,8 +504,8 @@ RETURN 0
// <summary> // <summary>
/// Verify that SqlCmdVars are set correctly for a generate script request /// Verify that SqlCmdVars are set correctly for a generate script request
/// </summary> /// </summary>
[Fact] [Test]
public async void GenerateDeployScriptWithSqlCmdVariables() public async Task GenerateDeployScriptWithSqlCmdVariables()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: storedProcScript, dbNamePrefix: "DacFxGenerateScriptSqlCmdVarsTest"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: storedProcScript, dbNamePrefix: "DacFxGenerateScriptSqlCmdVarsTest");
@@ -528,9 +532,9 @@ RETURN 0
service.PerformOperation(generateScriptOperation, TaskExecutionMode.Script); service.PerformOperation(generateScriptOperation, TaskExecutionMode.Script);
// Verify the SqlCmdVars were set correctly in the script // Verify the SqlCmdVars were set correctly in the script
Assert.NotEmpty(generateScriptOperation.Result.DatabaseScript); Assert.That(generateScriptOperation.Result.DatabaseScript, Is.Not.Empty);
Assert.Contains($":setvar {databaseRefVarName} \"{generateScriptParams.SqlCommandVariableValues[databaseRefVarName]}\"", generateScriptOperation.Result.DatabaseScript); Assert.That(generateScriptOperation.Result.DatabaseScript, Does.Contain($":setvar {databaseRefVarName} \"{generateScriptParams.SqlCommandVariableValues[databaseRefVarName]}\""));
Assert.Contains($":setvar {filterValueVarName} \"{generateScriptParams.SqlCommandVariableValues[filterValueVarName]}\"", generateScriptOperation.Result.DatabaseScript); Assert.That(generateScriptOperation.Result.DatabaseScript, Does.Contain($":setvar {filterValueVarName} \"{generateScriptParams.SqlCommandVariableValues[filterValueVarName]}\""));
VerifyAndCleanup(dacpacPath); VerifyAndCleanup(dacpacPath);
} }
@@ -543,8 +547,8 @@ RETURN 0
/// ///
/// Verify that options are set correctly for a deploy request /// Verify that options are set correctly for a deploy request
/// </summary> /// </summary>
[Fact] [Test]
public async void DeployWithOptions() public async Task DeployWithOptions()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: SourceScript, dbNamePrefix: "DacFxDeployOptionsTestSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: SourceScript, dbNamePrefix: "DacFxDeployOptionsTestSource");
@@ -607,10 +611,10 @@ RETURN 0
{ {
await conn.OpenAsync(); await conn.OpenAsync();
var deployedResult = (string)ReliableConnectionHelper.ExecuteScalar(conn, $"SELECT TABLE_NAME FROM {targetDb.DatabaseName}.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'table3'; "); var deployedResult = (string)ReliableConnectionHelper.ExecuteScalar(conn, $"SELECT TABLE_NAME FROM {targetDb.DatabaseName}.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'table3'; ");
Assert.Equal(expectedTableResult, deployedResult); Assert.AreEqual(expectedTableResult, deployedResult);
deployedResult = (string)ReliableConnectionHelper.ExecuteScalar(conn, $"SELECT TABLE_NAME FROM {targetDb.DatabaseName}.INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = 'view1'; "); deployedResult = (string)ReliableConnectionHelper.ExecuteScalar(conn, $"SELECT TABLE_NAME FROM {targetDb.DatabaseName}.INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = 'view1'; ");
Assert.Equal(expectedViewResult, deployedResult); Assert.AreEqual(expectedViewResult, deployedResult);
} }
finally finally
{ {
@@ -622,8 +626,8 @@ RETURN 0
// <summary> // <summary>
/// Verify that options are set correctly for a generate script request /// Verify that options are set correctly for a generate script request
/// </summary> /// </summary>
[Fact] [Test]
public async void GenerateDeployScriptWithOptions() public async Task GenerateDeployScriptWithOptions()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: SourceScript, dbNamePrefix: "DacFxDeployOptionsTestSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: SourceScript, dbNamePrefix: "DacFxDeployOptionsTestSource");
@@ -651,8 +655,8 @@ RETURN 0
var generateScriptFalseOptionOperation = new GenerateDeployScriptOperation(generateScriptFalseOptionParams, result.ConnectionInfo); var generateScriptFalseOptionOperation = new GenerateDeployScriptOperation(generateScriptFalseOptionParams, result.ConnectionInfo);
service.PerformOperation(generateScriptFalseOptionOperation, TaskExecutionMode.Execute); service.PerformOperation(generateScriptFalseOptionOperation, TaskExecutionMode.Execute);
Assert.DoesNotContain("table3", generateScriptFalseOptionOperation.Result.DatabaseScript); Assert.That(generateScriptFalseOptionOperation.Result.DatabaseScript, Does.Not.Contain("table3"));
Assert.DoesNotContain("CREATE VIEW", generateScriptFalseOptionOperation.Result.DatabaseScript); Assert.That(generateScriptFalseOptionOperation.Result.DatabaseScript, Does.Not.Contain("CREATE VIEW"));
// try to deploy with the option set to true to make sure it works // try to deploy with the option set to true to make sure it works
var generateScriptTrueOptionParams = new GenerateDeployScriptParams var generateScriptTrueOptionParams = new GenerateDeployScriptParams
@@ -669,8 +673,8 @@ RETURN 0
var generateScriptTrueOptionOperation = new GenerateDeployScriptOperation(generateScriptTrueOptionParams, result.ConnectionInfo); var generateScriptTrueOptionOperation = new GenerateDeployScriptOperation(generateScriptTrueOptionParams, result.ConnectionInfo);
service.PerformOperation(generateScriptTrueOptionOperation, TaskExecutionMode.Execute); service.PerformOperation(generateScriptTrueOptionOperation, TaskExecutionMode.Execute);
Assert.Contains("DROP TABLE [dbo].[table3]", generateScriptTrueOptionOperation.Result.DatabaseScript); Assert.That(generateScriptTrueOptionOperation.Result.DatabaseScript, Does.Contain("DROP TABLE [dbo].[table3]"));
Assert.DoesNotContain("CREATE VIEW", generateScriptTrueOptionOperation.Result.DatabaseScript); Assert.That(generateScriptTrueOptionOperation.Result.DatabaseScript, Does.Not.Contain("CREATE VIEW"));
// now generate script without options // now generate script without options
var generateScriptNoOptionsParams = new GenerateDeployScriptParams var generateScriptNoOptionsParams = new GenerateDeployScriptParams
@@ -682,8 +686,8 @@ RETURN 0
var generateScriptNoOptionsOperation = new GenerateDeployScriptOperation(generateScriptNoOptionsParams, result.ConnectionInfo); var generateScriptNoOptionsOperation = new GenerateDeployScriptOperation(generateScriptNoOptionsParams, result.ConnectionInfo);
service.PerformOperation(generateScriptNoOptionsOperation, TaskExecutionMode.Execute); service.PerformOperation(generateScriptNoOptionsOperation, TaskExecutionMode.Execute);
Assert.Contains("table3", generateScriptNoOptionsOperation.Result.DatabaseScript); Assert.That(generateScriptNoOptionsOperation.Result.DatabaseScript, Does.Contain("table3"));
Assert.Contains("CREATE VIEW", generateScriptNoOptionsOperation.Result.DatabaseScript); Assert.That(generateScriptNoOptionsOperation.Result.DatabaseScript, Does.Contain("CREATE VIEW"));
VerifyAndCleanup(dacpacPath); VerifyAndCleanup(dacpacPath);
} }
@@ -700,8 +704,8 @@ RETURN 0
// <summary> // <summary>
/// Verify that options can get retrieved from publish profile /// Verify that options can get retrieved from publish profile
/// </summary> /// </summary>
[Fact] [Test]
public async void GetOptionsFromProfile() public async Task GetOptionsFromProfile()
{ {
DeploymentOptions expectedResults = new DeploymentOptions() DeploymentOptions expectedResults = new DeploymentOptions()
{ {
@@ -729,8 +733,8 @@ RETURN 0
// <summary> // <summary>
/// Verify that default options are returned if a profile doesn't specify any options /// Verify that default options are returned if a profile doesn't specify any options
/// </summary> /// </summary>
[Fact] [Test]
public async void GetOptionsFromProfileWithoutOptions() public async Task GetOptionsFromProfileWithoutOptions()
{ {
DeploymentOptions expectedResults = new DeploymentOptions(); DeploymentOptions expectedResults = new DeploymentOptions();
expectedResults.ExcludeObjectTypes = null; expectedResults.ExcludeObjectTypes = null;
@@ -22,7 +22,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
{ {
@@ -42,8 +42,8 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// Get backup configuration info /// Get backup configuration info
/// </summary> /// </summary>
/// Test is failing in code coverage runs. Reenable when stable. /// Test is failing in code coverage runs. Reenable when stable.
///[Fact] ///[Test]
public async void GetBackupConfigInfoTest() public async Task GetBackupConfigInfoTest()
{ {
string databaseName = "testbackup_" + new Random().Next(10000000, 99999999); string databaseName = "testbackup_" + new Random().Next(10000000, 99999999);
using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName)) using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName))
@@ -72,7 +72,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// <summary> /// <summary>
/// Create simple backup test /// Create simple backup test
/// </summary> /// </summary>
[Fact] [Test]
public void CreateBackupTest() public void CreateBackupTest()
{ {
DisasterRecoveryService service = new DisasterRecoveryService(); DisasterRecoveryService service = new DisasterRecoveryService();
@@ -100,7 +100,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
} }
} }
[Fact] [Test]
public void ScriptBackupTest() public void ScriptBackupTest()
{ {
DisasterRecoveryService service = new DisasterRecoveryService(); DisasterRecoveryService service = new DisasterRecoveryService();
@@ -137,7 +137,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// <summary> /// <summary>
/// Test creating backup with advanced options set. /// Test creating backup with advanced options set.
/// </summary> /// </summary>
[Fact] [Test]
public void CreateBackupWithAdvancedOptionsTest() public void CreateBackupWithAdvancedOptionsTest()
{ {
DisasterRecoveryService service = new DisasterRecoveryService(); DisasterRecoveryService service = new DisasterRecoveryService();
@@ -190,7 +190,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// <summary> /// <summary>
/// Test creating backup with advanced options set. /// Test creating backup with advanced options set.
/// </summary> /// </summary>
[Fact] [Test]
public void ScriptBackupWithAdvancedOptionsTest() public void ScriptBackupWithAdvancedOptionsTest()
{ {
DisasterRecoveryService service = new DisasterRecoveryService(); DisasterRecoveryService service = new DisasterRecoveryService();
@@ -245,7 +245,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// <summary> /// <summary>
/// Test the correct script generation for different backup action types /// Test the correct script generation for different backup action types
/// </summary> /// </summary>
[Fact] [Test]
public void ScriptBackupWithDifferentActionTypesTest() public void ScriptBackupWithDifferentActionTypesTest()
{ {
string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999);
@@ -255,30 +255,30 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
string script = GenerateScriptForBackupType(BackupType.Full, databaseName); string script = GenerateScriptForBackupType(BackupType.Full, databaseName);
// Validate Full backup script // Validate Full backup script
Assert.Contains("BACKUP DATABASE", script, StringComparison.OrdinalIgnoreCase); Assert.That(script, Does.Contain("BACKUP DATABASE").IgnoreCase);
Assert.DoesNotContain("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase); Assert.That(script, Does.Not.Contain("BACKUP LOG").IgnoreCase);
Assert.DoesNotContain("DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase); Assert.That(script, Does.Not.Contain("DIFFERENTIAL").IgnoreCase);
// Create log backup script // Create log backup script
script = GenerateScriptForBackupType(BackupType.TransactionLog, databaseName); script = GenerateScriptForBackupType(BackupType.TransactionLog, databaseName);
// Validate Log backup script // Validate Log backup script
Assert.Contains("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase); Assert.That(script, Does.Contain("BACKUP LOG").IgnoreCase);
Assert.DoesNotContain("BACKUP DATABASE", script, StringComparison.OrdinalIgnoreCase); Assert.That(script, Does.Not.Contain("BACKUP DATABASE").IgnoreCase);
Assert.DoesNotContain("DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase); Assert.That(script, Does.Not.Contain("DIFFERENTIAL").IgnoreCase);
// Create differential backup script // Create differential backup script
script = GenerateScriptForBackupType(BackupType.Differential, databaseName); script = GenerateScriptForBackupType(BackupType.Differential, databaseName);
// Validate differential backup script // Validate differential backup script
Assert.Contains("BACKUP DATABASE", script, StringComparison.OrdinalIgnoreCase); Assert.That(script, Does.Contain("BACKUP DATABASE").IgnoreCase);
Assert.DoesNotContain("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase); Assert.That(script, Does.Not.Contain("BACKUP LOG").IgnoreCase);
Assert.Contains("WITH DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase); Assert.That(script, Does.Contain("WITH DIFFERENTIAL").IgnoreCase);
} }
} }
//[Fact] //[Test]
public async void BackupFileBrowserTest() public async Task BackupFileBrowserTest()
{ {
string databaseName = "testfilebrowser_" + new Random().Next(10000000, 99999999); string databaseName = "testfilebrowser_" + new Random().Next(10000000, 99999999);
SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);
@@ -13,7 +13,7 @@ using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.Contracts;
using Microsoft.SqlTools.ServiceLayer.FileBrowser; using Microsoft.SqlTools.ServiceLayer.FileBrowser;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility; using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Management; using Microsoft.SqlTools.ServiceLayer.Management;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
{ {
@@ -22,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
/// </summary> /// </summary>
public class DisasterRecoveryFileValidatorTests public class DisasterRecoveryFileValidatorTests
{ {
[Fact] [Test]
public void ValidateDefaultBackupFullFilePath() public void ValidateDefaultBackupFullFilePath()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -39,10 +39,10 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}, out message); }, out message);
Assert.True(result); Assert.True(result);
Assert.Empty(message); Assert.That(message, Is.Empty);
} }
[Fact] [Test]
public void ValidateDefaultBackupFolderPath() public void ValidateDefaultBackupFolderPath()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -56,7 +56,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
Assert.True(result); Assert.True(result);
} }
//[Fact] //[Test]
public void ValidatorShouldReturnFalseForInvalidPath() public void ValidatorShouldReturnFalseForInvalidPath()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -23,7 +23,7 @@ using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests; using Microsoft.SqlTools.ServiceLayer.UnitTests;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper; using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
@@ -65,16 +65,16 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
return backupFilesToRecoverDatabase; return backupFilesToRecoverDatabase;
} }
[Fact] [Test]
public async void RestorePlanShouldCreatedSuccessfullyForFullBackup() public async Task RestorePlanShouldCreatedSuccessfullyForFullBackup()
{ {
await VerifyBackupFileCreated(); await VerifyBackupFileCreated();
bool canRestore = true; bool canRestore = true;
await VerifyRestore(fullBackupFilePath, canRestore); await VerifyRestore(fullBackupFilePath, canRestore);
} }
[Fact] [Test]
public async void RestoreShouldNotRestoreAnyBackupSetsIfFullNotSelected() public async Task RestoreShouldNotRestoreAnyBackupSetsIfFullNotSelected()
{ {
var backupFiles = await GetBackupFilesToRecoverDatabaseCreated(); var backupFiles = await GetBackupFilesToRecoverDatabaseCreated();
//Remove the full backupset //Remove the full backupset
@@ -85,8 +85,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
await VerifyRestoreMultipleBackupSets(backupFiles, indexToDelete, expectedTable, TaskExecutionModeFlag.Execute); await VerifyRestoreMultipleBackupSets(backupFiles, indexToDelete, expectedTable, TaskExecutionModeFlag.Execute);
} }
[Fact] [Test]
public async void RestoreShouldRestoreFromAnotherDatabase() public async Task RestoreShouldRestoreFromAnotherDatabase()
{ {
await GetBackupFilesToRecoverDatabaseCreated(); await GetBackupFilesToRecoverDatabaseCreated();
@@ -106,8 +106,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async void RestoreShouldFailIfThereAreOtherConnectionsToDatabase() public async Task RestoreShouldFailIfThereAreOtherConnectionsToDatabase()
{ {
await GetBackupFilesToRecoverDatabaseCreated(); await GetBackupFilesToRecoverDatabaseCreated();
@@ -138,8 +138,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async void RestoreShouldFailIfThereAreOtherConnectionsToDatabase2() public async Task RestoreShouldFailIfThereAreOtherConnectionsToDatabase2()
{ {
await GetBackupFilesToRecoverDatabaseCreated(); await GetBackupFilesToRecoverDatabaseCreated();
@@ -173,8 +173,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async void RestoreShouldCloseOtherConnectionsBeforeExecuting() public async Task RestoreShouldCloseOtherConnectionsBeforeExecuting()
{ {
await GetBackupFilesToRecoverDatabaseCreated(); await GetBackupFilesToRecoverDatabaseCreated();
@@ -213,8 +213,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async void RestoreShouldRestoreTheBackupSetsThatAreSelected() public async Task RestoreShouldRestoreTheBackupSetsThatAreSelected()
{ {
var backupFiles = await GetBackupFilesToRecoverDatabaseCreated(); var backupFiles = await GetBackupFilesToRecoverDatabaseCreated();
//Remove the last backupset //Remove the last backupset
@@ -225,8 +225,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
await VerifyRestoreMultipleBackupSets(backupFiles, indexToDelete, expectedTable); await VerifyRestoreMultipleBackupSets(backupFiles, indexToDelete, expectedTable);
} }
[Fact] [Test]
public async void RestoreShouldNotRestoreTheLogBackupSetsIfOneNotSelected() public async Task RestoreShouldNotRestoreTheLogBackupSetsIfOneNotSelected()
{ {
var backupFiles = await GetBackupFilesToRecoverDatabaseCreated(); var backupFiles = await GetBackupFilesToRecoverDatabaseCreated();
//Remove the one of the log backup sets //Remove the one of the log backup sets
@@ -276,7 +276,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
for (int i = 0; i < response.BackupSetsToRestore.Count(); i++) for (int i = 0; i < response.BackupSetsToRestore.Count(); i++)
{ {
DatabaseFileInfo databaseInfo = response.BackupSetsToRestore[i]; DatabaseFileInfo databaseInfo = response.BackupSetsToRestore[i];
Assert.Equal(databaseInfo.IsSelected, expectedSelectedIndexes.Contains(i)); Assert.AreEqual(databaseInfo.IsSelected, expectedSelectedIndexes.Contains(i));
} }
} }
finally finally
@@ -288,8 +288,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async void RestorePlanShouldCreatedSuccessfullyOnExistingDatabaseGivenReplaceOption() public async Task RestorePlanShouldCreatedSuccessfullyOnExistingDatabaseGivenReplaceOption()
{ {
SqlTestDb testDb = null; SqlTestDb testDb = null;
try try
@@ -312,8 +312,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async void RestorePlanShouldFailOnExistingDatabaseNotGivenReplaceOption() public async Task RestorePlanShouldFailOnExistingDatabaseNotGivenReplaceOption()
{ {
SqlTestDb testDb = null; SqlTestDb testDb = null;
try try
@@ -334,8 +334,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
//[Fact] //[Test]
public async void RestoreShouldCreatedSuccessfullyGivenTwoBackupFiles() public async Task RestoreShouldCreatedSuccessfullyGivenTwoBackupFiles()
{ {
string[] backupFileNames = new string[] { "FullBackup.bak", "DiffBackup.bak" }; string[] backupFileNames = new string[] { "FullBackup.bak", "DiffBackup.bak" };
@@ -344,8 +344,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
Assert.True(response.BackupSetsToRestore.Count() == 2); Assert.True(response.BackupSetsToRestore.Count() == 2);
} }
//[Fact] //[Test]
public async void RestoreShouldFailGivenTwoBackupFilesButFilterFullBackup() public async Task RestoreShouldFailGivenTwoBackupFilesButFilterFullBackup()
{ {
string[] backupFileNames = new string[] { "FullBackup.bak", "DiffBackup.bak" }; string[] backupFileNames = new string[] { "FullBackup.bak", "DiffBackup.bak" };
@@ -360,8 +360,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
//[Fact] //[Test]
public async void RestoreShouldCompletedSuccessfullyGivenTwoBackupFilesButFilterDifferentialBackup() public async Task RestoreShouldCompletedSuccessfullyGivenTwoBackupFilesButFilterDifferentialBackup()
{ {
string[] backupFileNames = new string[] { "FullBackup.bak", "DiffBackup.bak" }; string[] backupFileNames = new string[] { "FullBackup.bak", "DiffBackup.bak" };
@@ -376,8 +376,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async void RestoreShouldExecuteSuccessfullyForFullBackup() public async Task RestoreShouldExecuteSuccessfullyForFullBackup()
{ {
await VerifyBackupFileCreated(); await VerifyBackupFileCreated();
@@ -387,8 +387,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
Assert.NotNull(restorePlan.BackupSetsToRestore); Assert.NotNull(restorePlan.BackupSetsToRestore);
} }
[Fact] [Test]
public async void RestoreToAnotherDatabaseShouldExecuteSuccessfullyForFullBackup() public async Task RestoreToAnotherDatabaseShouldExecuteSuccessfullyForFullBackup()
{ {
await VerifyBackupFileCreated(); await VerifyBackupFileCreated();
@@ -397,23 +397,23 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
var restorePlan = await VerifyRestore(backupFileName, canRestore, TaskExecutionModeFlag.ExecuteAndScript, "NewRestoredDatabase"); var restorePlan = await VerifyRestore(backupFileName, canRestore, TaskExecutionModeFlag.ExecuteAndScript, "NewRestoredDatabase");
} }
//[Fact] //[Test]
public async void RestorePlanShouldCreatedSuccessfullyForDiffBackup() public async Task RestorePlanShouldCreatedSuccessfullyForDiffBackup()
{ {
string backupFileName = "DiffBackup.bak"; string backupFileName = "DiffBackup.bak";
bool canRestore = true; bool canRestore = true;
await VerifyRestore(backupFileName, canRestore); await VerifyRestore(backupFileName, canRestore);
} }
//[Fact] //[Test]
public async void RestorePlanShouldCreatedSuccessfullyForTransactionLogBackup() public async Task RestorePlanShouldCreatedSuccessfullyForTransactionLogBackup()
{ {
string backupFileName = "TransactionLogBackup.bak"; string backupFileName = "TransactionLogBackup.bak";
bool canRestore = true; bool canRestore = true;
await VerifyRestore(backupFileName, canRestore); await VerifyRestore(backupFileName, canRestore);
} }
[Fact] [Test]
public async Task RestorePlanRequestShouldReturnResponseWithDbFiles() public async Task RestorePlanRequestShouldReturnResponseWithDbFiles()
{ {
await VerifyBackupFileCreated(); await VerifyBackupFileCreated();
@@ -439,7 +439,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async Task CancelRestorePlanRequestShouldCancelSuccessfully() public async Task CancelRestorePlanRequestShouldCancelSuccessfully()
{ {
await VerifyBackupFileCreated(); await VerifyBackupFileCreated();
@@ -473,7 +473,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async Task RestoreConfigInfoRequestShouldReturnResponse() public async Task RestoreConfigInfoRequestShouldReturnResponse()
{ {
await VerifyBackupFileCreated(); await VerifyBackupFileCreated();
@@ -499,7 +499,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async Task RestoreDatabaseRequestShouldStartTheRestoreTask() public async Task RestoreDatabaseRequestShouldStartTheRestoreTask()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -526,7 +526,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
} }
} }
[Fact] [Test]
public async Task RestorePlanRequestShouldReturnErrorMessageGivenInvalidFilePath() public async Task RestorePlanRequestShouldReturnErrorMessageGivenInvalidFilePath()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -625,7 +625,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
Assert.NotNull(response); Assert.NotNull(response);
Assert.False(string.IsNullOrWhiteSpace(response.SessionId)); Assert.False(string.IsNullOrWhiteSpace(response.SessionId));
Assert.Equal(response.CanRestore, canRestore); Assert.AreEqual(response.CanRestore, canRestore);
if (canRestore) if (canRestore)
{ {
Assert.True(response.DbFiles.Any()); Assert.True(response.DbFiles.Any());
@@ -633,7 +633,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
{ {
targetDatabase = response.DatabaseName; targetDatabase = response.DatabaseName;
} }
Assert.Equal(response.DatabaseName, targetDatabase); Assert.AreEqual(response.DatabaseName, targetDatabase);
Assert.NotNull(response.PlanDetails); Assert.NotNull(response.PlanDetails);
Assert.True(response.PlanDetails.Any()); Assert.True(response.PlanDetails.Any());
Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.BackupTailLog]); Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.BackupTailLog]);
@@ -649,7 +649,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
{ {
request.SessionId = response.SessionId; request.SessionId = response.SessionId;
restoreDataObject = service.CreateRestoreDatabaseTaskDataObject(request); restoreDataObject = service.CreateRestoreDatabaseTaskDataObject(request);
Assert.Equal(response.SessionId, restoreDataObject.SessionId); Assert.AreEqual(response.SessionId, restoreDataObject.SessionId);
request.RelocateDbFiles = !restoreDataObject.DbFilesLocationAreValid(); request.RelocateDbFiles = !restoreDataObject.DbFilesLocationAreValid();
restoreDataObject.Execute((TaskExecutionMode)Enum.Parse(typeof(TaskExecutionMode), executionMode.ToString())); restoreDataObject.Execute((TaskExecutionMode)Enum.Parse(typeof(TaskExecutionMode), executionMode.ToString()));
@@ -666,7 +666,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
//Some tests still verify the number of backup sets that are executed which in some cases can be less than the selected list //Some tests still verify the number of backup sets that are executed which in some cases can be less than the selected list
if (verifyDatabase == null && selectedBackupSets != null) if (verifyDatabase == null && selectedBackupSets != null)
{ {
Assert.Equal(selectedBackupSets.Count(), restoreDataObject.RestorePlanToExecute.RestoreOperations.Count()); Assert.AreEqual(selectedBackupSets.Count(), restoreDataObject.RestorePlanToExecute.RestoreOperations.Count());
} }
} }
if(executionMode.HasFlag(TaskExecutionModeFlag.Script)) if(executionMode.HasFlag(TaskExecutionModeFlag.Script))
@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.FileBrowser.Contracts;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility; using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
{ {
@@ -21,8 +21,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
{ {
#region Request handle tests #region Request handle tests
[Fact] [Test]
public async void HandleFileBrowserOpenRequestTest() public async Task HandleFileBrowserOpenRequestTest()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
FileBrowserService service = new FileBrowserService(); FileBrowserService service = new FileBrowserService();
@@ -41,8 +41,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
openRequestContext.Verify(x => x.SendResult(It.Is<bool>(p => p == true))); openRequestContext.Verify(x => x.SendResult(It.Is<bool>(p => p == true)));
} }
[Fact] [Test]
public async void HandleFileBrowserExpandRequestTest() public async Task HandleFileBrowserExpandRequestTest()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
FileBrowserService service = new FileBrowserService(); FileBrowserService service = new FileBrowserService();
@@ -59,8 +59,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
requestContext.Verify(x => x.SendResult(It.Is<bool>(p => p == true))); requestContext.Verify(x => x.SendResult(It.Is<bool>(p => p == true)));
} }
[Fact] [Test]
public async void HandleFileBrowserValidateRequestTest() public async Task HandleFileBrowserValidateRequestTest()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
FileBrowserService service = new FileBrowserService(); FileBrowserService service = new FileBrowserService();
@@ -77,8 +77,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
requestContext.Verify(x => x.SendResult(It.Is<bool>(p => p == true))); requestContext.Verify(x => x.SendResult(It.Is<bool>(p => p == true)));
} }
[Fact] [Test]
public async void HandleFileBrowserCloseRequestTest() public async Task HandleFileBrowserCloseRequestTest()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
FileBrowserService service = new FileBrowserService(); FileBrowserService service = new FileBrowserService();
@@ -96,8 +96,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
#endregion #endregion
[Fact] [Test]
public async void OpenFileBrowserTest() public async Task OpenFileBrowserTest()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
FileBrowserService service = new FileBrowserService(); FileBrowserService service = new FileBrowserService();
@@ -123,8 +123,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
efv.Validate(); efv.Validate();
} }
[Fact] [Test]
public async void ValidateSelectedFilesWithNullValidatorTest() public async Task ValidateSelectedFilesWithNullValidatorTest()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
FileBrowserService service = new FileBrowserService(); FileBrowserService service = new FileBrowserService();
@@ -146,8 +146,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
efv.Validate(); efv.Validate();
} }
[Fact] [Test]
public async void InvalidFileValidationTest() public async Task InvalidFileValidationTest()
{ {
FileBrowserService service = new FileBrowserService(); FileBrowserService service = new FileBrowserService();
service.RegisterValidatePathsCallback("TestService", ValidatePaths); service.RegisterValidatePathsCallback("TestService", ValidatePaths);
@@ -17,15 +17,15 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
{ {
public class ExternalLanguageServiceTests : ServiceTestBase public class ExternalLanguageServiceTests : ServiceTestBase
{ {
[Fact] [Test]
public async void VerifyExternalLanguageStatusRequest() public async Task VerifyExternalLanguageStatusRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -50,8 +50,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
} }
} }
[Fact] [Test]
public async void VerifyExternalLanguageDeleteRequest() public async Task VerifyExternalLanguageDeleteRequest()
{ {
ExternalLanguage language = new ExternalLanguage ExternalLanguage language = new ExternalLanguage
{ {
@@ -80,8 +80,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
})); }));
} }
[Fact] [Test]
public async void VerifyExternalLanguageDeleteRequestFailures() public async Task VerifyExternalLanguageDeleteRequestFailures()
{ {
ExternalLanguage language = new ExternalLanguage ExternalLanguage language = new ExternalLanguage
{ {
@@ -106,8 +106,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}); });
} }
[Fact] [Test]
public async void VerifyExternalLanguageDeleteRequestConnectionFailures() public async Task VerifyExternalLanguageDeleteRequestConnectionFailures()
{ {
ExternalLanguage language = new ExternalLanguage ExternalLanguage language = new ExternalLanguage
{ {
@@ -131,8 +131,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}); });
} }
[Fact] [Test]
public async void VerifyExternalLanguageUpdateRequest() public async Task VerifyExternalLanguageUpdateRequest()
{ {
ExternalLanguage language = new ExternalLanguage ExternalLanguage language = new ExternalLanguage
{ {
@@ -161,8 +161,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
})); }));
} }
[Fact] [Test]
public async void VerifyExternalLanguageUpdateRequestFailures() public async Task VerifyExternalLanguageUpdateRequestFailures()
{ {
ExternalLanguage language = new ExternalLanguage ExternalLanguage language = new ExternalLanguage
{ {
@@ -187,8 +187,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}); });
} }
[Fact] [Test]
public async void VerifyExternalLanguageUpdateRequestConnectionFailures() public async Task VerifyExternalLanguageUpdateRequestConnectionFailures()
{ {
ExternalLanguage language = new ExternalLanguage ExternalLanguage language = new ExternalLanguage
{ {
@@ -212,8 +212,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}); });
} }
[Fact] [Test]
public async void VerifyExternalLanguageListRequest() public async Task VerifyExternalLanguageListRequest()
{ {
ExternalLanguage language = new ExternalLanguage ExternalLanguage language = new ExternalLanguage
{ {
@@ -241,8 +241,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
})); }));
} }
[Fact] [Test]
public async void VerifyExternalLanguagListRequestFailures() public async Task VerifyExternalLanguagListRequestFailures()
{ {
ExternalLanguage language = new ExternalLanguage ExternalLanguage language = new ExternalLanguage
{ {
@@ -266,8 +266,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}); });
} }
[Fact] [Test]
public async void VerifyExternalLanguagListRequestConnectionFailures() public async Task VerifyExternalLanguagListRequestConnectionFailures()
{ {
ExternalLanguage language = new ExternalLanguage ExternalLanguage language = new ExternalLanguage
{ {
@@ -323,8 +323,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
} }
} }
[Fact] [Test]
public async void VerifyExternalLanguageStatusRequestSendErrorGivenInvalidConnection() public async Task VerifyExternalLanguageStatusRequestSendErrorGivenInvalidConnection()
{ {
ExternalLanguageStatusResponseParams result = null; ExternalLanguageStatusResponseParams result = null;
var requestContext = RequestContextMocks.Create<ExternalLanguageStatusResponseParams>(r => result = r).AddErrorHandling(null); var requestContext = RequestContextMocks.Create<ExternalLanguageStatusResponseParams>(r => result = r).AddErrorHandling(null);
@@ -22,7 +22,7 @@ using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
{ {
@@ -51,7 +51,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary> /// <summary>
/// Test the service initialization code path and verify nothing throws /// Test the service initialization code path and verify nothing throws
/// </summary> /// </summary>
[Fact] [Test]
public void ServiceInitialization() public void ServiceInitialization()
{ {
try try
@@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary> /// <summary>
/// Test the service initialization code path and verify nothing throws /// Test the service initialization code path and verify nothing throws
/// </summary> /// </summary>
//[Fact] //[Test]
public void PrepopulateCommonMetadata() public void PrepopulateCommonMetadata()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -89,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary> /// <summary>
/// This test tests auto completion /// This test tests auto completion
/// </summary> /// </summary>
[Fact] [Test]
public void AutoCompleteFindCompletions() public void AutoCompleteFindCompletions()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
@@ -123,8 +123,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// 2. Initializing a completion extension implementation /// 2. Initializing a completion extension implementation
/// 3. Excuting an auto completion with extension enabled /// 3. Excuting an auto completion with extension enabled
/// </summary> /// </summary>
[Fact] [Test]
public async void AutoCompleteWithExtension() public async Task AutoCompleteWithExtension()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
@@ -217,7 +217,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// has an associated ScriptParseInfo and the provided query has a function that should /// has an associated ScriptParseInfo and the provided query has a function that should
/// provide signature help. /// provide signature help.
/// </summary> /// </summary>
[Fact] [Test]
public async Task GetSignatureHelpReturnsNotNullIfParseInfoInitialized() public async Task GetSignatureHelpReturnsNotNullIfParseInfoInitialized()
{ {
// When we make a connection to a live database // When we make a connection to a live database
@@ -257,7 +257,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary> /// <summary>
/// Test overwriting the binding queue context /// Test overwriting the binding queue context
/// </summary> /// </summary>
[Fact] [Test]
public void OverwriteBindingContext() public void OverwriteBindingContext()
{ {
var result = LiveConnectionHelper.InitLiveConnectionInfo(); var result = LiveConnectionHelper.InitLiveConnectionInfo();
@@ -279,7 +279,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary> /// <summary>
/// Verifies that clearing the Intellisense cache correctly refreshes the cache with new info from the DB. /// Verifies that clearing the Intellisense cache correctly refreshes the cache with new info from the DB.
/// </summary> /// </summary>
[Fact] [Test]
public async Task RebuildIntellisenseCacheClearsScriptParseInfoCorrectly() public async Task RebuildIntellisenseCacheClearsScriptParseInfoCorrectly()
{ {
var testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, null, null, "LangSvcTest"); var testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, null, null, "LangSvcTest");
@@ -338,7 +338,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
// This test validates switching off editor intellisesnse for now. // This test validates switching off editor intellisesnse for now.
// Will change to better handling once we have specific SQLCMD intellisense in Language Service // Will change to better handling once we have specific SQLCMD intellisense in Language Service
/// </summary> /// </summary>
[Fact] [Test]
public async Task HandleRequestToChangeToSqlcmdFile() public async Task HandleRequestToChangeToSqlcmdFile()
{ {
@@ -15,7 +15,7 @@ using System;
using System.Data.Common; using System.Data.Common;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using Xunit; using NUnit.Framework;
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;
@@ -86,7 +86,7 @@ GO";
/// <summary> /// <summary>
/// Test get definition for a table object with active connection /// Test get definition for a table object with active connection
/// </summary> /// </summary>
[Fact] [Test]
public void GetValidTableDefinitionTest() public void GetValidTableDefinitionTest()
{ {
// Get live connectionInfo and serverConnection // Get live connectionInfo and serverConnection
@@ -105,7 +105,7 @@ GO";
Cleanup(locations); Cleanup(locations);
} }
[Fact] [Test]
public void LoggerGetValidTableDefinitionTest() public void LoggerGetValidTableDefinitionTest()
{ {
TestLogger test = new TestLogger() TestLogger test = new TestLogger()
@@ -126,7 +126,7 @@ GO";
/// <summary> /// <summary>
/// Test get definition for a invalid table object with active connection /// Test get definition for a invalid table object with active connection
/// </summary> /// </summary>
[Fact] [Test]
public void GetTableDefinitionInvalidObjectTest() public void GetTableDefinitionInvalidObjectTest()
{ {
// Get live connectionInfo and serverConnection // Get live connectionInfo and serverConnection
@@ -146,7 +146,7 @@ GO";
/// <summary> /// <summary>
/// Test get definition for a valid table object with schema and active connection /// Test get definition for a valid table object with schema and active connection
/// </summary> /// </summary>
[Fact] [Test]
public void GetTableDefinitionWithSchemaTest() public void GetTableDefinitionWithSchemaTest()
{ {
// Get live connectionInfo and serverConnection // Get live connectionInfo and serverConnection
@@ -168,7 +168,7 @@ GO";
/// <summary> /// <summary>
/// Test GetDefinition with an unsupported type(schema - dbo). Expect a error result. /// Test GetDefinition with an unsupported type(schema - dbo). Expect a error result.
/// </summary> /// </summary>
[Fact] [Test]
public void GetUnsupportedDefinitionErrorTest() public void GetUnsupportedDefinitionErrorTest()
{ {
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -187,7 +187,7 @@ GO";
/// <summary> /// <summary>
/// Get Definition for a object with no definition. Expect a error result /// Get Definition for a object with no definition. Expect a error result
/// </summary> /// </summary>
[Fact] [Test]
public void GetDefinitionWithNoResultsFoundError() public void GetDefinitionWithNoResultsFoundError()
{ {
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -206,13 +206,13 @@ GO";
Assert.NotNull(result); Assert.NotNull(result);
Assert.True(result.IsErrorResult); Assert.True(result.IsErrorResult);
Assert.Equal(SR.PeekDefinitionNoResultsError, result.Message); Assert.AreEqual(SR.PeekDefinitionNoResultsError, result.Message);
} }
/// <summary> /// <summary>
/// Test GetDefinition with a forced timeout. Expect a error result. /// Test GetDefinition with a forced timeout. Expect a error result.
/// </summary> /// </summary>
[Fact] [Test]
public void GetDefinitionTimeoutTest() public void GetDefinitionTimeoutTest()
{ {
// Given a binding queue that will automatically time out // Given a binding queue that will automatically time out
@@ -268,13 +268,13 @@ GO";
Assert.NotNull(result); Assert.NotNull(result);
Assert.True(result.IsErrorResult); Assert.True(result.IsErrorResult);
// Check timeout message // Check timeout message
Assert.Equal(SR.PeekDefinitionTimedoutError, result.Message); Assert.AreEqual(SR.PeekDefinitionTimedoutError, result.Message);
} }
/// <summary> /// <summary>
/// Test get definition for a view object with active connection /// Test get definition for a view object with active connection
/// </summary> /// </summary>
[Fact] [Test]
public void GetValidViewDefinitionTest() public void GetValidViewDefinitionTest()
{ {
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -293,7 +293,7 @@ GO";
/// <summary> /// <summary>
/// Test get definition for an invalid view object with no schema name and with active connection /// Test get definition for an invalid view object with no schema name and with active connection
/// </summary> /// </summary>
[Fact] [Test]
public void GetViewDefinitionInvalidObjectTest() public void GetViewDefinitionInvalidObjectTest()
{ {
// Get live connectionInfo and serverConnection // Get live connectionInfo and serverConnection
@@ -312,7 +312,7 @@ GO";
/// <summary> /// <summary>
/// Test get definition for a stored procedure object with active connection /// Test get definition for a stored procedure object with active connection
/// </summary> /// </summary>
[Fact] [Test]
public void GetStoredProcedureDefinitionTest() public void GetStoredProcedureDefinitionTest()
{ {
// Get live connectionInfo and serverConnection // Get live connectionInfo and serverConnection
@@ -333,7 +333,7 @@ GO";
/// <summary> /// <summary>
/// Test get definition for a stored procedure object that does not exist with active connection /// Test get definition for a stored procedure object that does not exist with active connection
/// </summary> /// </summary>
[Fact] [Test]
public void GetStoredProcedureDefinitionFailureTest() public void GetStoredProcedureDefinitionFailureTest()
{ {
// Get live connectionInfo and serverConnection // Get live connectionInfo and serverConnection
@@ -352,7 +352,7 @@ GO";
/// <summary> /// <summary>
/// Test get definition for a stored procedure object with active connection and no schema /// Test get definition for a stored procedure object with active connection and no schema
/// </summary> /// </summary>
[Fact] [Test]
public void GetStoredProcedureDefinitionWithoutSchemaTest() public void GetStoredProcedureDefinitionWithoutSchemaTest()
{ {
// Get live connectionInfo and serverConnection // Get live connectionInfo and serverConnection
@@ -372,7 +372,7 @@ GO";
/// <summary> /// <summary>
/// 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] [Test]
public async Task GetScalarValuedFunctionDefinitionWithSchemaNameSuccessTest() public async Task GetScalarValuedFunctionDefinitionWithSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName); await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName);
@@ -421,7 +421,7 @@ GO";
/// <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] [Test]
public async Task GetTableValuedFunctionDefinitionWithSchemaNameSuccessTest() public async Task GetTableValuedFunctionDefinitionWithSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, ScalarValuedFunctionTypeName); await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, ScalarValuedFunctionTypeName);
@@ -430,7 +430,7 @@ GO";
/// <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] [Test]
public async Task GetScalarValuedFunctionDefinitionWithNonExistentFailureTest() public async Task GetScalarValuedFunctionDefinitionWithNonExistentFailureTest()
{ {
string objectName = "doesNotExist"; string objectName = "doesNotExist";
@@ -443,7 +443,7 @@ GO";
/// <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] [Test]
public async Task GetTableValuedFunctionDefinitionWithNonExistentObjectFailureTest() public async Task GetTableValuedFunctionDefinitionWithNonExistentObjectFailureTest()
{ {
string objectName = "doesNotExist"; string objectName = "doesNotExist";
@@ -455,7 +455,7 @@ GO";
/// <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] [Test]
public async Task GetScalarValuedFunctionDefinitionWithoutSchemaNameSuccessTest() public async Task GetScalarValuedFunctionDefinitionWithoutSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName, null); await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName, null);
@@ -464,7 +464,7 @@ GO";
/// <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] [Test]
public async Task GetTableValuedFunctionDefinitionWithoutSchemaNameSuccessTest() public async Task GetTableValuedFunctionDefinitionWithoutSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, ScalarValuedFunctionTypeName, null); await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, ScalarValuedFunctionTypeName, null);
@@ -474,7 +474,7 @@ GO";
/// <summary> /// <summary>
/// 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] [Test]
public async Task GetUserDefinedDataTypeDefinitionWithSchemaNameSuccessTest() public async Task GetUserDefinedDataTypeDefinitionWithSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName); await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName);
@@ -483,7 +483,7 @@ GO";
/// <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] [Test]
public async Task GetUserDefinedDataTypeDefinitionWithoutSchemaNameSuccessTest() public async Task GetUserDefinedDataTypeDefinitionWithoutSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName, null); await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName, null);
@@ -492,7 +492,7 @@ GO";
/// <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] [Test]
public async Task GetUserDefinedDataTypeDefinitionWithNonExistentFailureTest() public async Task GetUserDefinedDataTypeDefinitionWithNonExistentFailureTest()
{ {
string objectName = "doesNotExist"; string objectName = "doesNotExist";
@@ -504,7 +504,7 @@ GO";
/// <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] [Test]
public async Task GetUserDefinedTableTypeDefinitionWithSchemaNameSuccessTest() public async Task GetUserDefinedTableTypeDefinitionWithSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName); await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName);
@@ -513,7 +513,7 @@ GO";
/// <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] [Test]
public async Task GetUserDefinedTableTypeDefinitionWithoutSchemaNameSuccessTest() public async Task GetUserDefinedTableTypeDefinitionWithoutSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName, null); await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName, null);
@@ -522,7 +522,7 @@ GO";
/// <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] [Test]
public async Task GetUserDefinedTableTypeDefinitionWithNonExistentFailureTest() public async Task GetUserDefinedTableTypeDefinitionWithNonExistentFailureTest()
{ {
string objectName = "doesNotExist"; string objectName = "doesNotExist";
@@ -535,7 +535,7 @@ GO";
/// <summary> /// <summary>
/// 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] [Test]
public async Task GetSynonymDefinitionWithSchemaNameSuccessTest() public async Task GetSynonymDefinitionWithSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName); await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName);
@@ -545,7 +545,7 @@ GO";
/// <summary> /// <summary>
/// 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] [Test]
public async Task GetSynonymDefinitionWithoutSchemaNameSuccessTest() public async Task GetSynonymDefinitionWithoutSchemaNameSuccessTest()
{ {
await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName, null); await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName, null);
@@ -554,7 +554,7 @@ GO";
/// <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] [Test]
public async Task GetSynonymDefinitionWithNonExistentFailureTest() public async Task GetSynonymDefinitionWithNonExistentFailureTest()
{ {
string objectName = "doesNotExist"; string objectName = "doesNotExist";
@@ -567,7 +567,7 @@ GO";
/// Test get definition using declaration type for a view object with active connection /// Test get definition using declaration type for a view object with active connection
/// Expect a non-null result with location /// Expect a non-null result with location
/// </summary> /// </summary>
[Fact] [Test]
public void GetDefinitionUsingDeclarationTypeWithValidObjectTest() public void GetDefinitionUsingDeclarationTypeWithValidObjectTest()
{ {
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -589,7 +589,7 @@ GO";
/// Test get definition using declaration type for a non existent view object with active connection /// Test get definition using declaration type for a non existent view object with active connection
/// Expect a non-null result with location /// Expect a non-null result with location
/// </summary> /// </summary>
[Fact] [Test]
public void GetDefinitionUsingDeclarationTypeWithNonexistentObjectTest() public void GetDefinitionUsingDeclarationTypeWithNonexistentObjectTest()
{ {
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -608,7 +608,7 @@ GO";
/// Test get definition using quickInfo text for a view object with active connection /// Test get definition using quickInfo text for a view object with active connection
/// Expect a non-null result with location /// Expect a non-null result with location
/// </summary> /// </summary>
[Fact] [Test]
public void GetDefinitionUsingQuickInfoTextWithValidObjectTest() public void GetDefinitionUsingQuickInfoTextWithValidObjectTest()
{ {
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -631,7 +631,7 @@ GO";
/// Test get definition using quickInfo text for a view object with active connection /// Test get definition using quickInfo text for a view object with active connection
/// Expect a non-null result with location /// Expect a non-null result with location
/// </summary> /// </summary>
[Fact] [Test]
public void GetDefinitionUsingQuickInfoTextWithNonexistentObjectTest() public void GetDefinitionUsingQuickInfoTextWithNonexistentObjectTest()
{ {
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -652,7 +652,7 @@ GO";
/// Given that there is no query connection /// Given that there is no query connection
/// Expect database name to be "master" /// Expect database name to be "master"
/// </summary> /// </summary>
[Fact] [Test]
public void GetDatabaseWithNoQueryConnectionTest() public void GetDatabaseWithNoQueryConnectionTest()
{ {
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -663,7 +663,7 @@ GO";
Scripter scripter = new Scripter(serverConnection, connInfo); Scripter scripter = new Scripter(serverConnection, connInfo);
//Check if database name is the default server connection database name //Check if database name is the default server connection database name
Assert.Equal(scripter.Database.Name, "master"); Assert.AreEqual("master", scripter.Database.Name);
} }
/// <summary> /// <summary>
@@ -671,7 +671,7 @@ GO";
/// Give that there is a query connection /// Give that there is a query connection
/// Expect database name to be query connection's database name /// Expect database name to be query connection's database name
/// </summary> /// </summary>
[Fact] [Test]
public void GetDatabaseWithQueryConnectionTest() public void GetDatabaseWithQueryConnectionTest()
{ {
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -686,7 +686,7 @@ GO";
Scripter scripter = new Scripter(serverConnection, connInfo); Scripter scripter = new Scripter(serverConnection, connInfo);
//Check if database name is the database name in the query connection //Check if database name is the database name in the query connection
Assert.Equal(scripter.Database.Name, "testdb"); Assert.AreEqual("testdb", scripter.Database.Name);
// remove mock from ConnectionInfo // remove mock from ConnectionInfo
Assert.True(connInfo.ConnectionTypeToConnectionMap.TryRemove(ConnectionType.Query, out connection)); Assert.True(connInfo.ConnectionTypeToConnectionMap.TryRemove(ConnectionType.Query, out connection));
@@ -698,8 +698,8 @@ 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] [Test]
public async void GetDefinitionFromChildrenAndParents() public async Task GetDefinitionFromChildrenAndParents()
{ {
string queryString = "select * from master.sys.objects"; string queryString = "select * from master.sys.objects";
// place the cursor on every token // place the cursor on every token
@@ -743,8 +743,8 @@ GO";
Assert.NotNull(masterResult); Assert.NotNull(masterResult);
// And I expect the all results to be the same // And I expect the all results to be the same
Assert.True(CompareLocations(objectResult.Locations, sysResult.Locations)); Assert.That(objectResult.Locations, Is.EqualTo(sysResult.Locations), "objectResult and sysResult Locations");
Assert.True(CompareLocations(objectResult.Locations, masterResult.Locations)); Assert.That(objectResult.Locations, Is.EqualTo(masterResult.Locations), "objectResult and masterResult Locations");
Cleanup(objectResult.Locations); Cleanup(objectResult.Locations);
Cleanup(sysResult.Locations); Cleanup(sysResult.Locations);
@@ -753,8 +753,8 @@ GO";
connInfo.RemoveAllConnections(); connInfo.RemoveAllConnections();
} }
[Fact] [Test]
public async void GetDefinitionFromProcedures() public async Task GetDefinitionFromProcedures()
{ {
string queryString = "EXEC master.dbo.sp_MSrepl_startup"; string queryString = "EXEC master.dbo.sp_MSrepl_startup";
@@ -17,7 +17,7 @@ using Microsoft.Data.SqlClient;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper; using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
@@ -70,7 +70,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
/// <summary> /// <summary>
/// Verify that the metadata service correctly returns details for user tables /// Verify that the metadata service correctly returns details for user tables
/// </summary> /// </summary>
[Fact] [Test]
public void MetadataReturnsUserTable() public void MetadataReturnsUserTable()
{ {
this.testTableName += new Random().Next(1000000, 9999999).ToString(); this.testTableName += new Random().Next(1000000, 9999999).ToString();
@@ -100,8 +100,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
DeleteTestTable(sqlConn); DeleteTestTable(sqlConn);
} }
[Fact] [Test]
public async void GetTableInfoReturnsValidResults() public async Task GetTableInfoReturnsValidResults()
{ {
this.testTableName += new Random().Next(1000000, 9999999).ToString(); this.testTableName += new Random().Next(1000000, 9999999).ToString();
@@ -127,8 +127,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
requestContext.VerifyAll(); requestContext.VerifyAll();
} }
[Fact] [Test]
public async void GetViewInfoReturnsValidResults() public async Task GetViewInfoReturnsValidResults()
{ {
var result = GetLiveAutoCompleteTestObjects(); var result = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<TableMetadataResult>>(); var requestContext = new Mock<RequestContext<TableMetadataResult>>();
@@ -146,8 +146,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
requestContext.VerifyAll(); requestContext.VerifyAll();
} }
[Fact] [Test]
public async void VerifyMetadataList() public async Task VerifyMetadataList()
{ {
string query = @"CREATE TABLE testTable1 (c1 int) string query = @"CREATE TABLE testTable1 (c1 int)
GO GO
@@ -20,8 +20,9 @@
<PackageReference Include="Moq" /> <PackageReference Include="Moq" />
<PackageReference Include="System.Net.Http"/> <PackageReference Include="System.Net.Http"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" /> <PackageReference Include="nunit" />
<PackageReference Include="xunit.runner.visualstudio" /> <PackageReference Include="nunit3testadapter" />
<PackageReference Include="nunit.console" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
@@ -17,7 +17,7 @@ using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Test.Common.Baselined; using Microsoft.SqlTools.ServiceLayer.Test.Common.Baselined;
using Microsoft.SqlTools.ServiceLayer.Test.Common.Extensions; using Microsoft.SqlTools.ServiceLayer.Test.Common.Extensions;
using Xunit; using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.ObjectExplorer.ObjectExplorerService; using static Microsoft.SqlTools.ServiceLayer.ObjectExplorer.ObjectExplorerService;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
@@ -26,8 +26,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
{ {
private ObjectExplorerService _service = TestServiceProvider.Instance.ObjectExplorerService; private ObjectExplorerService _service = TestServiceProvider.Instance.ObjectExplorerService;
[Fact] [Test]
public async void CreateSessionAndExpandOnTheServerShouldReturnServerAsTheRoot() public async Task CreateSessionAndExpandOnTheServerShouldReturnServerAsTheRoot()
{ {
var query = ""; var query = "";
string databaseName = null; string databaseName = null;
@@ -37,8 +37,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
}); });
} }
[Fact] [Test]
public async void CreateSessionWithTempdbAndExpandOnTheServerShouldReturnServerAsTheRoot() public async Task CreateSessionWithTempdbAndExpandOnTheServerShouldReturnServerAsTheRoot()
{ {
var query = ""; var query = "";
string databaseName = "tempdb"; string databaseName = "tempdb";
@@ -48,8 +48,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
}); });
} }
[Fact] [Test]
public async void VerifyServerLogins() public async Task VerifyServerLogins()
{ {
var query = $@"If Exists (select loginname from master.dbo.syslogins var query = $@"If Exists (select loginname from master.dbo.syslogins
where name = 'OEServerLogin') where name = 'OEServerLogin')
@@ -77,8 +77,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
}); });
} }
[Fact] [Test]
public async void VerifyServerTriggers() public async Task VerifyServerTriggers()
{ {
var query = @"IF EXISTS (SELECT * FROM sys.server_triggers WHERE name = 'OE_ddl_trig_database') var query = @"IF EXISTS (SELECT * FROM sys.server_triggers WHERE name = 'OE_ddl_trig_database')
@@ -113,8 +113,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
}); });
} }
[Fact] [Test]
public async void CreateSessionAndExpandOnTheDatabaseShouldReturnDatabaseAsTheRoot() public async Task CreateSessionAndExpandOnTheDatabaseShouldReturnDatabaseAsTheRoot()
{ {
var query = ""; var query = "";
string databaseName = "#testDb#"; string databaseName = "#testDb#";
@@ -124,8 +124,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
}); });
} }
[Fact] [Test]
public async void RefreshNodeShouldGetTheDataFromDatabase() public async Task RefreshNodeShouldGetTheDataFromDatabase()
{ {
var query = "Create table t1 (c1 int)"; var query = "Create table t1 (c1 int)";
string databaseName = "#testDb#"; string databaseName = "#testDb#";
@@ -148,8 +148,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
/// Create a test database with prefix (OfflineDb). Create an oe session for master db and expand the new test db. /// Create a test database with prefix (OfflineDb). Create an oe session for master db and expand the new test db.
/// The expand should return an error that says database if offline /// The expand should return an error that says database if offline
/// </summary> /// </summary>
[Fact] [Test]
public async void ExpandOfflineDatabaseShouldReturnError() public async Task ExpandOfflineDatabaseShouldReturnError()
{ {
var query = "ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE"; var query = "ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE";
string databaseName = "master"; string databaseName = "master";
@@ -162,8 +162,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
}); });
} }
[Fact] [Test]
public async void RefreshShouldCleanTheCache() public async Task RefreshShouldCleanTheCache()
{ {
string query = @"Create table t1 (c1 int) string query = @"Create table t1 (c1 int)
GO GO
@@ -220,7 +220,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
var tableChildren = (await _service.ExpandNode(session, tablePath, true)).Nodes; var tableChildren = (await _service.ExpandNode(session, tablePath, true)).Nodes;
//Verify table is not returned //Verify table is not returned
Assert.Equal(tableChildren.Any(t => t.Label == tableName), !deleted); Assert.AreEqual(tableChildren.Any(t => t.Label == tableName), !deleted);
//Verify tables cache has items //Verify tables cache has items
rootChildrenCache = session.Root.GetChildren(); rootChildrenCache = session.Root.GetChildren();
@@ -228,8 +228,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
Assert.True(tablesCache.Any()); Assert.True(tablesCache.Any());
} }
[Fact] [Test]
public async void VerifyAllSqlObjects() public async Task VerifyAllSqlObjects()
{ {
var queryFileName = "AllSqlObjects.sql"; var queryFileName = "AllSqlObjects.sql";
string baselineFileName = "AllSqlObjects.txt"; string baselineFileName = "AllSqlObjects.txt";
@@ -237,9 +237,9 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
await TestServiceProvider.CalculateRunTime(() => VerifyObjectExplorerTest(databaseName, "AllSqlObjects", queryFileName, baselineFileName), true); await TestServiceProvider.CalculateRunTime(() => VerifyObjectExplorerTest(databaseName, "AllSqlObjects", queryFileName, baselineFileName), true);
} }
//[Fact] //[Test]
//This takes take long to run so not a good test for CI builds //This takes take long to run so not a good test for CI builds
public async void VerifySystemObjects() public async Task VerifySystemObjects()
{ {
string queryFileName = null; string queryFileName = null;
string baselineFileName = null; string baselineFileName = null;
@@ -299,19 +299,19 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
Assert.NotNull(session); Assert.NotNull(session);
Assert.NotNull(session.Root); Assert.NotNull(session.Root);
NodeInfo nodeInfo = session.Root.ToNodeInfo(); NodeInfo nodeInfo = session.Root.ToNodeInfo();
Assert.Equal(nodeInfo.IsLeaf, false); Assert.AreEqual(false, nodeInfo.IsLeaf);
NodeInfo databaseNode = null; NodeInfo databaseNode = null;
if (serverNode) if (serverNode)
{ {
Assert.Equal(nodeInfo.NodeType, NodeTypes.Server.ToString()); Assert.AreEqual(nodeInfo.NodeType, NodeTypes.Server.ToString());
var children = session.Root.Expand(new CancellationToken()); var children = session.Root.Expand(new CancellationToken());
//All server children should be folder nodes //All server children should be folder nodes
foreach (var item in children) foreach (var item in children)
{ {
Assert.Equal(item.NodeType, "Folder"); Assert.AreEqual("Folder", item.NodeType);
} }
var databasesRoot = children.FirstOrDefault(x => x.NodeTypeId == NodeTypes.Databases); var databasesRoot = children.FirstOrDefault(x => x.NodeTypeId == NodeTypes.Databases);
@@ -331,7 +331,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
} }
else else
{ {
Assert.Equal(nodeInfo.NodeType, NodeTypes.Database.ToString()); Assert.AreEqual(nodeInfo.NodeType, NodeTypes.Database.ToString());
databaseNode = session.Root.ToNodeInfo(); databaseNode = session.Root.ToNodeInfo();
Assert.True(databaseNode.Label.Contains(databaseName)); Assert.True(databaseNode.Label.Contains(databaseName));
var databasesChildren = (await _service.ExpandNode(session, databaseNode.NodePath)).Nodes; var databasesChildren = (await _service.ExpandNode(session, databaseNode.NodePath)).Nodes;
@@ -347,15 +347,15 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
Assert.NotNull(session); Assert.NotNull(session);
Assert.NotNull(session.Root); Assert.NotNull(session.Root);
NodeInfo nodeInfo = session.Root.ToNodeInfo(); NodeInfo nodeInfo = session.Root.ToNodeInfo();
Assert.Equal(nodeInfo.IsLeaf, false); Assert.AreEqual(false, nodeInfo.IsLeaf);
Assert.Equal(nodeInfo.NodeType, NodeTypes.Database.ToString()); Assert.AreEqual(nodeInfo.NodeType, NodeTypes.Database.ToString());
Assert.True(nodeInfo.Label.Contains(databaseName)); Assert.True(nodeInfo.Label.Contains(databaseName));
var children = (await _service.ExpandNode(session, session.Root.GetNodePath())).Nodes; var children = (await _service.ExpandNode(session, session.Root.GetNodePath())).Nodes;
//All server children should be folder nodes //All server children should be folder nodes
foreach (var item in children) foreach (var item in children)
{ {
Assert.Equal(item.NodeType, "Folder"); Assert.AreEqual("Folder", item.NodeType);
} }
var tablesRoot = children.FirstOrDefault(x => x.Label == SR.SchemaHierarchy_Tables); var tablesRoot = children.FirstOrDefault(x => x.Label == SR.SchemaHierarchy_Tables);
@@ -18,7 +18,7 @@ using Microsoft.SqlTools.ServiceLayer.Profiler;
using Microsoft.SqlTools.ServiceLayer.Profiler.Contracts; using Microsoft.SqlTools.ServiceLayer.Profiler.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Profiler namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Profiler
{ {
@@ -27,7 +27,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Profiler
/// <summary> /// <summary>
/// Verify that a start profiling request starts a profiling session /// Verify that a start profiling request starts a profiling session
/// </summary> /// </summary>
//[Fact] //[Test]
public async Task TestHandleStartAndStopProfilingRequests() public async Task TestHandleStartAndStopProfilingRequests()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -76,7 +76,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Profiler
/// <summary> /// <summary>
/// Verify the profiler service XEvent session factory /// Verify the profiler service XEvent session factory
/// </summary> /// </summary>
//[Fact] //[Test]
public void TestCreateXEventSession() public void TestCreateXEventSession()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -8,7 +8,7 @@ using System.Data.Common;
using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility; using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage; using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataStorage namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataStorage
{ {
@@ -30,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt
/// <summary> /// <summary>
/// Validate GetBytesWithMaxCapacity /// Validate GetBytesWithMaxCapacity
/// </summary> /// </summary>
[Fact] [Test]
public void GetBytesWithMaxCapacityTest() public void GetBytesWithMaxCapacityTest()
{ {
var storageReader = GetTestStorageDataReader( var storageReader = GetTestStorageDataReader(
@@ -47,7 +47,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt
/// <summary> /// <summary>
/// Validate GetCharsWithMaxCapacity /// Validate GetCharsWithMaxCapacity
/// </summary> /// </summary>
[Fact] [Test]
public void GetCharsWithMaxCapacityTest() public void GetCharsWithMaxCapacityTest()
{ {
var storageReader = GetTestStorageDataReader( var storageReader = GetTestStorageDataReader(
@@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt
/// <summary> /// <summary>
/// Validate GetXmlWithMaxCapacity /// Validate GetXmlWithMaxCapacity
/// </summary> /// </summary>
[Fact] [Test]
public void GetXmlWithMaxCapacityTest() public void GetXmlWithMaxCapacityTest()
{ {
var storageReader = GetTestStorageDataReader( var storageReader = GetTestStorageDataReader(
@@ -86,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt
/// <summary> /// <summary>
/// Validate StringWriterWithMaxCapacity Write test /// Validate StringWriterWithMaxCapacity Write test
/// </summary> /// </summary>
[Fact] [Test]
public void StringWriterWithMaxCapacityTest() public void StringWriterWithMaxCapacityTest()
{ {
var writer = new StorageDataReader.StringWriterWithMaxCapacity(null, 4); var writer = new StorageDataReader.StringWriterWithMaxCapacity(null, 4);
@@ -6,19 +6,20 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Data.Common; using System.Data.Common;
using System.Linq;
using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility; using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage; using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.SqlContext; using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
{ {
public class ExecuteTests public class ExecuteTests
{ {
[Fact] [Test]
public void RollbackTransactionFailsWithoutBeginTransaction() public void RollbackTransactionFailsWithoutBeginTransaction()
{ {
const string refactorText = "ROLLBACK TRANSACTION"; const string refactorText = "ROLLBACK TRANSACTION";
@@ -37,7 +38,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
Assert.True(query.Batches[0].HasError); Assert.True(query.Batches[0].HasError);
} }
[Fact] [Test]
public void TransactionsSucceedAcrossQueries() public void TransactionsSucceedAcrossQueries()
{ {
const string beginText = "BEGIN TRANSACTION"; const string beginText = "BEGIN TRANSACTION";
@@ -56,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
Assert.False(rollbackQuery.Batches[0].HasError); Assert.False(rollbackQuery.Batches[0].HasError);
} }
[Fact] [Test]
public void TempTablesPersistAcrossQueries() public void TempTablesPersistAcrossQueries()
{ {
const string createTempText = "CREATE TABLE #someTempTable (id int)"; const string createTempText = "CREATE TABLE #someTempTable (id int)";
@@ -75,7 +76,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
Assert.False(insertTempQuery.Batches[0].HasError); Assert.False(insertTempQuery.Batches[0].HasError);
} }
[Fact] [Test]
public void DatabaseChangesWhenCallingUseDatabase() public void DatabaseChangesWhenCallingUseDatabase()
{ {
const string master = "master"; const string master = "master";
@@ -92,27 +93,15 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
// If I use master, the current database should be master // If I use master, the current database should be master
CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory); CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory);
Assert.Equal(master, connInfo.ConnectionDetails.DatabaseName); Assert.AreEqual(master, connInfo.ConnectionDetails.DatabaseName);
// If I use tempdb, the current database should be tempdb // If I use tempdb, the current database should be tempdb
CreateAndExecuteQuery(string.Format(useQuery, tempdb), connInfo, fileStreamFactory); CreateAndExecuteQuery(string.Format(useQuery, tempdb), connInfo, fileStreamFactory);
Assert.Equal(tempdb, connInfo.ConnectionDetails.DatabaseName); Assert.AreEqual(tempdb, connInfo.ConnectionDetails.DatabaseName);
// If I switch back to master, the current database should be master // If I switch back to master, the current database should be master
CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory); CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory);
Assert.Equal(master, connInfo.ConnectionDetails.DatabaseName); Assert.AreEqual(master, connInfo.ConnectionDetails.DatabaseName);
}
[Fact]
public void TestBatchExecutionTime() {
var result = LiveConnectionHelper.InitLiveConnectionInfo();
ConnectionInfo connInfo = result.ConnectionInfo;
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = CreateAndExecuteQuery("select * from sys.databases", connInfo, fileStreamFactory);
DateTime elapsedTime = Convert.ToDateTime(query.Batches[0].ExecutionElapsedTime);
Query mutipleQuery = CreateAndExecuteQuery("select * from sys.databases\r\nGO 15", connInfo, fileStreamFactory);
DateTime multipleElapsedTime = Convert.ToDateTime(mutipleQuery.Batches[0].ExecutionElapsedTime);
Assert.True(multipleElapsedTime > elapsedTime);
} }
public static Query CreateAndExecuteQuery(string queryText, ConnectionInfo connectionInfo, IFileStreamFactory fileStreamFactory, bool IsSqlCmd = false) public static Query CreateAndExecuteQuery(string queryText, ConnectionInfo connectionInfo, IFileStreamFactory fileStreamFactory, bool IsSqlCmd = false)
@@ -9,13 +9,13 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using System; using System;
using System.IO; using System.IO;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
{ {
public class SqlCmdExecutionTest public class SqlCmdExecutionTest
{ {
[Fact] [Test]
public void TestConnectSqlCmdCommand() public void TestConnectSqlCmdCommand()
{ {
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -41,7 +41,7 @@ GO";
Assert.True(query.Batches[0].HasError, "Query should have error"); Assert.True(query.Batches[0].HasError, "Query should have error");
} }
[Fact] [Test]
public void TestOnErrorSqlCmdCommand() public void TestOnErrorSqlCmdCommand()
{ {
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -73,7 +73,7 @@ GO";
Assert.False(query.Batches[1].HasExecuted, "last batch should NOT be executed"); Assert.False(query.Batches[1].HasExecuted, "last batch should NOT be executed");
} }
[Fact] [Test]
public void TestIncludeSqlCmdCommand() public void TestIncludeSqlCmdCommand()
{ {
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -12,7 +12,7 @@ using Moq;
using System; using System;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SchemaCompare namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SchemaCompare
{ {
@@ -265,8 +265,8 @@ END
{ {
// validate script generation failed because there were no differences // validate script generation failed because there were no differences
Assert.False(generateScriptOperation1.ScriptGenerationResult.Success); Assert.False(generateScriptOperation1.ScriptGenerationResult.Success);
Assert.Equal("Performing script generation is not possible for this comparison result.", generateScriptOperation1.ScriptGenerationResult.Message); Assert.AreEqual("Performing script generation is not possible for this comparison result.", generateScriptOperation1.ScriptGenerationResult.Message);
Assert.Equal("Performing script generation is not possible for this comparison result.", ex.Message); Assert.AreEqual("Performing script generation is not possible for this comparison result.", ex.Message);
} }
var schemaCompareParams2 = new SchemaCompareParams var schemaCompareParams2 = new SchemaCompareParams
@@ -309,8 +309,8 @@ END
/// <summary> /// <summary>
/// Verify the schema compare request comparing two dacpacs with and without ignore column option /// Verify the schema compare request comparing two dacpacs with and without ignore column option
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareDacpacToDacpacOptions() public async Task SchemaCompareDacpacToDacpacOptions()
{ {
await SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions()); await SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions());
} }
@@ -318,8 +318,8 @@ END
/// <summary> /// <summary>
/// Verify the schema compare request comparing two dacpacs with and excluding table valued functions /// Verify the schema compare request comparing two dacpacs with and excluding table valued functions
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareDacpacToDacpacObjectTypes() public async Task SchemaCompareDacpacToDacpacObjectTypes()
{ {
await SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions()); await SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions());
} }
@@ -327,8 +327,8 @@ END
/// <summary> /// <summary>
/// Verify the schema compare request comparing two databases with and without ignore column option /// Verify the schema compare request comparing two databases with and without ignore column option
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareDatabaseToDatabaseOptions() public async Task SchemaCompareDatabaseToDatabaseOptions()
{ {
await SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions()); await SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions());
} }
@@ -336,8 +336,8 @@ END
/// <summary> /// <summary>
/// Verify the schema compare request comparing two databases with and excluding table valued functions /// Verify the schema compare request comparing two databases with and excluding table valued functions
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareDatabaseToDatabaseObjectTypes() public async Task SchemaCompareDatabaseToDatabaseObjectTypes()
{ {
await SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions()); await SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions());
} }
@@ -345,8 +345,8 @@ END
/// <summary> /// <summary>
/// Verify the schema compare script generation comparing dacpac and db with and without ignore column option /// Verify the schema compare script generation comparing dacpac and db with and without ignore column option
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareGenerateScriptDacpacToDatabaseOptions() public async Task SchemaCompareGenerateScriptDacpacToDatabaseOptions()
{ {
await SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabaseWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions()); await SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabaseWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions());
} }
@@ -354,8 +354,8 @@ END
/// <summary> /// <summary>
/// Verify the schema compare script generation comparing dacpac and db with and excluding table valued function /// Verify the schema compare script generation comparing dacpac and db with and excluding table valued function
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareGenerateScriptDacpacToDatabaseObjectTypes() public async Task SchemaCompareGenerateScriptDacpacToDatabaseObjectTypes()
{ {
await SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabaseWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions()); await SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabaseWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions());
} }
@@ -363,7 +363,7 @@ END
/// <summary> /// <summary>
/// Verify the schema compare default creation test /// Verify the schema compare default creation test
/// </summary> /// </summary>
[Fact] [Test]
public void ValidateSchemaCompareOptionsDefaultAgainstDacFx() public void ValidateSchemaCompareOptionsDefaultAgainstDacFx()
{ {
DeploymentOptions deployOptions = new DeploymentOptions(); DeploymentOptions deployOptions = new DeploymentOptions();
@@ -384,8 +384,8 @@ END
/// <summary> /// <summary>
/// Verify the schema compare default creation test /// Verify the schema compare default creation test
/// </summary> /// </summary>
[Fact] [Test]
public async void ValidateSchemaCompareGetDefaultOptionsCallFromService() public async Task ValidateSchemaCompareGetDefaultOptionsCallFromService()
{ {
DeploymentOptions deployOptions = new DeploymentOptions(); DeploymentOptions deployOptions = new DeploymentOptions();
var schemaCompareRequestContext = new Mock<RequestContext<SchemaCompareOptionsResult>>(); var schemaCompareRequestContext = new Mock<RequestContext<SchemaCompareOptionsResult>>();
@@ -16,8 +16,9 @@ using Microsoft.Data.SqlClient;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using NUnit.Framework;
using System.Diagnostics;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SchemaCompare namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SchemaCompare
{ {
public class SchemaCompareServiceTests public class SchemaCompareServiceTests
@@ -78,8 +79,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare request comparing two dacpacs /// Verify the schema compare request comparing two dacpacs
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareDacpacToDacpac() public async Task SchemaCompareDacpacToDacpac()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
@@ -122,8 +123,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare request comparing a two databases /// Verify the schema compare request comparing a two databases
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareDatabaseToDatabase() public async Task SchemaCompareDatabaseToDatabase()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -161,8 +162,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare request comparing a database to a dacpac /// Verify the schema compare request comparing a database to a dacpac
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareDatabaseToDacpac() public async Task SchemaCompareDatabaseToDacpac()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -202,8 +203,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare generate script request comparing a database to a database /// Verify the schema compare generate script request comparing a database to a database
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareGenerateScriptDatabaseToDatabase() public async Task SchemaCompareGenerateScriptDatabaseToDatabase()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
var schemaCompareRequestContext = new Mock<RequestContext<SchemaCompareResult>>(); var schemaCompareRequestContext = new Mock<RequestContext<SchemaCompareResult>>();
@@ -249,8 +250,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare generate script request comparing a dacpac to a database /// Verify the schema compare generate script request comparing a dacpac to a database
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareGenerateScriptDacpacToDatabase() public async Task SchemaCompareGenerateScriptDacpacToDatabase()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -300,8 +301,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare publish changes request comparing a dacpac to a database /// Verify the schema compare publish changes request comparing a dacpac to a database
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaComparePublishChangesDacpacToDatabase() public async Task SchemaComparePublishChangesDacpacToDatabase()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -349,14 +350,14 @@ WITH VALUES
SchemaComparePublishChangesOperation publishChangesOperation = new SchemaComparePublishChangesOperation(publishChangesParams, schemaCompareOperation.ComparisonResult); SchemaComparePublishChangesOperation publishChangesOperation = new SchemaComparePublishChangesOperation(publishChangesParams, schemaCompareOperation.ComparisonResult);
publishChangesOperation.Execute(TaskExecutionMode.Execute); publishChangesOperation.Execute(TaskExecutionMode.Execute);
Assert.True(publishChangesOperation.PublishResult.Success); Assert.True(publishChangesOperation.PublishResult.Success);
Assert.Empty(publishChangesOperation.PublishResult.Errors); Assert.That(publishChangesOperation.PublishResult.Errors, Is.Empty);
// Verify that there are no differences after the publish by running the comparison again // Verify that there are no differences after the publish by running the comparison again
schemaCompareOperation.Execute(TaskExecutionMode.Execute); schemaCompareOperation.Execute(TaskExecutionMode.Execute);
Assert.True(schemaCompareOperation.ComparisonResult.IsValid); Assert.True(schemaCompareOperation.ComparisonResult.IsValid);
Assert.True(schemaCompareOperation.ComparisonResult.IsEqual); Assert.True(schemaCompareOperation.ComparisonResult.IsEqual);
Assert.Empty(schemaCompareOperation.ComparisonResult.Differences); Assert.That(schemaCompareOperation.ComparisonResult.Differences, Is.Empty);
// cleanup // cleanup
SchemaCompareTestUtils.VerifyAndCleanup(sourceDacpacFilePath); SchemaCompareTestUtils.VerifyAndCleanup(sourceDacpacFilePath);
@@ -371,8 +372,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare publish changes request comparing a database to a database /// Verify the schema compare publish changes request comparing a database to a database
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaComparePublishChangesDatabaseToDatabase() public async Task SchemaComparePublishChangesDatabaseToDatabase()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -416,14 +417,14 @@ WITH VALUES
SchemaComparePublishChangesOperation publishChangesOperation = new SchemaComparePublishChangesOperation(publishChangesParams, schemaCompareOperation.ComparisonResult); SchemaComparePublishChangesOperation publishChangesOperation = new SchemaComparePublishChangesOperation(publishChangesParams, schemaCompareOperation.ComparisonResult);
publishChangesOperation.Execute(TaskExecutionMode.Execute); publishChangesOperation.Execute(TaskExecutionMode.Execute);
Assert.True(publishChangesOperation.PublishResult.Success); Assert.True(publishChangesOperation.PublishResult.Success);
Assert.Empty(publishChangesOperation.PublishResult.Errors); Assert.That(publishChangesOperation.PublishResult.Errors, Is.Empty);
// Verify that there are no differences after the publish by running the comparison again // Verify that there are no differences after the publish by running the comparison again
schemaCompareOperation.Execute(TaskExecutionMode.Execute); schemaCompareOperation.Execute(TaskExecutionMode.Execute);
Assert.True(schemaCompareOperation.ComparisonResult.IsValid); Assert.True(schemaCompareOperation.ComparisonResult.IsValid);
Assert.True(schemaCompareOperation.ComparisonResult.IsEqual); Assert.True(schemaCompareOperation.ComparisonResult.IsEqual);
Assert.Empty(schemaCompareOperation.ComparisonResult.Differences); Assert.That(schemaCompareOperation.ComparisonResult.Differences, Is.Empty);
} }
finally finally
{ {
@@ -435,8 +436,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare Scmp File Save for database endpoints /// Verify the schema compare Scmp File Save for database endpoints
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareSaveScmpFileForDatabases() public async Task SchemaCompareSaveScmpFileForDatabases()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
@@ -465,8 +466,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare Scmp File Save for dacpac endpoints /// Verify the schema compare Scmp File Save for dacpac endpoints
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareSaveScmpFileForDacpacs() public async Task SchemaCompareSaveScmpFileForDacpacs()
{ {
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget"); SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget");
@@ -497,8 +498,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare Scmp File Save for dacpac and db endpoints combination /// Verify the schema compare Scmp File Save for dacpac and db endpoints combination
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareSaveScmpFileForDacpacToDB() public async Task SchemaCompareSaveScmpFileForDacpacToDB()
{ {
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget"); SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget");
@@ -528,8 +529,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify opening an scmp comparing two databases /// Verify opening an scmp comparing two databases
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareOpenScmpDatabaseToDatabaseRequest() public async Task SchemaCompareOpenScmpDatabaseToDatabaseRequest()
{ {
await CreateAndOpenScmp(SchemaCompareEndpointType.Database, SchemaCompareEndpointType.Database); await CreateAndOpenScmp(SchemaCompareEndpointType.Database, SchemaCompareEndpointType.Database);
} }
@@ -537,8 +538,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify opening an scmp comparing a dacpac and database /// Verify opening an scmp comparing a dacpac and database
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareOpenScmpDacpacToDatabaseRequest() public async Task SchemaCompareOpenScmpDacpacToDatabaseRequest()
{ {
await CreateAndOpenScmp(SchemaCompareEndpointType.Dacpac, SchemaCompareEndpointType.Database); await CreateAndOpenScmp(SchemaCompareEndpointType.Dacpac, SchemaCompareEndpointType.Database);
} }
@@ -546,8 +547,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify opening an scmp comparing two dacpacs /// Verify opening an scmp comparing two dacpacs
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareOpenScmpDacpacToDacpacRequest() public async Task SchemaCompareOpenScmpDacpacToDacpacRequest()
{ {
await CreateAndOpenScmp(SchemaCompareEndpointType.Dacpac, SchemaCompareEndpointType.Dacpac); await CreateAndOpenScmp(SchemaCompareEndpointType.Dacpac, SchemaCompareEndpointType.Dacpac);
} }
@@ -555,7 +556,7 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare Service Calls ends to end /// Verify the schema compare Service Calls ends to end
/// </summary> /// </summary>
[Fact] [Test]
public async Task VerifySchemaCompareServiceCalls() public async Task VerifySchemaCompareServiceCalls()
{ {
string operationId = Guid.NewGuid().ToString(); string operationId = Guid.NewGuid().ToString();
@@ -695,8 +696,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare cancel /// Verify the schema compare cancel
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareCancelCompareOperation() public async Task SchemaCompareCancelCompareOperation()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -746,8 +747,8 @@ WITH VALUES
/// test to verify recent dacfx bugs /// test to verify recent dacfx bugs
/// does not need all combinations of db and dacpacs /// does not need all combinations of db and dacpacs
/// </summary> /// </summary>
//[Fact] disabling the failing test is failing now. //[Test] disabling the failing test is failing now.
public async void SchemaCompareCEKAndFilegoupTest() public async Task SchemaCompareCEKAndFilegoupTest()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, CreateKey, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, CreateKey, "SchemaCompareSource");
@@ -819,8 +820,8 @@ WITH VALUES
/// <summary> /// <summary>
/// Verify the schema compare request with failing exclude request because of dependencies and that include will include dependencies /// Verify the schema compare request with failing exclude request because of dependencies and that include will include dependencies
/// </summary> /// </summary>
[Fact] [Test]
public async void SchemaCompareIncludeExcludeWithDependencies() public async Task SchemaCompareIncludeExcludeWithDependencies()
{ {
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceIncludeExcludeScript, "SchemaCompareSource"); SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceIncludeExcludeScript, "SchemaCompareSource");
@@ -1031,7 +1032,7 @@ WITH VALUES
// create a comparison and exclude the first difference // create a comparison and exclude the first difference
SchemaComparison compare = new SchemaComparison(sourceEndpoint, targetEndpoint); SchemaComparison compare = new SchemaComparison(sourceEndpoint, targetEndpoint);
SchemaComparisonResult result = compare.Compare(); SchemaComparisonResult result = compare.Compare();
Assert.NotEmpty(result.Differences); Assert.That(result.Differences, Is.Not.Empty);
SchemaDifference difference = result.Differences.First(); SchemaDifference difference = result.Differences.First();
if (difference.SourceObject != null) if (difference.SourceObject != null)
{ {
@@ -1059,10 +1060,10 @@ WITH VALUES
Assert.NotNull(schemaCompareOpenScmpOperation.Result); Assert.NotNull(schemaCompareOpenScmpOperation.Result);
Assert.True(schemaCompareOpenScmpOperation.Result.Success); Assert.True(schemaCompareOpenScmpOperation.Result.Success);
Assert.NotEmpty(schemaCompareOpenScmpOperation.Result.ExcludedSourceElements); Assert.That(schemaCompareOpenScmpOperation.Result.ExcludedSourceElements, Is.Not.Empty);
Assert.Equal(1, schemaCompareOpenScmpOperation.Result.ExcludedSourceElements.Count()); Assert.AreEqual(1, schemaCompareOpenScmpOperation.Result.ExcludedSourceElements.Count());
Assert.Empty(schemaCompareOpenScmpOperation.Result.ExcludedTargetElements); Assert.That(schemaCompareOpenScmpOperation.Result.ExcludedTargetElements, Is.Empty);
Assert.Equal(targetDb.DatabaseName, schemaCompareOpenScmpOperation.Result.OriginalTargetName); Assert.AreEqual(targetDb.DatabaseName, schemaCompareOpenScmpOperation.Result.OriginalTargetName);
ValidateResultEndpointInfo(sourceEndpoint, schemaCompareOpenScmpOperation.Result.SourceEndpointInfo, sourceDb.ConnectionString); ValidateResultEndpointInfo(sourceEndpoint, schemaCompareOpenScmpOperation.Result.SourceEndpointInfo, sourceDb.ConnectionString);
ValidateResultEndpointInfo(targetEndpoint, schemaCompareOpenScmpOperation.Result.TargetEndpointInfo, targetDb.ConnectionString); ValidateResultEndpointInfo(targetEndpoint, schemaCompareOpenScmpOperation.Result.TargetEndpointInfo, targetDb.ConnectionString);
@@ -1093,13 +1094,13 @@ WITH VALUES
if (resultEndpoint.EndpointType == SchemaCompareEndpointType.Dacpac) if (resultEndpoint.EndpointType == SchemaCompareEndpointType.Dacpac)
{ {
SchemaCompareDacpacEndpoint dacpacEndpoint = originalEndpoint as SchemaCompareDacpacEndpoint; SchemaCompareDacpacEndpoint dacpacEndpoint = originalEndpoint as SchemaCompareDacpacEndpoint;
Assert.Equal(dacpacEndpoint.FilePath, resultEndpoint.PackageFilePath); Assert.AreEqual(dacpacEndpoint.FilePath, resultEndpoint.PackageFilePath);
} }
else else
{ {
SchemaCompareDatabaseEndpoint databaseEndpoint = originalEndpoint as SchemaCompareDatabaseEndpoint; SchemaCompareDatabaseEndpoint databaseEndpoint = originalEndpoint as SchemaCompareDatabaseEndpoint;
Assert.Equal(databaseEndpoint.DatabaseName, resultEndpoint.DatabaseName); Assert.AreEqual(databaseEndpoint.DatabaseName, resultEndpoint.DatabaseName);
Assert.Contains(resultEndpoint.ConnectionDetails.ConnectionString, connectionString); // connectionString has password but resultEndpoint doesn't Assert.That(connectionString, Does.Contain(resultEndpoint.ConnectionDetails.ConnectionString), "connectionString has password but resultEndpoint doesn't");
} }
} }
@@ -1117,20 +1118,20 @@ WITH VALUES
private void ValidateDiffEntryObjects(string[] diffObjectName, string diffObjectTypeType, TSqlObject dacfxObject) private void ValidateDiffEntryObjects(string[] diffObjectName, string diffObjectTypeType, TSqlObject dacfxObject)
{ {
Assert.Equal(dacfxObject.Name.Parts.Count, diffObjectName.Length); Assert.AreEqual(dacfxObject.Name.Parts.Count, diffObjectName.Length);
for (int i = 0; i < diffObjectName.Length; i++) for (int i = 0; i < diffObjectName.Length; i++)
{ {
Assert.Equal(dacfxObject.Name.Parts[i], diffObjectName[i]); Assert.AreEqual(dacfxObject.Name.Parts[i], diffObjectName[i]);
} }
var dacFxExcludedObject = new SchemaComparisonExcludedObjectId(dacfxObject.ObjectType, dacfxObject.Name); var dacFxExcludedObject = new SchemaComparisonExcludedObjectId(dacfxObject.ObjectType, dacfxObject.Name);
var excludedObject = new SchemaComparisonExcludedObjectId(diffObjectTypeType, new ObjectIdentifier(diffObjectName)); var excludedObject = new SchemaComparisonExcludedObjectId(diffObjectTypeType, new ObjectIdentifier(diffObjectName));
Assert.Equal(dacFxExcludedObject.Identifier.ToString(), excludedObject.Identifier.ToString()); Assert.AreEqual(dacFxExcludedObject.Identifier.ToString(), excludedObject.Identifier.ToString());
Assert.Equal(dacFxExcludedObject.TypeName, excludedObject.TypeName); Assert.AreEqual(dacFxExcludedObject.TypeName, excludedObject.TypeName);
string dacFxType = dacFxExcludedObject.TypeName; string dacFxType = dacFxExcludedObject.TypeName;
Assert.Equal(dacFxType, diffObjectTypeType); Assert.AreEqual(dacFxType, diffObjectTypeType);
} }
private void CreateAndValidateScmpFile(SchemaCompareEndpointInfo sourceInfo, SchemaCompareEndpointInfo targetInfo, bool isSourceDb, bool isTargetDb) private void CreateAndValidateScmpFile(SchemaCompareEndpointInfo sourceInfo, SchemaCompareEndpointInfo targetInfo, bool isSourceDb, bool isTargetDb)
@@ -1236,7 +1237,8 @@ WITH VALUES
private void ValidateTask(string expectedTaskName) private void ValidateTask(string expectedTaskName)
{ {
int retry = 5; // upped the retry count to 20 so tests pass against remote servers more readily
int retry = 20;
Assert.True(TaskService.Instance.TaskManager.Tasks.Count == 1, $"Expected 1 task but found {TaskService.Instance.TaskManager.Tasks.Count} tasks"); Assert.True(TaskService.Instance.TaskManager.Tasks.Count == 1, $"Expected 1 task but found {TaskService.Instance.TaskManager.Tasks.Count} tasks");
while (TaskService.Instance.TaskManager.Tasks.Any() && retry > 0) while (TaskService.Instance.TaskManager.Tasks.Any() && retry > 0)
{ {
@@ -1259,6 +1261,7 @@ WITH VALUES
retry--; retry--;
} }
Assert.False(TaskService.Instance.TaskManager.Tasks.Any(), $"No tasks were expected to exist but had {TaskService.Instance.TaskManager.Tasks.Count} [{string.Join(",", TaskService.Instance.TaskManager.Tasks.Select(t => t.TaskId))}]"); Assert.False(TaskService.Instance.TaskManager.Tasks.Any(), $"No tasks were expected to exist but had {TaskService.Instance.TaskManager.Tasks.Count} [{string.Join(",", TaskService.Instance.TaskManager.Tasks.Select(t => t.TaskId))}]");
Console.WriteLine($"ValidateTask{expectedTaskName} completed at retry = {retry}");
TaskService.Instance.TaskManager.Reset(); TaskService.Instance.TaskManager.Reset();
} }
} }
@@ -15,7 +15,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper; using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
@@ -76,8 +76,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
/// <summary> /// <summary>
/// Verify the script object request /// Verify the script object request
/// </summary> /// </summary>
[Fact] [Test]
public async void ScriptingScript() public async Task ScriptingScript()
{ {
foreach (string obj in objects) foreach (string obj in objects)
{ {
@@ -86,8 +86,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
} }
} }
[Fact] [Test]
public async void VerifyScriptAsCreateTable() public async Task VerifyScriptAsCreateTable()
{ {
string query = @"CREATE TABLE testTable1 (c1 int) string query = @"CREATE TABLE testTable1 (c1 int)
GO GO
@@ -110,8 +110,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAsForMultipleObjects(query, new List<ScriptingObject> { scriptingObject }, scriptCreateDrop, expectedScripts); await VerifyScriptAsForMultipleObjects(query, new List<ScriptingObject> { scriptingObject }, scriptCreateDrop, expectedScripts);
} }
[Fact] [Test]
public async void VerifyScriptAsExecuteTableFailes() public async Task VerifyScriptAsExecuteTableFailes()
{ {
string query = "CREATE TABLE testTable1 (c1 int)"; string query = "CREATE TABLE testTable1 (c1 int)";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Execute; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Execute;
@@ -125,8 +125,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
} }
[Fact] [Test]
public async void VerifyScriptAsAlter() public async Task VerifyScriptAsAlter()
{ {
string query = @"CREATE PROCEDURE testSp1 @StartProductID [int] AS BEGIN Select * from sys.all_columns END string query = @"CREATE PROCEDURE testSp1 @StartProductID [int] AS BEGIN Select * from sys.all_columns END
GO GO
@@ -168,8 +168,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
} }
// TODO: Fix flaky test. See https://github.com/Microsoft/sqltoolsservice/issues/631 // TODO: Fix flaky test. See https://github.com/Microsoft/sqltoolsservice/issues/631
// [Fact] // [Test]
public async void VerifyScriptAsExecuteStoredProcedure() public async Task VerifyScriptAsExecuteStoredProcedure()
{ {
string query = @"CREATE PROCEDURE testSp1 string query = @"CREATE PROCEDURE testSp1
@BusinessEntityID [int], @BusinessEntityID [int],
@@ -192,8 +192,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
} }
[Fact] [Test]
public async void VerifyScriptAsSelectTable() public async Task VerifyScriptAsSelectTable()
{ {
string query = "CREATE TABLE testTable1 (c1 int)"; string query = "CREATE TABLE testTable1 (c1 int)";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Select; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Select;
@@ -208,8 +208,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
} }
[Fact] [Test]
public async void VerifyScriptAsCreateView() public async Task VerifyScriptAsCreateView()
{ {
string query = "CREATE VIEW testView1 AS SELECT * from sys.all_columns"; string query = "CREATE VIEW testView1 AS SELECT * from sys.all_columns";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Create; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Create;
@@ -224,8 +224,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
} }
[Fact] [Test]
public async void VerifyScriptAsCreateStoredProcedure() public async Task VerifyScriptAsCreateStoredProcedure()
{ {
string query = "CREATE PROCEDURE testSp1 AS BEGIN Select * from sys.all_columns END"; string query = "CREATE PROCEDURE testSp1 AS BEGIN Select * from sys.all_columns END";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Create; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Create;
@@ -240,8 +240,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
} }
[Fact] [Test]
public async void VerifyScriptAsDropTable() public async Task VerifyScriptAsDropTable()
{ {
string query = "CREATE TABLE testTable1 (c1 int)"; string query = "CREATE TABLE testTable1 (c1 int)";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Delete; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Delete;
@@ -256,8 +256,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
} }
[Fact] [Test]
public async void VerifyScriptAsDropView() public async Task VerifyScriptAsDropView()
{ {
string query = "CREATE VIEW testView1 AS SELECT * from sys.all_columns"; string query = "CREATE VIEW testView1 AS SELECT * from sys.all_columns";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Delete; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Delete;
@@ -272,8 +272,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
} }
[Fact] [Test]
public async void VerifyScriptAsDropStoredProcedure() public async Task VerifyScriptAsDropStoredProcedure()
{ {
string query = "CREATE PROCEDURE testSp1 AS BEGIN Select * from sys.all_columns END"; string query = "CREATE PROCEDURE testSp1 AS BEGIN Select * from sys.all_columns END";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Delete; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Delete;
@@ -14,7 +14,7 @@ using Microsoft.SqlTools.ServiceLayer.Security.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper; using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security
@@ -27,7 +27,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security
/// <summary> /// <summary>
/// TestHandleCreateCredentialRequest /// TestHandleCreateCredentialRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleCreateCredentialRequest() public async Task TestHandleCreateCredentialRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -49,7 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security
/// <summary> /// <summary>
/// TestHandleUpdateCredentialRequest /// TestHandleUpdateCredentialRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleUpdateCredentialRequest() public async Task TestHandleUpdateCredentialRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security
/// <summary> /// <summary>
/// TestHandleDeleteCredentialRequest /// TestHandleDeleteCredentialRequest
/// </summary> /// </summary>
[Fact] [Test]
public async Task TestHandleDeleteCredentialRequest() public async Task TestHandleDeleteCredentialRequest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -13,22 +13,22 @@ using Moq;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServices namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServices
{ {
public class ServerConfigurationsServiceTests public class ServerConfigurationsServiceTests
{ {
[Fact] [Test]
public async void VerifyListingConfigs() public async Task VerifyListingConfigs()
{ {
List<ServerConfigProperty> configs = await GetAllConfigs(); List<ServerConfigProperty> configs = await GetAllConfigs();
Assert.NotNull(configs); Assert.NotNull(configs);
Assert.True(configs.Count > 0); Assert.True(configs.Count > 0);
} }
[Fact] [Test]
public async void VerifyUpdatingConfigs() public async Task VerifyUpdatingConfigs()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{ {
@@ -59,14 +59,14 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServic
await ServerConfigService.Instance.HandleServerConfigViewRequest(requestParams, requestContext.Object); await ServerConfigService.Instance.HandleServerConfigViewRequest(requestParams, requestContext.Object);
Assert.NotNull(result); Assert.NotNull(result);
Assert.Equal(result.ConfigProperty.ConfigValue, sampleConfig.ConfigValue); Assert.AreEqual(result.ConfigProperty.ConfigValue, sampleConfig.ConfigValue);
await ServerConfigService.Instance.HandleServerConfigUpdateRequest(updateRequestParams, updateRequestContext.Object); await ServerConfigService.Instance.HandleServerConfigUpdateRequest(updateRequestParams, updateRequestContext.Object);
Assert.NotNull(updateResult); Assert.NotNull(updateResult);
Assert.Equal(updateResult.ConfigProperty.ConfigValue, newValue); Assert.AreEqual(updateResult.ConfigProperty.ConfigValue, newValue);
updateRequestParams.ConfigValue = sampleConfig.ConfigValue; updateRequestParams.ConfigValue = sampleConfig.ConfigValue;
await ServerConfigService.Instance.HandleServerConfigUpdateRequest(updateRequestParams, updateRequestContext.Object); await ServerConfigService.Instance.HandleServerConfigUpdateRequest(updateRequestParams, updateRequestContext.Object);
Assert.NotNull(updateResult); Assert.NotNull(updateResult);
Assert.Equal(updateResult.ConfigProperty.ConfigValue, sampleConfig.ConfigValue); Assert.AreEqual(updateResult.ConfigProperty.ConfigValue, sampleConfig.ConfigValue);
ServerConfigService.Instance.ConnectionServiceInstance.Disconnect(new DisconnectParams ServerConfigService.Instance.ConnectionServiceInstance.Disconnect(new DisconnectParams
{ {
OwnerUri = queryTempFile.FilePath, OwnerUri = queryTempFile.FilePath,
@@ -97,8 +97,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServic
} }
[Fact] [Test]
public async void VerifyConfigViewRequestSendErrorGivenInvalidConnection() public async Task VerifyConfigViewRequestSendErrorGivenInvalidConnection()
{ {
ServerConfigViewResponseParams result = null; ServerConfigViewResponseParams result = null;
var requestContext = RequestContextMocks.Create<ServerConfigViewResponseParams>(r => result = r).AddErrorHandling(null); var requestContext = RequestContextMocks.Create<ServerConfigViewResponseParams>(r => result = r).AddErrorHandling(null);
@@ -113,8 +113,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServic
requestContext.Verify(x => x.SendError(It.IsAny<Exception>())); requestContext.Verify(x => x.SendError(It.IsAny<Exception>()));
} }
[Fact] [Test]
public async void VerifyConfigUpdateRequestSendErrorGivenInvalidConnection() public async Task VerifyConfigUpdateRequestSendErrorGivenInvalidConnection()
{ {
ServerConfigUpdateResponseParams result = null; ServerConfigUpdateResponseParams result = null;
var requestContext = RequestContextMocks.Create<ServerConfigUpdateResponseParams>(r => result = r).AddErrorHandling(null); var requestContext = RequestContextMocks.Create<ServerConfigUpdateResponseParams>(r => result = r).AddErrorHandling(null);
@@ -130,8 +130,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServic
requestContext.Verify(x => x.SendError(It.IsAny<Exception>())); requestContext.Verify(x => x.SendError(It.IsAny<Exception>()));
} }
[Fact] [Test]
public async void VerifyConfigListRequestSendErrorGivenInvalidConnection() public async Task VerifyConfigListRequestSendErrorGivenInvalidConnection()
{ {
ServerConfigListResponseParams result = null; ServerConfigListResponseParams result = null;
var requestContext = RequestContextMocks.Create<ServerConfigListResponseParams>(r => result = r).AddErrorHandling(null); var requestContext = RequestContextMocks.Create<ServerConfigListResponseParams>(r => result = r).AddErrorHandling(null);
@@ -20,8 +20,6 @@ using Microsoft.SqlTools.ServiceLayer.SqlAssessment;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts; using Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using NUnit.Framework; using NUnit.Framework;
using Xunit;
using Assert = Xunit.Assert;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
{ {
@@ -31,8 +29,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
private static readonly string[] AllowedSeverityLevels = { "Information", "Warning", "Critical" }; private static readonly string[] AllowedSeverityLevels = { "Information", "Warning", "Critical" };
[Fact] [Test]
public async void InvokeSqlAssessmentServerTest() public async Task InvokeSqlAssessmentServerTest()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -46,23 +44,19 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
SqlObjectType.Server, SqlObjectType.Server,
liveConnection); liveConnection);
Assert.All( Assert.Multiple(() =>
response.Items, {
i => Assert.That(response.Items.Select(i => i.Message), Has.All.Not.Null.Or.Empty);
{ Assert.That(response.Items.Select(i => i.TargetName), Has.All.EqualTo(serverInfo.ServerName));
Assert.NotNull(i.Message); foreach (var i in response.Items.Where(i => i.Kind == 0))
Assert.NotEmpty(i.Message); {
Assert.Equal(serverInfo.ServerName, i.TargetName); AssertInfoPresent(i);
}
if (i.Kind == 0) });
{
AssertInfoPresent(i);
}
});
} }
[Fact] [Test]
public async void GetAssessmentItemsServerTest() public async Task GetAssessmentItemsServerTest()
{ {
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -76,17 +70,18 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
SqlObjectType.Server, SqlObjectType.Server,
liveConnection); liveConnection);
Assert.All( Assert.Multiple(() =>
response.Items, {
i => Assert.That(response.Items.Select(i => i.TargetName), Has.All.EqualTo(serverInfo.ServerName));
foreach (var i in response.Items)
{ {
AssertInfoPresent(i); AssertInfoPresent(i);
Assert.Equal(serverInfo.ServerName, i.TargetName); }
}); });
} }
[Fact] [Test]
public async void GetAssessmentItemsDatabaseTest() public async Task GetAssessmentItemsDatabaseTest()
{ {
const string DatabaseName = "tempdb"; const string DatabaseName = "tempdb";
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName);
@@ -95,17 +90,18 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
SqlObjectType.Database, SqlObjectType.Database,
liveConnection); liveConnection);
Assert.All( Assert.Multiple(() =>
response.Items, {
i => Assert.That(response.Items.Select(i => i.TargetName), Has.All.EndsWith(":" + DatabaseName));
foreach (var i in response.Items)
{ {
StringAssert.EndsWith(":" + DatabaseName, i.TargetName);
AssertInfoPresent(i); AssertInfoPresent(i);
}); }
});
} }
[Fact] [Test]
public async void InvokeSqlAssessmentIDatabaseTest() public async Task InvokeSqlAssessmentIDatabaseTest()
{ {
const string DatabaseName = "tempdb"; const string DatabaseName = "tempdb";
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName);
@@ -114,19 +110,15 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
SqlObjectType.Database, SqlObjectType.Database,
liveConnection); liveConnection);
Assert.All( Assert.Multiple(() =>
response.Items, {
i => Assert.That(response.Items.Select(i => i.Message), Has.All.Not.Null.Or.Empty);
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EndsWith(":" + DatabaseName));
foreach (var i in response.Items.Where(i => i.Kind == 0))
{ {
StringAssert.EndsWith(":" + DatabaseName, i.TargetName); AssertInfoPresent(i);
Assert.NotNull(i.Message); }
Assert.NotEmpty(i.Message); });
if (i.Kind == 0)
{
AssertInfoPresent(i);
}
});
} }
private static async Task<AssessmentResult<TResult>> CallAssessment<TResult>( private static async Task<AssessmentResult<TResult>> CallAssessment<TResult>(
@@ -176,13 +168,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
Assert.NotNull(response); Assert.NotNull(response);
if (response.Success) if (response.Success)
{ {
Assert.All( Assert.That(response.Items.Select(i => i.TargetType), Has.All.EqualTo(sqlObjectType));
response.Items, Assert.That(response.Items.Select(i => i.Level), Has.All.AnyOf(AllowedSeverityLevels));
i =>
{
Assert.Equal(sqlObjectType, i.TargetType);
Assert.Contains(i.Level, AllowedSeverityLevels);
});
} }
return response; return response;
@@ -225,17 +212,13 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
private void AssertInfoPresent(AssessmentItemInfo item) private void AssertInfoPresent(AssessmentItemInfo item)
{ {
Assert.NotNull(item.CheckId); Assert.Multiple(() =>
Assert.NotEmpty(item.CheckId);
Assert.NotNull(item.DisplayName);
Assert.NotEmpty(item.DisplayName);
Assert.NotNull(item.Description);
Assert.NotEmpty(item.Description);
Assert.NotNull(item.Tags);
Assert.All(item.Tags, t =>
{ {
Assert.NotNull(t); Assert.That(item.CheckId, Is.Not.Null.Or.Empty);
Assert.NotEmpty(t); Assert.That(item.DisplayName, Is.Not.Null.Or.Empty);
Assert.That(item.Description, Is.Not.Null.Or.Empty);
Assert.NotNull(item.Tags);
Assert.That(item.Tags, Has.All.Not.Null.Or.Empty);
}); });
} }
} }
@@ -20,7 +20,7 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests; using Microsoft.SqlTools.ServiceLayer.UnitTests;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper; using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.TaskServices namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.TaskServices
@@ -37,25 +37,25 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.TaskServices
service.InitializeService(serviceHostMock.Object); service.InitializeService(serviceHostMock.Object);
} }
[Fact] [Test]
public async Task VerifyTaskExecuteTheQueryGivenExecutionModeExecute() public async Task VerifyTaskExecuteTheQueryGivenExecutionModeExecute()
{ {
await VerifyTaskWithExecutionMode(TaskExecutionMode.Execute); await VerifyTaskWithExecutionMode(TaskExecutionMode.Execute);
} }
[Fact] [Test]
public async Task VerifyTaskGenerateScriptOnlyGivenExecutionModeScript() public async Task VerifyTaskGenerateScriptOnlyGivenExecutionModeScript()
{ {
await VerifyTaskWithExecutionMode(TaskExecutionMode.Script); await VerifyTaskWithExecutionMode(TaskExecutionMode.Script);
} }
[Fact] [Test]
public async Task VerifyTaskNotExecuteAndGenerateScriptGivenExecutionModeExecuteAndScript() public async Task VerifyTaskNotExecuteAndGenerateScriptGivenExecutionModeExecuteAndScript()
{ {
await VerifyTaskWithExecutionMode(TaskExecutionMode.ExecuteAndScript); await VerifyTaskWithExecutionMode(TaskExecutionMode.ExecuteAndScript);
} }
[Fact] [Test]
public async Task VerifyTaskSendsFailureNotificationGivenInvalidQuery() public async Task VerifyTaskSendsFailureNotificationGivenInvalidQuery()
{ {
await VerifyTaskWithExecutionMode(TaskExecutionMode.ExecuteAndScript, true); await VerifyTaskWithExecutionMode(TaskExecutionMode.ExecuteAndScript, true);
@@ -103,7 +103,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.TaskServices
bool expected = executionMode == TaskExecutionMode.Execute || executionMode == TaskExecutionMode.ExecuteAndScript; bool expected = executionMode == TaskExecutionMode.Execute || executionMode == TaskExecutionMode.ExecuteAndScript;
Server serverToverfiy = CreateServerObject(connectionResult.ConnectionInfo); Server serverToverfiy = CreateServerObject(connectionResult.ConnectionInfo);
bool actual = serverToverfiy.Databases[testDb.DatabaseName].Tables.Contains(taskOperation.TableName, "test"); bool actual = serverToverfiy.Databases[testDb.DatabaseName].Tables.Contains(taskOperation.TableName, "test");
Assert.Equal(expected, actual); Assert.AreEqual(expected, actual);
} }
else else
{ {
@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility
{ {
@@ -7,7 +7,7 @@ using System;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Text; using System.Text;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common.Baselined namespace Microsoft.SqlTools.ServiceLayer.Test.Common.Baselined
{ {
@@ -10,8 +10,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Moq" /> <PackageReference Include="Moq" />
<PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" /> <PackageReference Include="nunit" />
<PackageReference Include="xunit.runner.visualstudio" /> <PackageReference Include="nunit3testadapter" />
<PackageReference Include="nunit.console" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Include="Scripts/CreateTestDatabaseObjects.sql" /> <EmbeddedResource Include="Scripts/CreateTestDatabaseObjects.sql" />
@@ -11,7 +11,7 @@ using Microsoft.SqlTools.Hosting.Contracts;
using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.Hosting.Protocol.Contracts; using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking namespace Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking
{ {
@@ -99,7 +99,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking
// Add an error validator that just ensures a non-empty error message and null data obj // Add an error validator that just ensures a non-empty error message and null data obj
return AddSimpleErrorValidation((msg, code) => return AddSimpleErrorValidation((msg, code) =>
{ {
Assert.NotEmpty(msg); Assert.That(msg, Is.Not.Null.Or.Empty, $"AddStandardErrorValidation msg for {code}");
}); });
} }
@@ -7,7 +7,7 @@ using System;
using System.Globalization; using System.Globalization;
using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Xunit; using NUnit.Framework;
using Microsoft.Data.SqlClient; using Microsoft.Data.SqlClient;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Common;
@@ -8,7 +8,7 @@ using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using Microsoft.SqlTools.Credentials.Contracts; using Microsoft.SqlTools.Credentials.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{ {
@@ -9,7 +9,7 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{ {
@@ -18,7 +18,7 @@ using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.TestDriver.Driver; using Microsoft.SqlTools.ServiceLayer.TestDriver.Driver;
using Microsoft.SqlTools.ServiceLayer.TestDriver.Utility; using Microsoft.SqlTools.ServiceLayer.TestDriver.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{ {
@@ -16,7 +16,7 @@ using Microsoft.SqlTools.ServiceLayer.ObjectExplorer;
using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.SqlContext; using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Workspace; using Microsoft.SqlTools.ServiceLayer.Workspace;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{ {
@@ -6,11 +6,12 @@
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{ {
[TestFixture]
/// <summary> /// <summary>
/// Language Service end-to-end integration tests /// Language Service end-to-end integration tests
/// </summary> /// </summary>
@@ -19,16 +20,16 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary> /// <summary>
/// Try to connect with invalid credentials /// Try to connect with invalid credentials
/// </summary> /// </summary>
[Fact] [Test]
public async Task InvalidConnection() public async Task InvalidConnection()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
{ {
bool connected = await testService.Connect(queryTempFile.FilePath, InvalidConnectParams, 300000); bool connected = await testService.Connect(queryTempFile.FilePath, InvalidConnectParams, 60000);
Assert.False(connected, "Invalid connection is failed to connect"); Assert.False(connected, "Invalid connection is failed to connect");
await testService.Connect(queryTempFile.FilePath, InvalidConnectParams, 300000); await testService.Connect(queryTempFile.FilePath, InvalidConnectParams, 60000);
Thread.Sleep(1000); Thread.Sleep(1000);
@@ -41,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary> /// <summary>
/// Validate list databases request /// Validate list databases request
/// </summary> /// </summary>
[Fact] [Test]
public async Task ListDatabasesTest() public async Task ListDatabasesTest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -10,10 +10,11 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.SqlContext; using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{ {
[TestFixture]
/// <summary> /// <summary>
/// Language Service end-to-end integration tests /// Language Service end-to-end integration tests
/// </summary> /// </summary>
@@ -23,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary> /// <summary>
/// Validate hover tooltip scenarios /// Validate hover tooltip scenarios
/// </summary> /// </summary>
[Fact] [Test]
public async Task HoverTest() public async Task HoverTest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -64,7 +65,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary> /// <summary>
/// Validation autocompletion suggestions scenarios /// Validation autocompletion suggestions scenarios
/// </summary> /// </summary>
[Fact] [Test]
public async Task CompletionTest() public async Task CompletionTest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -111,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary> /// <summary>
/// Validate diagnostic scenarios /// Validate diagnostic scenarios
/// </summary> /// </summary>
[Fact] [Test]
public async Task DiagnosticsTests() public async Task DiagnosticsTests()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -214,7 +215,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// Peek Definition/ Go to definition /// Peek Definition/ Go to definition
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Test]
public async Task DefinitionTest() public async Task DefinitionTest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -260,7 +261,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary> /// <summary>
/// Validate the configuration change event /// Validate the configuration change event
/// </summary> /// </summary>
[Fact] [Test]
public async Task ChangeConfigurationTest() public async Task ChangeConfigurationTest()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -286,7 +287,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task NotificationIsSentAfterOnConnectionAutoCompleteUpdate() public async Task NotificationIsSentAfterOnConnectionAutoCompleteUpdate()
{ {
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -298,13 +299,13 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
// An event signalling that IntelliSense is ready should be sent shortly thereafter // An event signalling that IntelliSense is ready should be sent shortly thereafter
var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000); var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000);
Assert.NotNull(readyParams); Assert.NotNull(readyParams);
Assert.Equal(queryTempFile.FilePath, readyParams.OwnerUri); Assert.AreEqual(queryTempFile.FilePath, readyParams.OwnerUri);
await testService.Disconnect(queryTempFile.FilePath); await testService.Disconnect(queryTempFile.FilePath);
} }
} }
[Fact] [Test]
public async Task FunctionSignatureCompletionReturnsEmptySignatureHelpObjectWhenThereAreNoMatches() public async Task FunctionSignatureCompletionReturnsEmptySignatureHelpObjectWhenThereAreNoMatches()
{ {
string sqlText = "EXEC sys.fn_not_a_real_function "; string sqlText = "EXEC sys.fn_not_a_real_function ";
@@ -321,7 +322,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
// Wait for intellisense to be ready // Wait for intellisense to be ready
var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000); var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000);
Assert.NotNull(readyParams); Assert.NotNull(readyParams);
Assert.Equal(ownerUri, readyParams.OwnerUri); Assert.AreEqual(ownerUri, readyParams.OwnerUri);
// Send a function signature help Request // Send a function signature help Request
var position = new TextDocumentPosition() var position = new TextDocumentPosition()
@@ -346,7 +347,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task FunctionSignatureCompletionReturnsCorrectFunction() public async Task FunctionSignatureCompletionReturnsCorrectFunction()
{ {
string sqlText = "EXEC sys.fn_isrolemember "; string sqlText = "EXEC sys.fn_isrolemember ";
@@ -362,7 +363,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
// Wait for intellisense to be ready // Wait for intellisense to be ready
var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000); var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000);
Assert.NotNull(readyParams); Assert.NotNull(readyParams);
Assert.Equal(ownerUri, readyParams.OwnerUri); Assert.AreEqual(ownerUri, readyParams.OwnerUri);
// Send a function signature help Request // Send a function signature help Request
var position = new TextDocumentPosition() var position = new TextDocumentPosition()
@@ -381,18 +382,17 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
Assert.NotNull(signatureHelp); Assert.NotNull(signatureHelp);
Assert.True(signatureHelp.ActiveSignature.HasValue); Assert.True(signatureHelp.ActiveSignature.HasValue);
Assert.NotEmpty(signatureHelp.Signatures); Assert.That(signatureHelp.Signatures, Is.Not.Empty, "signatureHelp.Signatures after SendRequest");
var label = signatureHelp.Signatures[signatureHelp.ActiveSignature.Value].Label; var label = signatureHelp.Signatures[signatureHelp.ActiveSignature.Value].Label;
Assert.NotNull(label); Assert.That(label, Is.Not.Null.Or.Empty, "label");
Assert.NotEmpty(label); Assert.That(label, Contains.Substring("fn_isrolemember"), "label contents");
Assert.True(label.Contains("fn_isrolemember"));
await testService.Disconnect(ownerUri); await testService.Disconnect(ownerUri);
} }
} }
[Fact] [Test]
public async Task FunctionSignatureCompletionReturnsCorrectParametersAtEachPosition() public async Task FunctionSignatureCompletionReturnsCorrectParametersAtEachPosition()
{ {
string sqlText = "EXEC sys.fn_isrolemember 1, 'testing', 2"; string sqlText = "EXEC sys.fn_isrolemember 1, 'testing', 2";
@@ -409,7 +409,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
// Wait for intellisense to be ready // Wait for intellisense to be ready
var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000); var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000);
Assert.NotNull(readyParams); Assert.NotNull(readyParams);
Assert.Equal(ownerUri, readyParams.OwnerUri); Assert.AreEqual(ownerUri, readyParams.OwnerUri);
// Verify all parameters when the cursor is inside of parameters and at separator boundaries (,) // Verify all parameters when the cursor is inside of parameters and at separator boundaries (,)
await VerifyFunctionSignatureHelpParameter(testService, ownerUri, 25, "fn_isrolemember", 0, "@mode int"); await VerifyFunctionSignatureHelpParameter(testService, ownerUri, 25, "fn_isrolemember", 0, "@mode int");
@@ -449,25 +449,23 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
Assert.NotNull(signatureHelp); Assert.NotNull(signatureHelp);
Assert.NotNull(signatureHelp.ActiveSignature); Assert.NotNull(signatureHelp.ActiveSignature);
Assert.True(signatureHelp.ActiveSignature.HasValue); Assert.True(signatureHelp.ActiveSignature.HasValue);
Assert.NotEmpty(signatureHelp.Signatures); Assert.That(signatureHelp.Signatures, Is.Not.Empty, "Signatures");
var activeSignature = signatureHelp.Signatures[signatureHelp.ActiveSignature.Value]; var activeSignature = signatureHelp.Signatures[signatureHelp.ActiveSignature.Value];
Assert.NotNull(activeSignature); Assert.NotNull(activeSignature);
var label = activeSignature.Label; var label = activeSignature.Label;
Assert.NotNull(label); Assert.That(label, Is.Not.Null.Or.Empty, "label");
Assert.NotEmpty(label); Assert.That(label, Contains.Substring(expectedFunctionName), "label contents");
Assert.True(label.Contains(expectedFunctionName));
Assert.NotNull(signatureHelp.ActiveParameter); Assert.NotNull(signatureHelp.ActiveParameter);
Assert.True(signatureHelp.ActiveParameter.HasValue); Assert.True(signatureHelp.ActiveParameter.HasValue);
Assert.Equal(expectedParameterIndex, signatureHelp.ActiveParameter.Value); Assert.AreEqual(expectedParameterIndex, signatureHelp.ActiveParameter.Value);
var parameter = activeSignature.Parameters[signatureHelp.ActiveParameter.Value]; var parameter = activeSignature.Parameters[signatureHelp.ActiveParameter.Value];
Assert.NotNull(parameter); Assert.NotNull(parameter);
Assert.NotNull(parameter.Label); Assert.That(parameter.Label, Is.Not.Null.Or.Empty, "parameter.Label");
Assert.NotEmpty(parameter.Label); Assert.AreEqual(expectedParameterName, parameter.Label);
Assert.Equal(expectedParameterName, parameter.Label);
} }
} }
} }
@@ -21,8 +21,9 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" /> <PackageReference Include="nunit" />
<PackageReference Include="xunit.runner.visualstudio" /> <PackageReference Include="nunit.console" />
<PackageReference Include="nunit3testadapter"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
@@ -9,9 +9,9 @@ using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.TestDriver.Driver; using Microsoft.SqlTools.ServiceLayer.TestDriver.Driver;
using Microsoft.SqlTools.Utility; using Microsoft.SqlTools.Utility;
using Xunit; using NUnit.Framework;
[assembly: CollectionBehavior(DisableTestParallelization = true)] [assembly: NonParallelizable]
// turn off entry point since this is xUnit project // turn off entry point since this is xUnit project
#if false #if false
@@ -5,14 +5,14 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{ {
public class QueryExecutionTests public class QueryExecutionTests
{ {
/* Commenting out these tests until they are fixed (12/1/16) /* Commenting out these tests until they are fixed (12/1/16)
[Fact] [Test]
public async Task TestQueryCancelReliability() public async Task TestQueryCancelReliability()
{ {
const string query = "SELECT * FROM sys.objects a CROSS JOIN sys.objects b CROSS JOIN sys.objects c"; const string query = "SELECT * FROM sys.objects a CROSS JOIN sys.objects b CROSS JOIN sys.objects c";
@@ -38,7 +38,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task TestQueryDoesNotBlockOtherRequests() public async Task TestQueryDoesNotBlockOtherRequests()
{ {
const string query = "SELECT * FROM sys.objects a CROSS JOIN sys.objects b CROSS JOIN sys.objects c"; const string query = "SELECT * FROM sys.objects a CROSS JOIN sys.objects b CROSS JOIN sys.objects c";
@@ -67,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task TestParallelQueryExecution() public async Task TestParallelQueryExecution()
{ {
const int queryCount = 10; const int queryCount = 10;
@@ -102,7 +102,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task TestSaveResultsDoesNotBlockOtherRequests() public async Task TestSaveResultsDoesNotBlockOtherRequests()
{ {
const string query = "SELECT * FROM sys.objects"; const string query = "SELECT * FROM sys.objects";
@@ -146,7 +146,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task TestQueryingSubsetDoesNotBlockOtherRequests() public async Task TestQueryingSubsetDoesNotBlockOtherRequests()
{ {
const string query = "SELECT * FROM sys.objects"; const string query = "SELECT * FROM sys.objects";
@@ -183,7 +183,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task TestCancelQueryWhileOtherOperationsAreInProgress() public async Task TestCancelQueryWhileOtherOperationsAreInProgress()
{ {
const string query = "SELECT * FROM sys.objects a CROSS JOIN sys.objects b"; const string query = "SELECT * FROM sys.objects a CROSS JOIN sys.objects b";
@@ -220,7 +220,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task ExecuteBasicQueryTest() public async Task ExecuteBasicQueryTest()
{ {
const string query = "SELECT * FROM sys.all_columns c"; const string query = "SELECT * FROM sys.all_columns c";
@@ -276,7 +276,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task TestQueryingAfterCompletionRequests() public async Task TestQueryingAfterCompletionRequests()
{ {
const string query = "SELECT * FROM sys.objects"; const string query = "SELECT * FROM sys.objects";
@@ -6,28 +6,31 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Scripting.Contracts; using Microsoft.SqlTools.ServiceLayer.Scripting.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{ {
[TestFixture]
/// <summary> /// <summary>
/// Scripting service end-to-end integration tests that use the SqlScriptPublishModel type to generate scripts. /// Scripting service end-to-end integration tests that use the SqlScriptPublishModel type to generate scripts.
/// </summary> /// </summary>
public class SqlScriptPublishModelTests : IClassFixture<SqlScriptPublishModelTests.ScriptingFixture> public class SqlScriptPublishModelTests
{ {
public SqlScriptPublishModelTests(ScriptingFixture scriptingFixture) [OneTimeSetUp]
public void SetupSqlScriptPublishModelTests()
{ {
this.Fixture = scriptingFixture; Fixture = new ScriptingFixture();
} }
public ScriptingFixture Fixture { get; private set; } private static ScriptingFixture Fixture { get; set; }
public SqlTestDb Northwind { get { return this.Fixture.Database; } } private SqlTestDb Northwind { get { return Fixture.Database; } }
[Fact] [Test]
public async Task ListSchemaObjects() public async Task ListSchemaObjects()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -40,11 +43,11 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingListObjectsResult result = await testService.ListScriptingObjects(requestParams); ScriptingListObjectsResult result = await testService.ListScriptingObjects(requestParams);
ScriptingListObjectsCompleteParams completeParameters = await testService.Driver.WaitForEvent(ScriptingListObjectsCompleteEvent.Type, TimeSpan.FromSeconds(30)); ScriptingListObjectsCompleteParams completeParameters = await testService.Driver.WaitForEvent(ScriptingListObjectsCompleteEvent.Type, TimeSpan.FromSeconds(30));
Assert.Equal<int>(ScriptingFixture.ObjectCountWithoutDatabase, completeParameters.ScriptingObjects.Count); Assert.AreEqual(ScriptingFixture.ObjectCountWithoutDatabase, completeParameters.ScriptingObjects.Count);
} }
} }
[Fact] [Test]
public async Task ScriptDatabaseSchema() public async Task ScriptDatabaseSchema()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -65,7 +68,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task ScriptDatabaseSchemaAndData() public async Task ScriptDatabaseSchemaAndData()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -86,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
[Fact] [Test]
public async Task ScriptTable() public async Task ScriptTable()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -115,11 +118,11 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingPlanNotificationParams planEvent = await testService.Driver.WaitForEvent(ScriptingPlanNotificationEvent.Type, TimeSpan.FromSeconds(1)); ScriptingPlanNotificationParams planEvent = await testService.Driver.WaitForEvent(ScriptingPlanNotificationEvent.Type, TimeSpan.FromSeconds(1));
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30)); ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30));
Assert.True(parameters.Success); Assert.True(parameters.Success);
Assert.Equal<int>(1, planEvent.Count); Assert.AreEqual(1, planEvent.Count);
} }
} }
[Fact] [Test]
public async Task ScriptTableUsingIncludeFilter() public async Task ScriptTableUsingIncludeFilter()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -147,11 +150,13 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingPlanNotificationParams planEvent = await testService.Driver.WaitForEvent(ScriptingPlanNotificationEvent.Type, TimeSpan.FromSeconds(30)); ScriptingPlanNotificationParams planEvent = await testService.Driver.WaitForEvent(ScriptingPlanNotificationEvent.Type, TimeSpan.FromSeconds(30));
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30)); ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30));
Assert.True(parameters.Success); Assert.True(parameters.Success);
Assert.Equal<int>(1, planEvent.Count); // Work around SMO bug https://github.com/microsoft/sqlmanagementobjects/issues/19 which leads to non-unique URNs in the collection
Assert.That(planEvent.Count, Is.AtLeast(1), "ScripingPlanNotificationParams.Count");
Assert.That(planEvent.ScriptingObjects.All(obj => obj.Name == "Customers" && obj.Schema == "dbo" && obj.Type == "Table"), "ScriptingPlanNotificationParams.ScriptingObjects contents");
} }
} }
[Fact] [Test]
public async Task ScriptTableAndData() public async Task ScriptTableAndData()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -179,11 +184,13 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingPlanNotificationParams planEvent = await testService.Driver.WaitForEvent(ScriptingPlanNotificationEvent.Type, TimeSpan.FromSeconds(30)); ScriptingPlanNotificationParams planEvent = await testService.Driver.WaitForEvent(ScriptingPlanNotificationEvent.Type, TimeSpan.FromSeconds(30));
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30)); ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30));
Assert.True(parameters.Success); Assert.True(parameters.Success);
Assert.Equal<int>(1, planEvent.Count); // Work around SMO bug https://github.com/microsoft/sqlmanagementobjects/issues/19 which leads to non-unique URNs in the collection
Assert.That(planEvent.Count, Is.AtLeast(1), "ScripingPlanNotificationParams.Count");
Assert.That(planEvent.ScriptingObjects.All(obj => obj.Name == "Customers" && obj.Schema == "dbo" && obj.Type == "Table"), "ScriptingPlanNotificationParams.ScriptingObjects contents");
} }
} }
[Fact] [Test]
public async Task ScriptTableDoesNotExist() public async Task ScriptTableDoesNotExist()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -211,13 +218,13 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingResult result = await testService.Script(requestParams); ScriptingResult result = await testService.Script(requestParams);
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(15)); ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(15));
Assert.True(parameters.HasError); Assert.True(parameters.HasError);
Assert.True(parameters.ErrorMessage.Contains("An error occurred while scripting the objects.")); Assert.That(parameters.ErrorMessage, Contains.Substring("An error occurred while scripting the objects."), "parameters.ErrorMessage");
Assert.Contains("The Table '[dbo].[TableDoesNotExist]' does not exist on the server.", parameters.ErrorDetails); Assert.That(parameters.ErrorDetails, Contains.Substring("The Table '[dbo].[TableDoesNotExist]' does not exist on the server."), "parameters.ErrorDetails");
} }
} }
[Fact] [Test]
public async void ScriptSchemaCancel() public async Task ScriptSchemaCancel()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
{ {
@@ -232,15 +239,15 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
}; };
var result = Task.Run(() => testService.Script(requestParams)); var result = Task.Run(() => testService.Script(requestParams));
ScriptingProgressNotificationParams progressParams = await testService.Driver.WaitForEvent(ScriptingProgressNotificationEvent.Type, TimeSpan.FromSeconds(10)); ScriptingProgressNotificationParams progressParams = await testService.Driver.WaitForEvent(ScriptingProgressNotificationEvent.Type, TimeSpan.FromSeconds(60));
Task.Run(() => testService.CancelScript(progressParams.OperationId).Wait()); await Task.Run(() => testService.CancelScript(progressParams.OperationId));
ScriptingCompleteParams cancelEvent = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(10)); ScriptingCompleteParams cancelEvent = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(10));
Assert.True(cancelEvent.Canceled); Assert.True(cancelEvent.Canceled);
} }
} }
[Fact] [Test]
public async Task ScriptSchemaInvalidConnectionString() public async Task ScriptSchemaInvalidConnectionString()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -258,11 +265,11 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingResult result = await testService.Script(requestParams); ScriptingResult result = await testService.Script(requestParams);
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(10)); ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(10));
Assert.True(parameters.HasError); Assert.True(parameters.HasError);
Assert.Equal("Error parsing ScriptingParams.ConnectionString property.", parameters.ErrorMessage); Assert.AreEqual("Error parsing ScriptingParams.ConnectionString property.", parameters.ErrorMessage);
} }
} }
[Fact] [Test]
public async Task ScriptSchemaInvalidFilePath() public async Task ScriptSchemaInvalidFilePath()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -280,11 +287,11 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingResult result = await testService.Script(requestParams); ScriptingResult result = await testService.Script(requestParams);
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(10)); ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(10));
Assert.True(parameters.HasError); Assert.True(parameters.HasError);
Assert.Equal("Invalid directory specified by the ScriptingParams.FilePath property.", parameters.ErrorMessage); Assert.AreEqual("Invalid directory specified by the ScriptingParams.FilePath property.", parameters.ErrorMessage);
} }
} }
[Fact] [Test]
public async Task ScriptSelectTable() public async Task ScriptSelectTable()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -359,7 +366,6 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
} }
} }
public void Dispose() { }
public class ScriptingFixture : IDisposable public class ScriptingFixture : IDisposable
{ {
@@ -5,21 +5,23 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit; using NUnit.Framework;
using Range = Microsoft.SqlTools.ServiceLayer.Workspace.Contracts.Range; using Range = Microsoft.SqlTools.ServiceLayer.Workspace.Contracts.Range;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{ {
[TestFixture]
public class StressTests public class StressTests
{ {
/// <summary> /// <summary>
/// Simulate typing by a user to stress test the language service /// Simulate typing by a user to stress test the language service
/// </summary> /// </summary>
//[Fact] //[Test]
public async Task TestLanguageService() public async Task TestLanguageService()
{ {
const string textToType = "SELECT * FROM sys.objects GO " + const string textToType = "SELECT * FROM sys.objects GO " +
@@ -144,7 +146,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary> /// <summary>
/// Repeatedly execute queries to stress test the query execution service. /// Repeatedly execute queries to stress test the query execution service.
/// </summary> /// </summary>
//[Fact] //[Test]
public async Task TestQueryExecutionService() public async Task TestQueryExecutionService()
{ {
const string queryToRun = "SELECT * FROM sys.all_objects GO " + const string queryToRun = "SELECT * FROM sys.all_objects GO " +
@@ -167,12 +169,8 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
var queryResult = await testService.RunQueryAndWaitToComplete(queryTempFile.FilePath, queryToRun, 10000); var queryResult = await testService.RunQueryAndWaitToComplete(queryTempFile.FilePath, queryToRun, 10000);
Assert.NotNull(queryResult); Assert.NotNull(queryResult);
Assert.NotNull(queryResult.BatchSummaries); Assert.That(queryResult.BatchSummaries, Is.Not.Null, "queryResult.BatchSummaries");
Assert.NotEmpty(queryResult.BatchSummaries); Assert.That(queryResult.BatchSummaries.Select(b => b.ResultSetSummaries), Has.Exactly(4).Not.Null, "ResultSetSummaries in the queryResult");
Assert.NotNull(queryResult.BatchSummaries[0].ResultSetSummaries);
Assert.NotNull(queryResult.BatchSummaries[1].ResultSetSummaries);
Assert.NotNull(queryResult.BatchSummaries[2].ResultSetSummaries);
Assert.NotNull(queryResult.BatchSummaries[3].ResultSetSummaries);
Assert.NotNull(await testService.ExecuteSubset(queryTempFile.FilePath, 0, 0, 0, 7)); Assert.NotNull(await testService.ExecuteSubset(queryTempFile.FilePath, 0, 0, 0, 7));
Assert.NotNull(await testService.ExecuteSubset(queryTempFile.FilePath, 1, 0, 0, 7)); Assert.NotNull(await testService.ExecuteSubset(queryTempFile.FilePath, 1, 0, 0, 7));
@@ -189,7 +187,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary> /// <summary>
/// Repeatedly connect and disconnect to stress test the connection service. /// Repeatedly connect and disconnect to stress test the connection service.
/// </summary> /// </summary>
//[Fact] //[Test]
public async Task TestConnectionService() public async Task TestConnectionService()
{ {
string ownerUri = "file:///my/test/file.sql"; string ownerUri = "file:///my/test/file.sql";
@@ -7,10 +7,11 @@ using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Contracts; using Microsoft.SqlTools.Hosting.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{ {
[TestFixture]
/// <summary> /// <summary>
/// Language Service end-to-end integration tests /// Language Service end-to-end integration tests
/// </summary> /// </summary>
@@ -19,7 +20,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary> /// <summary>
/// Validate workspace lifecycle events /// Validate workspace lifecycle events
/// </summary> /// </summary>
[Fact] [Test]
public async Task InitializeRequestTest() public async Task InitializeRequestTest()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -49,9 +49,14 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Driver
string serviceHostArguments = "--enable-logging"; string serviceHostArguments = "--enable-logging";
if (string.IsNullOrWhiteSpace(serviceHostExecutable)) if (string.IsNullOrWhiteSpace(serviceHostExecutable))
{ {
// Include a fallback value to for running tests within visual studio // Include a fallback value to for running tests within visual studio
serviceHostExecutable = serviceHostExecutable =
@"..\..\..\..\..\src\Microsoft.SqlTools.ServiceLayer\bin\Debug\netcoreapp3.1\win7-x64\MicrosoftSqlToolsServiceLayer.exe"; @"..\..\..\..\..\src\Microsoft.SqlTools.ServiceLayer\bin\Debug\netcoreapp3.1\win7-x64\MicrosoftSqlToolsServiceLayer.exe";
if (!File.Exists(serviceHostExecutable))
{
serviceHostExecutable = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "MicrosoftSqlToolsServiceLayer.exe");
}
} }
serviceHostExecutable = Path.GetFullPath(serviceHostExecutable); serviceHostExecutable = Path.GetFullPath(serviceHostExecutable);
@@ -9,8 +9,6 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="../../src/Microsoft.SqlTools.Hosting/Microsoft.SqlTools.Hosting.csproj" /> <ProjectReference Include="../../src/Microsoft.SqlTools.Hosting/Microsoft.SqlTools.Hosting.csproj" />
@@ -4,13 +4,7 @@
// //
using System; using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit;
using Xunit.Sdk;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Utility namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Utility
{ {
@@ -95,90 +89,15 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Utility
public async Task<int> RunTests(string[] args, string testNamespace) public async Task<int> RunTests(string[] args, string testNamespace)
{ {
ParseArguments(args); ParseArguments(args);
foreach (var test in Tests)
{
try
{
var testName = test.Contains(testNamespace) ? test.Replace(testNamespace, "") : test;
bool containsTestName = testName.Contains(".");
var className = containsTestName ? testName.Substring(0, testName.LastIndexOf('.')) : testName;
var methodName = containsTestName ? testName.Substring(testName.LastIndexOf('.') + 1) : null;
Assembly assembly = Assembly.GetEntryAssembly();
Type type = assembly.GetType(testNamespace + className);
if (type == null)
{
Console.WriteLine("Invalid class name");
}
else
{
var typeInstance = Activator.CreateInstance(type);
if (string.IsNullOrEmpty(methodName))
{
var methods = type.GetMethods().Where(x => x.CustomAttributes.Any(a => a.AttributeType == typeof(FactAttribute)));
foreach (var method in methods)
{
await RunTest(typeInstance, method, method.Name);
}
}
else
{
MethodInfo methodInfo = type.GetMethod(methodName);
await RunTest(typeInstance, methodInfo, test);
}
IDisposable disposable = typeInstance as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return -1;
}
}
return 0;
}
private static async Task RunTest(object typeInstance, MethodInfo methodInfo, string testName)
{
try try
{ {
if (methodInfo == null) throw new NotImplementedException("This code needs to change to use 'dotnet test' or nunit directly");
{ }
Console.WriteLine("Invalid method name"); catch (Exception ex)
} {
else Console.WriteLine(ex.ToString());
{ return await Task.FromResult(-1);
var testAttributes = methodInfo.CustomAttributes; }
BeforeAfterTestAttribute beforeAfterTestAttribute = null;
foreach (var attribute in testAttributes)
{
var args = attribute.ConstructorArguments.Select(x => x.Value as object).ToArray();
var objAttribute = Activator.CreateInstance(attribute.AttributeType, args);
beforeAfterTestAttribute = objAttribute as BeforeAfterTestAttribute;
if (beforeAfterTestAttribute != null)
{
beforeAfterTestAttribute.Before(methodInfo);
}
}
Console.WriteLine("Running test " + testName);
await (Task)methodInfo.Invoke(typeInstance, null);
if (beforeAfterTestAttribute != null)
{
beforeAfterTestAttribute.After(methodInfo);
}
Console.WriteLine("Test ran successfully: " + testName);
}
}
catch(Exception ex)
{
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Test Failed: {0} error: {1}", testName, ex.Message));
}
} }
} }
} }
@@ -3,35 +3,31 @@
// 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.Security; using NUnit.Framework;
using Xunit;
using Microsoft.SqlTools.ServiceLayer.Admin;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Management; using Microsoft.SqlTools.ServiceLayer.Management;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Admin namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Admin
{ {
[TestFixture]
/// <summary> /// <summary>
/// Tests for AdminService Class /// Tests for AdminService Class
/// </summary> /// </summary>
public class AdminServiceTests public class AdminServiceTests
{ {
[Fact] [Test]
public void TestBuildingSecureStringFromPassword() public void TestBuildingSecureStringFromPassword()
{ {
string password = "test_password"; string password = "test_password";
var secureString = CDataContainer.BuildSecureStringFromPassword(password); var secureString = CDataContainer.BuildSecureStringFromPassword(password);
Assert.Equal(password.Length, secureString.Length); Assert.AreEqual(password.Length, secureString.Length);
} }
[Fact] [Test]
public void TestBuildingSecureStringFromNullPassword() public void TestBuildingSecureStringFromNullPassword()
{ {
string password = null; string password = null;
var secureString = CDataContainer.BuildSecureStringFromPassword(password); var secureString = CDataContainer.BuildSecureStringFromPassword(password);
Assert.Equal(0, secureString.Length); Assert.AreEqual(0, secureString.Length);
} }
} }
} }
@@ -3,6 +3,6 @@
// 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 Xunit; using NUnit.Framework;
[assembly: CollectionBehavior(DisableTestParallelization = true)] [assembly: NonParallelizable]
@@ -12,12 +12,13 @@ using Microsoft.Data.SqlClient;
using Microsoft.SqlTools.ServiceLayer.AutoParameterizaition; using Microsoft.SqlTools.ServiceLayer.AutoParameterizaition;
using Microsoft.SqlTools.ServiceLayer.AutoParameterizaition.Exceptions; using Microsoft.SqlTools.ServiceLayer.AutoParameterizaition.Exceptions;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit; using NUnit.Framework;
using static System.Linq.Enumerable; using static System.Linq.Enumerable;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
{ {
[TestFixture]
/// <summary> /// <summary>
/// Parameterization for Always Encrypted is a feature that automatically converts Transact-SQL variables /// Parameterization for Always Encrypted is a feature that automatically converts Transact-SQL variables
/// into query parameters (instances of <c>SqlParameter</c> Class). This allows the underlying .NET Framework /// into query parameters (instances of <c>SqlParameter</c> Class). This allows the underlying .NET Framework
@@ -38,7 +39,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// - Are declared and initialized in the same statement(inline initialization). /// - Are declared and initialized in the same statement(inline initialization).
/// - Are initialized using a single literal. /// - Are initialized using a single literal.
/// </summary> /// </summary>
[Fact] [Test]
public void SqlParameterizerShouldParameterizeValidVariables() public void SqlParameterizerShouldParameterizeValidVariables()
{ {
const string ssn = "795-73-9838"; const string ssn = "795-73-9838";
@@ -56,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
DbCommand command = new SqlCommand { CommandText = sql }; DbCommand command = new SqlCommand { CommandText = sql };
command.Parameterize(); command.Parameterize();
Assert.Equal(expected: 3, actual: command.Parameters.Count); Assert.AreEqual(expected: 3, actual: command.Parameters.Count);
} }
/// <summary> /// <summary>
@@ -67,7 +68,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// The second is using a function used instead of a literal and so should not be parameterized. /// The second is using a function used instead of a literal and so should not be parameterized.
/// The third is using an expression used instead of a literal and so should not be parameterized. /// The third is using an expression used instead of a literal and so should not be parameterized.
/// </summary> /// </summary>
[Fact] [Test]
public void SqlParameterizerShouldNotParameterizeInvalidVariables() public void SqlParameterizerShouldNotParameterizeInvalidVariables()
{ {
string sql = $@" string sql = $@"
@@ -82,7 +83,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
DbCommand command = new SqlCommand { CommandText = sql }; DbCommand command = new SqlCommand { CommandText = sql };
command.Parameterize(); command.Parameterize();
Assert.Equal(expected: 0, actual: command.Parameters.Count); Assert.AreEqual(expected: 0, actual: command.Parameters.Count);
} }
/// <summary> /// <summary>
@@ -90,7 +91,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// Batch statements larger than 300000 characters (Approximately 600 Kb) should /// Batch statements larger than 300000 characters (Approximately 600 Kb) should
/// throw <c>ParameterizationScriptTooLargeException</c>. /// throw <c>ParameterizationScriptTooLargeException</c>.
/// </summary> /// </summary>
[Fact] [Test]
public void SqlParameterizerShouldThrowWhenSqlIsTooLong() public void SqlParameterizerShouldThrowWhenSqlIsTooLong()
{ {
@@ -118,7 +119,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// During parameterization, if we could not parse the SQL we will throw an <c>ParameterizationParsingException</c>. /// During parameterization, if we could not parse the SQL we will throw an <c>ParameterizationParsingException</c>.
/// Better to catch the error here than on the server. /// Better to catch the error here than on the server.
/// </summary> /// </summary>
[Fact] [Test]
public void SqlParameterizerShouldThrowWhenSqlIsInvalid() public void SqlParameterizerShouldThrowWhenSqlIsInvalid()
{ {
string invalidSql = "THIS IS INVALID SQL"; string invalidSql = "THIS IS INVALID SQL";
@@ -135,7 +136,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// literal used for the initialization of the variable must also match the type in the variable declaration. /// literal used for the initialization of the variable must also match the type in the variable declaration.
/// If not, a <c>ParameterizationFormatException</c> should get thrown. /// If not, a <c>ParameterizationFormatException</c> should get thrown.
/// </summary> /// </summary>
[Fact] [Test]
public void SqlParameterizerShouldThrowWhenLiteralHasTypeMismatch() public void SqlParameterizerShouldThrowWhenLiteralHasTypeMismatch()
{ {
// variable is declared an int but is getting set to character data // variable is declared an int but is getting set to character data
@@ -157,7 +158,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// the DbCommand object will throw an exception with the following message: /// the DbCommand object will throw an exception with the following message:
/// BeginExecuteReader: CommandText property has not been initialized /// BeginExecuteReader: CommandText property has not been initialized
/// </summary> /// </summary>
[Fact] [Test]
public void CommentOnlyBatchesShouldNotBeErasedFromCommandText() public void CommentOnlyBatchesShouldNotBeErasedFromCommandText()
{ {
string sql = $@" string sql = $@"
@@ -169,7 +170,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
command.Parameterize(); command.Parameterize();
Assert.False(string.IsNullOrEmpty(command.CommandText)); Assert.False(string.IsNullOrEmpty(command.CommandText));
Assert.Equal(expected: sql, actual: command.CommandText); Assert.AreEqual(expected: sql, actual: command.CommandText);
} }
#endregion #endregion
@@ -180,21 +181,21 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// When requesting a collection of <c>ScriptFileMarker</c> by calling the <c>SqlParameterizer.CodeSense</c> /// When requesting a collection of <c>ScriptFileMarker</c> by calling the <c>SqlParameterizer.CodeSense</c>
/// method, if a null script is passed in, the reuslt should be an empty collection. /// method, if a null script is passed in, the reuslt should be an empty collection.
/// </summary> /// </summary>
[Fact] [Test]
public void CodeSenseShouldReturnEmptyListWhenGivenANullScript() public void CodeSenseShouldReturnEmptyListWhenGivenANullScript()
{ {
string sql = null; string sql = null;
IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql); IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql);
Assert.NotNull(result); Assert.NotNull(result);
Assert.Empty(result); Assert.That(result, Is.Empty);
} }
/// <summary> /// <summary>
/// When requesting a collection of <c>ScriptFileMarker</c> by calling the <c>SqlParameterizer.CodeSense</c> /// When requesting a collection of <c>ScriptFileMarker</c> by calling the <c>SqlParameterizer.CodeSense</c>
/// method, if a script is passed in that contains no valid parameters, the reuslt should be an empty collection. /// method, if a script is passed in that contains no valid parameters, the reuslt should be an empty collection.
/// </summary> /// </summary>
[Fact] [Test]
public void CodeSenseShouldReturnEmptyListWhenGivenAParameterlessScript() public void CodeSenseShouldReturnEmptyListWhenGivenAParameterlessScript()
{ {
// SQL with no parameters // SQL with no parameters
@@ -206,7 +207,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql); IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql);
Assert.NotNull(result); Assert.NotNull(result);
Assert.Empty(result); Assert.That(result, Is.Empty);
} }
/// <summary> /// <summary>
@@ -214,7 +215,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// SQL statements larger than 300000 characters (Approximately 600 Kb) should /// SQL statements larger than 300000 characters (Approximately 600 Kb) should
/// return a max string sength code sense item. These will be returned to ADS to display to the user as intelli-sense. /// return a max string sength code sense item. These will be returned to ADS to display to the user as intelli-sense.
/// </summary> /// </summary>
[Fact] [Test]
public void CodeSenseShouldReturnMaxStringLengthScriptFileMarkerErrorItemWhenScriptIsTooLong() public void CodeSenseShouldReturnMaxStringLengthScriptFileMarkerErrorItemWhenScriptIsTooLong()
{ {
// SQL length of 300 characters // SQL length of 300 characters
@@ -235,10 +236,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
Console.WriteLine(result[0].Message); Console.WriteLine(result[0].Message);
Assert.NotEmpty(result); Assert.That(result, Is.Not.Empty);
Assert.Equal(expected: 1, actual: result.Count); Assert.AreEqual(expected: 1, actual: result.Count);
Assert.Equal(expected: ScriptFileMarkerLevel.Error, actual: result[0].Level); Assert.AreEqual(expected: ScriptFileMarkerLevel.Error, actual: result[0].Level);
Assert.Equal(expected: expectedMessage, actual: result[0].Message); Assert.AreEqual(expected: expectedMessage, actual: result[0].Message);
} }
/// <summary> /// <summary>
@@ -246,7 +247,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// method, if a script is passed in that contains 3 valid parameters, the reuslt should be a collection of /// method, if a script is passed in that contains 3 valid parameters, the reuslt should be a collection of
/// three informational code sense items. These will be returned to ADS to display to the user as intelli-sense. /// three informational code sense items. These will be returned to ADS to display to the user as intelli-sense.
/// </summary> /// </summary>
[Fact] [Test]
public void CodeSenseShouldReturnInformationalCodeSenseItemsForValidParameters() public void CodeSenseShouldReturnInformationalCodeSenseItemsForValidParameters()
{ {
const string ssn = "795-73-9838"; const string ssn = "795-73-9838";
@@ -263,8 +264,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql); IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql);
Assert.NotEmpty(result); Assert.That(result, Is.Not.Empty);
Assert.Equal(expected: 3, actual: result.Count); Assert.AreEqual(expected: 3, actual: result.Count);
Assert.True(Enumerable.All(result, i => i.Level == ScriptFileMarkerLevel.Information)); Assert.True(Enumerable.All(result, i => i.Level == ScriptFileMarkerLevel.Information));
} }
@@ -7,13 +7,14 @@
using System.Threading; using System.Threading;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion
{ {
[TestFixture]
public class AutoCompletionResultTest public class AutoCompletionResultTest
{ {
[Fact] [Test]
public void CompletionShouldRecordDuration() public void CompletionShouldRecordDuration()
{ {
AutoCompletionResult result = new AutoCompletionResult(); AutoCompletionResult result = new AutoCompletionResult();
@@ -6,13 +6,14 @@
using Microsoft.SqlTools.ServiceLayer.LanguageServices; using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion
{ {
[TestFixture]
public class ScriptDocumentInfoTest public class ScriptDocumentInfoTest
{ {
[Fact] [Test]
public void MetricsShouldGetSortedGivenUnSortedArray() public void MetricsShouldGetSortedGivenUnSortedArray()
{ {
TextDocumentPosition doc = new TextDocumentPosition() TextDocumentPosition doc = new TextDocumentPosition()
@@ -35,11 +36,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion
ScriptParseInfo scriptParseInfo = new ScriptParseInfo(); ScriptParseInfo scriptParseInfo = new ScriptParseInfo();
ScriptDocumentInfo docInfo = new ScriptDocumentInfo(doc, scriptFile, scriptParseInfo); ScriptDocumentInfo docInfo = new ScriptDocumentInfo(doc, scriptFile, scriptParseInfo);
Assert.Equal(docInfo.StartLine, 1); Assert.AreEqual(1, docInfo.StartLine);
Assert.Equal(docInfo.ParserLine, 2); Assert.AreEqual(2, docInfo.ParserLine);
Assert.Equal(docInfo.StartColumn, 44); Assert.AreEqual(44, docInfo.StartColumn);
Assert.Equal(docInfo.EndColumn, 14); Assert.AreEqual(14, docInfo.EndColumn);
Assert.Equal(docInfo.ParserColumn, 15); Assert.AreEqual(15, docInfo.ParserColumn);
} }
} }
} }
@@ -4,12 +4,13 @@
// //
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection; using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Xunit; using NUnit.Framework;
using Microsoft.Data.SqlClient; using Microsoft.Data.SqlClient;
using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Common;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{ {
[TestFixture]
/// <summary> /// <summary>
/// Tests for Sever Information Caching Class /// Tests for Sever Information Caching Class
/// </summary> /// </summary>
@@ -22,12 +23,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
cache = new CachedServerInfo(); cache = new CachedServerInfo();
} }
[Fact] [Test]
public void CacheMatchesNullDbNameToEmptyString() public void CacheMatchesNullDbNameToEmptyString()
{ {
// Set sqlDw result into cache // Set sqlDw result into cache
string dataSource = "testDataSource"; string dataSource = "testDataSource";
DatabaseEngineEdition engineEdition;
SqlConnectionStringBuilder testSource = new SqlConnectionStringBuilder SqlConnectionStringBuilder testSource = new SqlConnectionStringBuilder
{ {
DataSource = dataSource, DataSource = dataSource,
@@ -36,31 +36,26 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
cache.AddOrUpdateCache(testSource, DatabaseEngineEdition.SqlDataWarehouse, CachedServerInfo.CacheVariable.EngineEdition); cache.AddOrUpdateCache(testSource, DatabaseEngineEdition.SqlDataWarehouse, CachedServerInfo.CacheVariable.EngineEdition);
// Expect the same returned result // Expect the same returned result
Assert.Equal(cache.TryGetEngineEdition(testSource, out engineEdition), DatabaseEngineEdition.SqlDataWarehouse); Assert.AreEqual(DatabaseEngineEdition.SqlDataWarehouse, cache.TryGetEngineEdition(testSource, out _));
// And expect the same for the null string // And expect the same for the null string
Assert.Equal(cache.TryGetEngineEdition(new SqlConnectionStringBuilder Assert.AreEqual(DatabaseEngineEdition.SqlDataWarehouse, cache.TryGetEngineEdition(new SqlConnectionStringBuilder
{ {
DataSource = dataSource DataSource = dataSource
// Initial Catalog is null. Can't set explicitly as this throws // Initial Catalog is null. Can't set explicitly as this throws
}, out engineEdition), DatabaseEngineEdition.SqlDataWarehouse); }, out _));
// But expect NotEqual for a different DB Assert.That(cache.TryGetEngineEdition(new SqlConnectionStringBuilder
Assert.NotEqual(cache.TryGetEngineEdition(new SqlConnectionStringBuilder
{ {
DataSource = dataSource, DataSource = dataSource,
InitialCatalog = "OtherDb" InitialCatalog = "OtherDb"
}, out engineEdition), DatabaseEngineEdition.SqlDataWarehouse); }, out _), Is.Not.EqualTo(DatabaseEngineEdition.SqlDataWarehouse), "expect NotEqual for a different DB");
} }
[Theory]
[InlineData(null, DatabaseEngineEdition.SqlDataWarehouse)] // is SqlDW instance [Test]
[InlineData("", DatabaseEngineEdition.SqlDataWarehouse)] // is SqlDW instance public void AddOrUpdateEngineEdition([Values(null, "", "myDb")] string dbName,
[InlineData("myDb", DatabaseEngineEdition.SqlDataWarehouse)] // is SqlDW instance [Values(DatabaseEngineEdition.SqlDataWarehouse, DatabaseEngineEdition.SqlOnDemand)] DatabaseEngineEdition state)
[InlineData(null, DatabaseEngineEdition.SqlOnDemand)] // is SqlOnDemand Instance
[InlineData("", DatabaseEngineEdition.SqlOnDemand)] // is SqlOnDemand Instance
[InlineData("myDb", DatabaseEngineEdition.SqlOnDemand)] // is SqlOnDemand instance
public void AddOrUpdateEngineEditiopn(string dbName, DatabaseEngineEdition state)
{ {
// Set result into cache // Set result into cache
DatabaseEngineEdition engineEdition; DatabaseEngineEdition engineEdition;
@@ -75,15 +70,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
cache.AddOrUpdateCache(testSource, state, CachedServerInfo.CacheVariable.EngineEdition); cache.AddOrUpdateCache(testSource, state, CachedServerInfo.CacheVariable.EngineEdition);
// Expect the same returned result Assert.Multiple(() =>
Assert.NotEqual(cache.TryGetEngineEdition(testSource, out engineEdition), DatabaseEngineEdition.Unknown); {
Assert.Equal(engineEdition, state); Assert.That(cache.TryGetEngineEdition(testSource, out engineEdition), Is.Not.EqualTo(DatabaseEngineEdition.Unknown) );
Assert.That(engineEdition, Is.EqualTo(state), "Expect the same returned result");
});
} }
[Theory] [Test]
[InlineData(DatabaseEngineEdition.SqlDataWarehouse)] // is SqlDW instance public void AddOrUpdateEngineEditionToggle([Values(DatabaseEngineEdition.SqlDataWarehouse, DatabaseEngineEdition.SqlOnDemand)] DatabaseEngineEdition state)
[InlineData(DatabaseEngineEdition.SqlOnDemand)] // is SqlOnDemand Instance
public void AddOrUpdateEngineEditionToggle(DatabaseEngineEdition state)
{ {
// Set result into cache // Set result into cache
DatabaseEngineEdition engineEdition; DatabaseEngineEdition engineEdition;
@@ -93,21 +88,25 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
}; };
cache.AddOrUpdateCache(testSource, state, CachedServerInfo.CacheVariable.EngineEdition); cache.AddOrUpdateCache(testSource, state, CachedServerInfo.CacheVariable.EngineEdition);
// Expect the same returned result Assert.Multiple(() =>
Assert.NotEqual(cache.TryGetEngineEdition(testSource, out engineEdition), DatabaseEngineEdition.Unknown); {
Assert.Equal(engineEdition, state); Assert.That(cache.TryGetEngineEdition(testSource, out engineEdition), Is.Not.EqualTo(DatabaseEngineEdition.Unknown));
Assert.That(engineEdition, Is.EqualTo(state), "Expect the same returned result");
});
DatabaseEngineEdition newState = state == DatabaseEngineEdition.SqlDataWarehouse ? DatabaseEngineEdition newState = state == DatabaseEngineEdition.SqlDataWarehouse ?
DatabaseEngineEdition.SqlOnDemand : DatabaseEngineEdition.SqlDataWarehouse; DatabaseEngineEdition.SqlOnDemand : DatabaseEngineEdition.SqlDataWarehouse;
cache.AddOrUpdateCache(testSource, newState, CachedServerInfo.CacheVariable.EngineEdition); cache.AddOrUpdateCache(testSource, newState, CachedServerInfo.CacheVariable.EngineEdition);
// Expect the opposite returned result Assert.Multiple(() =>
Assert.NotEqual(cache.TryGetEngineEdition(testSource, out engineEdition), DatabaseEngineEdition.Unknown); {
Assert.Equal(engineEdition, newState); Assert.That(cache.TryGetEngineEdition(testSource, out engineEdition), Is.Not.EqualTo(DatabaseEngineEdition.Unknown));
Assert.That(engineEdition, Is.EqualTo(newState), "Expect the opposite returned result");
});
} }
/* [Fact] /* [Test]
public void AddOrUpdateIsSqlDwFalseToggle() public void AddOrUpdateIsSqlDwFalseToggle()
{ {
bool state = true; bool state = true;
@@ -142,22 +141,21 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
Assert.True(cache.TryGetIsSqlDw(differentServerSameDb, out isSqlDwResult3)); Assert.True(cache.TryGetIsSqlDw(differentServerSameDb, out isSqlDwResult3));
// Assert cache is set on a per connection basis // Assert cache is set on a per connection basis
Assert.Equal(isSqlDwResult, state); Assert.AreEqual(isSqlDwResult, state);
Assert.Equal(isSqlDwResult2, !state); Assert.AreEqual(isSqlDwResult2, !state);
Assert.Equal(isSqlDwResult3, !state); Assert.AreEqual(isSqlDwResult3, !state);
} }
*/ */
[Fact] [Test]
public void AskforEngineEditionBeforeCached() public void AskforEngineEditionBeforeCached()
{ {
DatabaseEngineEdition engineEdition; Assert.AreEqual(DatabaseEngineEdition.Unknown, cache.TryGetEngineEdition(new SqlConnectionStringBuilder
Assert.Equal(cache.TryGetEngineEdition(new SqlConnectionStringBuilder
{ {
DataSource = "testDataSourceUnCached" DataSource = "testDataSourceUnCached"
}, },
out engineEdition), DatabaseEngineEdition.Unknown); out _));
} }
} }
} }
@@ -6,17 +6,18 @@
using System.Linq; using System.Linq;
using Microsoft.SqlTools.Hosting.Contracts; using Microsoft.SqlTools.Hosting.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Xunit; using NUnit.Framework;
using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.Connection;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{ {
[TestFixture]
/// <summary> /// <summary>
/// Tests for ConnectionDetails Class /// Tests for ConnectionDetails Class
/// </summary> /// </summary>
public class ConnectionDetailsTests public class ConnectionDetailsTests
{ {
[Fact] [Test]
public void ConnectionDetailsWithoutAnyOptionShouldReturnNullOrDefaultForOptions() public void ConnectionDetailsWithoutAnyOptionShouldReturnNullOrDefaultForOptions()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
@@ -25,39 +26,39 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
var expectedForInt = default(int?); var expectedForInt = default(int?);
var expectedForBoolean = default(bool?); var expectedForBoolean = default(bool?);
Assert.Equal(details.ApplicationIntent, expectedForStrings); Assert.AreEqual(details.ApplicationIntent, expectedForStrings);
Assert.Equal(details.ApplicationName, expectedForStrings); Assert.AreEqual(details.ApplicationName, expectedForStrings);
Assert.Equal(details.AttachDbFilename, expectedForStrings); Assert.AreEqual(details.AttachDbFilename, expectedForStrings);
Assert.Equal(details.AuthenticationType, expectedForStrings); Assert.AreEqual(details.AuthenticationType, expectedForStrings);
Assert.Equal(details.CurrentLanguage, expectedForStrings); Assert.AreEqual(details.CurrentLanguage, expectedForStrings);
Assert.Equal(details.DatabaseName, expectedForStrings); Assert.AreEqual(details.DatabaseName, expectedForStrings);
Assert.Equal(details.FailoverPartner, expectedForStrings); Assert.AreEqual(details.FailoverPartner, expectedForStrings);
Assert.Equal(details.Password, expectedForStrings); Assert.AreEqual(details.Password, expectedForStrings);
Assert.Equal(details.ServerName, expectedForStrings); Assert.AreEqual(details.ServerName, expectedForStrings);
Assert.Equal(details.TypeSystemVersion, expectedForStrings); Assert.AreEqual(details.TypeSystemVersion, expectedForStrings);
Assert.Equal(details.UserName, expectedForStrings); Assert.AreEqual(details.UserName, expectedForStrings);
Assert.Equal(details.WorkstationId, expectedForStrings); Assert.AreEqual(details.WorkstationId, expectedForStrings);
Assert.Equal(details.ConnectRetryInterval, expectedForInt); Assert.AreEqual(details.ConnectRetryInterval, expectedForInt);
Assert.Equal(details.ConnectRetryCount, expectedForInt); Assert.AreEqual(details.ConnectRetryCount, expectedForInt);
Assert.Equal(details.ConnectTimeout, expectedForInt); Assert.AreEqual(details.ConnectTimeout, expectedForInt);
Assert.Equal(details.LoadBalanceTimeout, expectedForInt); Assert.AreEqual(details.LoadBalanceTimeout, expectedForInt);
Assert.Equal(details.MaxPoolSize, expectedForInt); Assert.AreEqual(details.MaxPoolSize, expectedForInt);
Assert.Equal(details.MinPoolSize, expectedForInt); Assert.AreEqual(details.MinPoolSize, expectedForInt);
Assert.Equal(details.PacketSize, expectedForInt); Assert.AreEqual(details.PacketSize, expectedForInt);
Assert.Equal(details.ColumnEncryptionSetting, expectedForStrings); Assert.AreEqual(details.ColumnEncryptionSetting, expectedForStrings);
Assert.Equal(details.EnclaveAttestationUrl, expectedForStrings); Assert.AreEqual(details.EnclaveAttestationUrl, expectedForStrings);
Assert.Equal(details.EnclaveAttestationProtocol, expectedForStrings); Assert.AreEqual(details.EnclaveAttestationProtocol, expectedForStrings);
Assert.Equal(details.Encrypt, expectedForBoolean); Assert.AreEqual(details.Encrypt, expectedForBoolean);
Assert.Equal(details.MultipleActiveResultSets, expectedForBoolean); Assert.AreEqual(details.MultipleActiveResultSets, expectedForBoolean);
Assert.Equal(details.MultiSubnetFailover, expectedForBoolean); Assert.AreEqual(details.MultiSubnetFailover, expectedForBoolean);
Assert.Equal(details.PersistSecurityInfo, expectedForBoolean); Assert.AreEqual(details.PersistSecurityInfo, expectedForBoolean);
Assert.Equal(details.Pooling, expectedForBoolean); Assert.AreEqual(details.Pooling, expectedForBoolean);
Assert.Equal(details.Replication, expectedForBoolean); Assert.AreEqual(details.Replication, expectedForBoolean);
Assert.Equal(details.TrustServerCertificate, expectedForBoolean); Assert.AreEqual(details.TrustServerCertificate, expectedForBoolean);
Assert.Equal(details.Port, expectedForInt); Assert.AreEqual(details.Port, expectedForInt);
} }
[Fact] [Test]
public void ConnectionDetailsPropertySettersShouldSetOptionValuesCorrectly() public void ConnectionDetailsPropertySettersShouldSetOptionValuesCorrectly()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
@@ -97,39 +98,39 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
details.Port = expectedForInt + index++; details.Port = expectedForInt + index++;
index = 0; index = 0;
Assert.Equal(details.ApplicationIntent, expectedForStrings + index++); Assert.AreEqual(details.ApplicationIntent, expectedForStrings + index++);
Assert.Equal(details.ApplicationName, expectedForStrings + index++); Assert.AreEqual(details.ApplicationName, expectedForStrings + index++);
Assert.Equal(details.AttachDbFilename, expectedForStrings + index++); Assert.AreEqual(details.AttachDbFilename, expectedForStrings + index++);
Assert.Equal(details.AuthenticationType, expectedForStrings + index++); Assert.AreEqual(details.AuthenticationType, expectedForStrings + index++);
Assert.Equal(details.CurrentLanguage, expectedForStrings + index++); Assert.AreEqual(details.CurrentLanguage, expectedForStrings + index++);
Assert.Equal(details.DatabaseName, expectedForStrings + index++); Assert.AreEqual(details.DatabaseName, expectedForStrings + index++);
Assert.Equal(details.FailoverPartner, expectedForStrings + index++); Assert.AreEqual(details.FailoverPartner, expectedForStrings + index++);
Assert.Equal(details.Password, expectedForStrings + index++); Assert.AreEqual(details.Password, expectedForStrings + index++);
Assert.Equal(details.ServerName, expectedForStrings + index++); Assert.AreEqual(details.ServerName, expectedForStrings + index++);
Assert.Equal(details.TypeSystemVersion, expectedForStrings + index++); Assert.AreEqual(details.TypeSystemVersion, expectedForStrings + index++);
Assert.Equal(details.UserName, expectedForStrings + index++); Assert.AreEqual(details.UserName, expectedForStrings + index++);
Assert.Equal(details.WorkstationId, expectedForStrings + index++); Assert.AreEqual(details.WorkstationId, expectedForStrings + index++);
Assert.Equal(details.ConnectRetryInterval, expectedForInt + index++); Assert.AreEqual(details.ConnectRetryInterval, expectedForInt + index++);
Assert.Equal(details.ConnectRetryCount, expectedForInt + index++); Assert.AreEqual(details.ConnectRetryCount, expectedForInt + index++);
Assert.Equal(details.ConnectTimeout, expectedForInt + index++); Assert.AreEqual(details.ConnectTimeout, expectedForInt + index++);
Assert.Equal(details.LoadBalanceTimeout, expectedForInt + index++); Assert.AreEqual(details.LoadBalanceTimeout, expectedForInt + index++);
Assert.Equal(details.MaxPoolSize, expectedForInt + index++); Assert.AreEqual(details.MaxPoolSize, expectedForInt + index++);
Assert.Equal(details.MinPoolSize, expectedForInt + index++); Assert.AreEqual(details.MinPoolSize, expectedForInt + index++);
Assert.Equal(details.PacketSize, expectedForInt + index++); Assert.AreEqual(details.PacketSize, expectedForInt + index++);
Assert.Equal(details.ColumnEncryptionSetting, expectedForStrings + index++); Assert.AreEqual(details.ColumnEncryptionSetting, expectedForStrings + index++);
Assert.Equal(details.EnclaveAttestationProtocol, expectedForStrings + index++); Assert.AreEqual(details.EnclaveAttestationProtocol, expectedForStrings + index++);
Assert.Equal(details.EnclaveAttestationUrl, expectedForStrings + index++); Assert.AreEqual(details.EnclaveAttestationUrl, expectedForStrings + index++);
Assert.Equal(details.Encrypt, (index++ % 2 == 0)); Assert.AreEqual(details.Encrypt, (index++ % 2 == 0));
Assert.Equal(details.MultipleActiveResultSets, (index++ % 2 == 0)); Assert.AreEqual(details.MultipleActiveResultSets, (index++ % 2 == 0));
Assert.Equal(details.MultiSubnetFailover, (index++ % 2 == 0)); Assert.AreEqual(details.MultiSubnetFailover, (index++ % 2 == 0));
Assert.Equal(details.PersistSecurityInfo, (index++ % 2 == 0)); Assert.AreEqual(details.PersistSecurityInfo, (index++ % 2 == 0));
Assert.Equal(details.Pooling, (index++ % 2 == 0)); Assert.AreEqual(details.Pooling, (index++ % 2 == 0));
Assert.Equal(details.Replication, (index++ % 2 == 0)); Assert.AreEqual(details.Replication, (index++ % 2 == 0));
Assert.Equal(details.TrustServerCertificate, (index++ % 2 == 0)); Assert.AreEqual(details.TrustServerCertificate, (index++ % 2 == 0));
Assert.Equal(details.Port, (expectedForInt + index++)); Assert.AreEqual(details.Port, (expectedForInt + index++));
} }
[Fact] [Test]
public void ConnectionDetailsOptionsShouldBeDefinedInConnectionProviderOptions() public void ConnectionDetailsOptionsShouldBeDefinedInConnectionProviderOptions()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
@@ -195,7 +196,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
} }
[Fact] [Test]
public void SettingConnectiomTimeoutToLongShouldStillReturnInt() public void SettingConnectiomTimeoutToLongShouldStillReturnInt()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
@@ -204,27 +205,27 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
int? expectedValue = 30; int? expectedValue = 30;
details.Options["connectTimeout"] = timeout; details.Options["connectTimeout"] = timeout;
Assert.Equal(details.ConnectTimeout, expectedValue); Assert.AreEqual(details.ConnectTimeout, expectedValue);
} }
[Fact] [Test]
public void ConnectTimeoutShouldReturnNullIfNotSet() public void ConnectTimeoutShouldReturnNullIfNotSet()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
int? expectedValue = null; int? expectedValue = null;
Assert.Equal(details.ConnectTimeout, expectedValue); Assert.AreEqual(details.ConnectTimeout, expectedValue);
} }
[Fact] [Test]
public void ConnectTimeoutShouldReturnNullIfSetToNull() public void ConnectTimeoutShouldReturnNullIfSetToNull()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
details.Options["connectTimeout"] = null; details.Options["connectTimeout"] = null;
int? expectedValue = null; int? expectedValue = null;
Assert.Equal(details.ConnectTimeout, expectedValue); Assert.AreEqual(details.ConnectTimeout, expectedValue);
} }
[Fact] [Test]
public void SettingEncryptToStringShouldStillReturnBoolean() public void SettingEncryptToStringShouldStillReturnBoolean()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
@@ -233,10 +234,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
bool? expectedValue = true; bool? expectedValue = true;
details.Options["encrypt"] = encrypt; details.Options["encrypt"] = encrypt;
Assert.Equal(details.Encrypt, expectedValue); Assert.AreEqual(details.Encrypt, expectedValue);
} }
[Fact] [Test]
public void SettingEncryptToLowecaseStringShouldStillReturnBoolean() public void SettingEncryptToLowecaseStringShouldStillReturnBoolean()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
@@ -245,27 +246,27 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
bool? expectedValue = true; bool? expectedValue = true;
details.Options["encrypt"] = encrypt; details.Options["encrypt"] = encrypt;
Assert.Equal(details.Encrypt, expectedValue); Assert.AreEqual(details.Encrypt, expectedValue);
} }
[Fact] [Test]
public void EncryptShouldReturnNullIfNotSet() public void EncryptShouldReturnNullIfNotSet()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
bool? expectedValue = null; bool? expectedValue = null;
Assert.Equal(details.Encrypt, expectedValue); Assert.AreEqual(details.Encrypt, expectedValue);
} }
[Fact] [Test]
public void EncryptShouldReturnNullIfSetToNull() public void EncryptShouldReturnNullIfSetToNull()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
details.Options["encrypt"] = null; details.Options["encrypt"] = null;
int? expectedValue = null; int? expectedValue = null;
Assert.Equal(details.ConnectTimeout, expectedValue); Assert.AreEqual(details.ConnectTimeout, expectedValue);
} }
[Fact] [Test]
public void SettingConnectiomTimeoutToLongWhichCannotBeConvertedToIntShouldNotCrash() public void SettingConnectiomTimeoutToLongWhichCannotBeConvertedToIntShouldNotCrash()
{ {
ConnectionDetails details = new ConnectionDetails(); ConnectionDetails details = new ConnectionDetails();
@@ -275,8 +276,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
details.Options["connectTimeout"] = timeout; details.Options["connectTimeout"] = timeout;
details.Options["encrypt"] = true; details.Options["encrypt"] = true;
Assert.Equal(details.ConnectTimeout, expectedValue); Assert.AreEqual(details.ConnectTimeout, expectedValue);
Assert.Equal(details.Encrypt, true); Assert.AreEqual(true, details.Encrypt);
} }
} }
} }
File diff suppressed because it is too large Load Diff
@@ -6,16 +6,17 @@
using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.LanguageServices; using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Moq; using Moq;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{ {
[TestFixture]
public class DatabaseLocksManagerTests public class DatabaseLocksManagerTests
{ {
private const string server1 = "server1"; private const string server1 = "server1";
private const string database1 = "database1"; private const string database1 = "database1";
[Fact] [Test]
public void GainFullAccessShouldDisconnectTheConnections() public void GainFullAccessShouldDisconnectTheConnections()
{ {
var connectionLock = new Mock<IConnectedBindingQueue>(); var connectionLock = new Mock<IConnectedBindingQueue>();
@@ -30,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
} }
} }
[Fact] [Test]
public void ReleaseAccessShouldConnectTheConnections() public void ReleaseAccessShouldConnectTheConnections()
{ {
var connectionLock = new Mock<IConnectedBindingQueue>(); var connectionLock = new Mock<IConnectedBindingQueue>();
@@ -45,7 +46,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
} }
} }
//[Fact] //[Test]
public void SecondProcessToGainAccessShouldWaitForTheFirstProcess() public void SecondProcessToGainAccessShouldWaitForTheFirstProcess()
{ {
var connectionLock = new Mock<IConnectedBindingQueue>(); var connectionLock = new Mock<IConnectedBindingQueue>();
@@ -62,9 +63,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{ {
secondTimeGettingAccessFails = true; secondTimeGettingAccessFails = true;
} }
Assert.Equal(secondTimeGettingAccessFails, true); Assert.AreEqual(true, secondTimeGettingAccessFails);
databaseLocksManager.ReleaseAccess(server1, database1); databaseLocksManager.ReleaseAccess(server1, database1);
Assert.Equal(databaseLocksManager.GainFullAccessToDatabase(server1, database1), true); Assert.AreEqual(true, databaseLocksManager.GainFullAccessToDatabase(server1, database1));
databaseLocksManager.ReleaseAccess(server1, database1); databaseLocksManager.ReleaseAccess(server1, database1);
} }
} }
@@ -7,16 +7,17 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection; using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{ {
[TestFixture]
/// <summary> /// <summary>
/// Tests for ReliableConnection code /// Tests for ReliableConnection code
/// </summary> /// </summary>
public class ReliableConnectionTests public class ReliableConnectionTests
{ {
[Fact] [Test]
public void ReliableSqlConnectionUsesAzureToken() public void ReliableSqlConnectionUsesAzureToken()
{ {
ConnectionDetails details = TestObjects.GetTestConnectionDetails(); ConnectionDetails details = TestObjects.GetTestConnectionDetails();
@@ -30,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
var reliableConnection = new ReliableSqlConnection(connectionString, retryPolicy, retryPolicy, azureAccountToken); var reliableConnection = new ReliableSqlConnection(connectionString, retryPolicy, retryPolicy, azureAccountToken);
// Then the connection's azureAccountToken gets set // Then the connection's azureAccountToken gets set
Assert.Equal(azureAccountToken, reliableConnection.GetUnderlyingConnection().AccessToken); Assert.AreEqual(azureAccountToken, reliableConnection.GetUnderlyingConnection().AccessToken);
} }
} }
} }
@@ -12,16 +12,17 @@ using Microsoft.SqlTools.Credentials.Contracts;
using Microsoft.SqlTools.Credentials.Linux; using Microsoft.SqlTools.Credentials.Linux;
using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
{ {
[TestFixture]
/// <summary> /// <summary>
/// Credential Service tests that should pass on all platforms, regardless of backing store. /// Credential Service tests that should pass on all platforms, regardless of backing store.
/// These tests run E2E, storing values in the native credential store for whichever platform /// These tests run E2E, storing values in the native credential store for whichever platform
/// tests are being run on /// tests are being run on
/// </summary> /// </summary>
public class CredentialServiceTests : IDisposable public class CredentialServiceTests
{ {
private static readonly StoreConfig Config = new StoreConfig private static readonly StoreConfig Config = new StoreConfig
{ {
@@ -39,18 +40,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
// Test-owned credential store used to clean up before/after tests to ensure code works as expected // Test-owned credential store used to clean up before/after tests to ensure code works as expected
// even if previous runs stopped midway through // even if previous runs stopped midway through
private readonly ICredentialStore credStore; private ICredentialStore credStore;
private readonly CredentialService service; private CredentialService service;
/// <summary>
/// Constructor called once for every test [SetUp]
/// </summary> public void SetupCredentialServiceTests()
public CredentialServiceTests()
{ {
credStore = CredentialService.GetStoreForOS(Config); credStore = CredentialService.GetStoreForOS(Config);
service = new CredentialService(credStore, Config); service = new CredentialService(credStore, Config);
DeleteDefaultCreds(); DeleteDefaultCreds();
} }
[TearDown]
public void Dispose() public void Dispose()
{ {
DeleteDefaultCreds(); DeleteDefaultCreds();
@@ -73,7 +74,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
#endif #endif
} }
[Fact] [Test]
public async Task SaveCredentialThrowsIfCredentialIdMissing() public async Task SaveCredentialThrowsIfCredentialIdMissing()
{ {
string errorResponse = null; string errorResponse = null;
@@ -81,10 +82,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
await service.HandleSaveCredentialRequest(new Credential(null), contextMock.Object); await service.HandleSaveCredentialRequest(new Credential(null), contextMock.Object);
TestUtils.VerifyErrorSent(contextMock); TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentException", errorResponse); Assert.That(errorResponse, Does.Contain("ArgumentException"));
} }
[Fact] [Test]
public async Task SaveCredentialThrowsIfPasswordMissing() public async Task SaveCredentialThrowsIfPasswordMissing()
{ {
string errorResponse = null; string errorResponse = null;
@@ -95,7 +96,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
Assert.True(errorResponse.Contains("ArgumentException") || errorResponse.Contains("ArgumentNullException")); Assert.True(errorResponse.Contains("ArgumentException") || errorResponse.Contains("ArgumentNullException"));
} }
[Fact] [Test]
public async Task SaveCredentialWorksForSingleCredential() public async Task SaveCredentialWorksForSingleCredential()
{ {
await TestUtils.RunAndVerify<bool>( await TestUtils.RunAndVerify<bool>(
@@ -103,7 +104,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: Assert.True); verify: Assert.True);
} }
[Fact] [Test]
public async Task SaveCredentialWorksForEmptyPassword() public async Task SaveCredentialWorksForEmptyPassword()
{ {
await TestUtils.RunAndVerify<bool>( await TestUtils.RunAndVerify<bool>(
@@ -111,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: Assert.True); verify: Assert.True);
} }
[Fact] [Test]
public async Task SaveCredentialSupportsSavingCredentialMultipleTimes() public async Task SaveCredentialSupportsSavingCredentialMultipleTimes()
{ {
await TestUtils.RunAndVerify<bool>( await TestUtils.RunAndVerify<bool>(
@@ -123,7 +124,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: Assert.True); verify: Assert.True);
} }
[Fact] [Test]
public async Task ReadCredentialWorksForSingleCredential() public async Task ReadCredentialWorksForSingleCredential()
{ {
// Given we have saved the credential // Given we have saved the credential
@@ -137,11 +138,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId, null), requestContext), test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId, null), requestContext),
verify: (actual => verify: (actual =>
{ {
Assert.Equal(Password1, actual.Password); Assert.AreEqual(Password1, actual.Password);
})); }));
} }
[Fact] [Test]
public async Task ReadCredentialWorksForMultipleCredentials() public async Task ReadCredentialWorksForMultipleCredentials()
{ {
@@ -159,17 +160,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId, null), requestContext), test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId, null), requestContext),
verify: (actual => verify: (actual =>
{ {
Assert.Equal(Password1, actual.Password); Assert.AreEqual(Password1, actual.Password);
})); }));
await TestUtils.RunAndVerify<Credential>( await TestUtils.RunAndVerify<Credential>(
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(OtherCredId, null), requestContext), test: (requestContext) => service.HandleReadCredentialRequest(new Credential(OtherCredId, null), requestContext),
verify: (actual => verify: (actual =>
{ {
Assert.Equal(OtherPassword, actual.Password); Assert.AreEqual(OtherPassword, actual.Password);
})); }));
} }
[Fact] [Test]
public async Task ReadCredentialHandlesPasswordUpdate() public async Task ReadCredentialHandlesPasswordUpdate()
{ {
// Given we have saved twice with a different password // Given we have saved twice with a different password
@@ -187,11 +188,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId), requestContext), test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId), requestContext),
verify: (actual => verify: (actual =>
{ {
Assert.Equal(Password2, actual.Password); Assert.AreEqual(Password2, actual.Password);
})); }));
} }
[Fact] [Test]
public async Task ReadCredentialThrowsIfCredentialIsNull() public async Task ReadCredentialThrowsIfCredentialIsNull()
{ {
string errorResponse = null; string errorResponse = null;
@@ -200,10 +201,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
// Verify throws on null, and this is sent as an error // Verify throws on null, and this is sent as an error
await service.HandleReadCredentialRequest(null, contextMock.Object); await service.HandleReadCredentialRequest(null, contextMock.Object);
TestUtils.VerifyErrorSent(contextMock); TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentNullException", errorResponse); Assert.That(errorResponse, Does.Contain("ArgumentNullException"));
} }
[Fact] [Test]
public async Task ReadCredentialThrowsIfIdMissing() public async Task ReadCredentialThrowsIfIdMissing()
{ {
string errorResponse = null; string errorResponse = null;
@@ -212,10 +213,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
// Verify throws with no ID // Verify throws with no ID
await service.HandleReadCredentialRequest(new Credential(), contextMock.Object); await service.HandleReadCredentialRequest(new Credential(), contextMock.Object);
TestUtils.VerifyErrorSent(contextMock); TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentException", errorResponse); Assert.That(errorResponse, Does.Contain("ArgumentException"));
} }
[Fact] [Test]
public async Task ReadCredentialReturnsNullPasswordForMissingCredential() public async Task ReadCredentialReturnsNullPasswordForMissingCredential()
{ {
// Given a credential whose password doesn't exist // Given a credential whose password doesn't exist
@@ -228,12 +229,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: (actual => verify: (actual =>
{ {
Assert.NotNull(actual); Assert.NotNull(actual);
Assert.Equal(credWithNoPassword, actual.CredentialId); Assert.AreEqual(credWithNoPassword, actual.CredentialId);
Assert.Null(actual.Password); Assert.Null(actual.Password);
})); }));
} }
[Fact] [Test]
public async Task DeleteCredentialThrowsIfIdMissing() public async Task DeleteCredentialThrowsIfIdMissing()
{ {
object errorResponse = null; object errorResponse = null;
@@ -245,7 +246,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
Assert.True(((string)errorResponse).Contains("ArgumentException")); Assert.True(((string)errorResponse).Contains("ArgumentException"));
} }
[Fact] [Test]
public async Task DeleteCredentialReturnsTrueOnlyIfCredentialExisted() public async Task DeleteCredentialReturnsTrueOnlyIfCredentialExisted()
{ {
// Save should be true // Save should be true
@@ -6,13 +6,14 @@
using Microsoft.SqlTools.Credentials; using Microsoft.SqlTools.Credentials;
using Microsoft.SqlTools.Credentials.Linux; using Microsoft.SqlTools.Credentials.Linux;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Linux namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Linux
{ {
[TestFixture]
public class LinuxInteropTests public class LinuxInteropTests
{ {
[Fact] [Test]
public void GetEUidReturnsInt() public void GetEUidReturnsInt()
{ {
#if !WINDOWS_ONLY_BUILD #if !WINDOWS_ONLY_BUILD
@@ -23,14 +24,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Linux
#endif #endif
} }
[Fact] [Test]
public void GetHomeDirectoryFromPwFindsHomeDir() public void GetHomeDirectoryFromPwFindsHomeDir()
{ {
#if !WINDOWS_ONLY_BUILD #if !WINDOWS_ONLY_BUILD
RunIfWrapper.RunIfLinux(() => RunIfWrapper.RunIfLinux(() =>
{ {
string userDir = LinuxCredentialStore.GetHomeDirectoryFromPw(); string userDir = LinuxCredentialStore.GetHomeDirectoryFromPw();
Assert.StartsWith("/", userDir); Assert.That(userDir, Does.StartWith("/"), "GetHomeDirectoryFromPw");
}); });
#endif #endif
} }
@@ -6,13 +6,14 @@
using System; using System;
using Microsoft.SqlTools.Credentials.Win32; using Microsoft.SqlTools.Credentials.Win32;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32 namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
{ {
[TestFixture]
public class CredentialSetTests public class CredentialSetTests
{ {
[Fact] [Test]
public void CredentialSetCreate() public void CredentialSetCreate()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -21,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void CredentialSetCreateWithTarget() public void CredentialSetCreateWithTarget()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -30,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void CredentialSetShouldBeIDisposable() public void CredentialSetShouldBeIDisposable()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -39,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void CredentialSetLoad() public void CredentialSetLoad()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -56,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
CredentialSet set = new CredentialSet(); CredentialSet set = new CredentialSet();
set.Load(); set.Load();
Assert.NotNull(set); Assert.NotNull(set);
Assert.NotEmpty(set); Assert.That(set, Is.Not.Empty);
credential.Delete(); credential.Delete();
@@ -64,19 +65,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void CredentialSetLoadShouldReturnSelf() public void CredentialSetLoadShouldReturnSelf()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
{ {
CredentialSet set = new CredentialSet(); CredentialSet set = new CredentialSet();
Assert.IsType<CredentialSet>(set.Load()); Assert.That(set.Load(), Is.SameAs(set));
set.Dispose(); set.Dispose();
}); });
} }
[Fact] [Test]
public void CredentialSetLoadWithTargetFilter() public void CredentialSetLoadWithTargetFilter()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -90,7 +91,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
credential.Save(); credential.Save();
CredentialSet set = new CredentialSet("filtertarget"); CredentialSet set = new CredentialSet("filtertarget");
Assert.Equal(1, set.Load().Count); Assert.AreEqual(1, set.Load().Count);
set.Dispose(); set.Dispose();
}); });
} }
@@ -6,13 +6,14 @@
using System; using System;
using Microsoft.SqlTools.Credentials.Win32; using Microsoft.SqlTools.Credentials.Win32;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32 namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
{ {
[TestFixture]
public class Win32CredentialTests public class Win32CredentialTests
{ {
[Fact] [Test]
public void Credential_Create_ShouldNotThrowNull() public void Credential_Create_ShouldNotThrowNull()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -21,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_Create_With_Username_ShouldNotThrowNull() public void Credential_Create_With_Username_ShouldNotThrowNull()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -30,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_Create_With_Username_And_Password_ShouldNotThrowNull() public void Credential_Create_With_Username_And_Password_ShouldNotThrowNull()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -39,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_Create_With_Username_Password_Target_ShouldNotThrowNull() public void Credential_Create_With_Username_Password_Target_ShouldNotThrowNull()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -48,7 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_ShouldBe_IDisposable() public void Credential_ShouldBe_IDisposable()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -57,7 +58,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_Dispose_ShouldNotThrowException() public void Credential_Dispose_ShouldNotThrowException()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -66,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_ShouldThrowObjectDisposedException() public void Credential_ShouldThrowObjectDisposedException()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -77,7 +78,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_Save() public void Credential_Save()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -88,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_Delete() public void Credential_Delete()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -98,7 +99,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_Delete_NullTerminator() public void Credential_Delete_NullTerminator()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -109,7 +110,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
}); });
} }
[Fact] [Test]
public void Credential_Load() public void Credential_Load()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -120,15 +121,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
Win32Credential credential = new Win32Credential { Target = "target", Type = CredentialType.Generic }; Win32Credential credential = new Win32Credential { Target = "target", Type = CredentialType.Generic };
Assert.True(credential.Load()); Assert.True(credential.Load());
Assert.NotEmpty(credential.Username); Assert.That(credential.Username, Is.Not.Empty);
Assert.NotNull(credential.Password); Assert.NotNull(credential.Password);
Assert.Equal("username", credential.Username); Assert.AreEqual("username", credential.Username);
Assert.Equal("password", credential.Password); Assert.AreEqual("password", credential.Password);
Assert.Equal("target", credential.Target); Assert.AreEqual("target", credential.Target);
}); });
} }
[Fact] [Test]
public void Credential_Exists_Target_ShouldNotBeNull() public void Credential_Exists_Target_ShouldNotBeNull()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
@@ -5,13 +5,14 @@
using System; using System;
using Microsoft.SqlTools.ServiceLayer.DacFx; using Microsoft.SqlTools.ServiceLayer.DacFx;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DacFx namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DacFx
{ {
[TestFixture]
public class DacFxTests public class DacFxTests
{ {
[Fact] [Test]
public void ExtractParseVersionShouldThrowExceptionGivenInvalidVersion() public void ExtractParseVersionShouldThrowExceptionGivenInvalidVersion()
{ {
string invalidVersion = "invalidVerison"; string invalidVersion = "invalidVerison";
@@ -7,7 +7,7 @@ using Microsoft.SqlTools.ServiceLayer.DisasterRecovery;
using Microsoft.SqlTools.ServiceLayer.TaskServices; using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Moq; using Moq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
{ {
@@ -17,7 +17,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Create and run a backup task /// Create and run a backup task
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Test]
public async Task VerifyRunningBackupTask() public async Task VerifyRunningBackupTask()
{ {
using (SqlTaskManager manager = new SqlTaskManager()) using (SqlTaskManager manager = new SqlTaskManager())
@@ -28,7 +28,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.NotNull(sqlTask); Assert.NotNull(sqlTask);
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task => Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{ {
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask.TaskStatus); Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
}); });
await taskToVerify; await taskToVerify;
@@ -39,7 +39,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Generate script for backup task /// Generate script for backup task
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Test]
public async Task VerifyScriptBackupTask() public async Task VerifyScriptBackupTask()
{ {
using (SqlTaskManager manager = new SqlTaskManager()) using (SqlTaskManager manager = new SqlTaskManager())
@@ -52,7 +52,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.NotNull(sqlTask); Assert.NotNull(sqlTask);
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task => Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{ {
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask.TaskStatus); Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
}); });
await taskToVerify; await taskToVerify;
@@ -63,7 +63,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Create and run multiple backup tasks /// Create and run multiple backup tasks
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Test]
public async Task VerifyRunningMultipleBackupTasks() public async Task VerifyRunningMultipleBackupTasks()
{ {
using (SqlTaskManager manager = new SqlTaskManager()) using (SqlTaskManager manager = new SqlTaskManager())
@@ -78,12 +78,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task => Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{ {
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask.TaskStatus); Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
}); });
Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task => Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task =>
{ {
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus); Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus);
}); });
await Task.WhenAll(taskToVerify, taskToVerify2); await Task.WhenAll(taskToVerify, taskToVerify2);
@@ -94,7 +94,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Cancel a backup task /// Cancel a backup task
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Test]
public async Task VerifyCancelBackupTask() public async Task VerifyCancelBackupTask()
{ {
using (SqlTaskManager manager = new SqlTaskManager()) using (SqlTaskManager manager = new SqlTaskManager())
@@ -105,8 +105,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.NotNull(sqlTask); Assert.NotNull(sqlTask);
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task => Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{ {
Assert.Equal(SqlTaskStatus.Canceled, sqlTask.TaskStatus); Assert.AreEqual(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
Assert.Equal(sqlTask.IsCancelRequested, true); Assert.AreEqual(true, sqlTask.IsCancelRequested);
((BackupOperationStub)backupOperation).BackupSemaphore.Release(); ((BackupOperationStub)backupOperation).BackupSemaphore.Release();
manager.Reset(); manager.Reset();
}); });
@@ -120,7 +120,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Cancel multiple backup tasks /// Cancel multiple backup tasks
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Test]
public async Task VerifyCancelMultipleBackupTasks() public async Task VerifyCancelMultipleBackupTasks()
{ {
using (SqlTaskManager manager = new SqlTaskManager()) using (SqlTaskManager manager = new SqlTaskManager())
@@ -137,16 +137,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task => Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{ {
Assert.Equal(SqlTaskStatus.Canceled, sqlTask.TaskStatus); Assert.AreEqual(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
Assert.Equal(sqlTask.IsCancelRequested, true); Assert.AreEqual(true, sqlTask.IsCancelRequested);
((BackupOperationStub)backupOperation).BackupSemaphore.Release(); ((BackupOperationStub)backupOperation).BackupSemaphore.Release();
manager.Reset(); manager.Reset();
}); });
Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task => Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task =>
{ {
Assert.Equal(SqlTaskStatus.Canceled, sqlTask2.TaskStatus); Assert.AreEqual(SqlTaskStatus.Canceled, sqlTask2.TaskStatus);
Assert.Equal(sqlTask2.IsCancelRequested, true); Assert.AreEqual(true, sqlTask2.IsCancelRequested);
((BackupOperationStub)backupOperation2).BackupSemaphore.Release(); ((BackupOperationStub)backupOperation2).BackupSemaphore.Release();
manager.Reset(); manager.Reset();
}); });
@@ -161,7 +161,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Create two backup tasks and cancel one task /// Create two backup tasks and cancel one task
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Test]
public async Task VerifyCombinationRunAndCancelBackupTasks() public async Task VerifyCombinationRunAndCancelBackupTasks()
{ {
using (SqlTaskManager manager = new SqlTaskManager()) using (SqlTaskManager manager = new SqlTaskManager())
@@ -179,15 +179,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task => Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{ {
Assert.Equal(SqlTaskStatus.Canceled, sqlTask.TaskStatus); Assert.AreEqual(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
Assert.Equal(sqlTask.IsCancelRequested, true); Assert.AreEqual(true, sqlTask.IsCancelRequested);
((BackupOperationStub)backupOperation).BackupSemaphore.Release(); ((BackupOperationStub)backupOperation).BackupSemaphore.Release();
manager.Reset(); manager.Reset();
}); });
Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task => Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task =>
{ {
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus); Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus);
}); });
manager.CancelTask(sqlTask.TaskId); manager.CancelTask(sqlTask.TaskId);
@@ -8,19 +8,19 @@ using System.Collections.Generic;
using System.Text; using System.Text;
using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.Contracts; using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.Contracts;
using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.RestoreOperation; using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.RestoreOperation;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
{ {
public class DatabaseFileInfoTests public class DatabaseFileInfoTests
{ {
[Fact] [Test]
public void DatabaseFileInfoConstructorShouldThrowExceptionGivenNull() public void DatabaseFileInfoConstructorShouldThrowExceptionGivenNull()
{ {
Assert.Throws<ArgumentNullException>(() => new DatabaseFileInfo(null)); Assert.Throws<ArgumentNullException>(() => new DatabaseFileInfo(null));
} }
[Fact] [Test]
public void DatabaseFileInfoShouldReturnNullGivenEmptyProperties() public void DatabaseFileInfoShouldReturnNullGivenEmptyProperties()
{ {
LocalizedPropertyInfo[] properties = new LocalizedPropertyInfo[] { }; LocalizedPropertyInfo[] properties = new LocalizedPropertyInfo[] { };
@@ -29,7 +29,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.True(string.IsNullOrEmpty(fileInfo.GetPropertyValueAsString(BackupSetInfo.BackupComponentPropertyName))); Assert.True(string.IsNullOrEmpty(fileInfo.GetPropertyValueAsString(BackupSetInfo.BackupComponentPropertyName)));
} }
[Fact] [Test]
public void DatabaseFileInfoShouldReturnValuesGivenValidProperties() public void DatabaseFileInfoShouldReturnValuesGivenValidProperties()
{ {
LocalizedPropertyInfo[] properties = new LocalizedPropertyInfo[] { LocalizedPropertyInfo[] properties = new LocalizedPropertyInfo[] {
@@ -46,8 +46,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
}; };
var fileInfo = new DatabaseFileInfo(properties); var fileInfo = new DatabaseFileInfo(properties);
Assert.Equal(fileInfo.Id, "id"); Assert.AreEqual("id", fileInfo.Id);
Assert.Equal(fileInfo.GetPropertyValueAsString("name"), "1"); Assert.AreEqual("1", fileInfo.GetPropertyValueAsString("name"));
} }
} }
} }
@@ -4,7 +4,7 @@
// //
using Microsoft.SqlTools.ServiceLayer.DisasterRecovery; using Microsoft.SqlTools.ServiceLayer.DisasterRecovery;
using Xunit; using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
{ {
@@ -13,7 +13,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// </summary> /// </summary>
public class DisasterRecoveryFileValidatorUnitTests public class DisasterRecoveryFileValidatorUnitTests
{ {
[Fact] [Test]
public void ValidatorShouldReturnTrueForNullArgument() public void ValidatorShouldReturnTrueForNullArgument()
{ {
string message; string message;
@@ -21,14 +21,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.True(result); Assert.True(result);
} }
[Fact] [Test]
public void GetMachineNameForLocalServer() public void GetMachineNameForLocalServer()
{ {
string machineName = DisasterRecoveryFileValidator.GetMachineName(DisasterRecoveryFileValidator.LocalSqlServer); string machineName = DisasterRecoveryFileValidator.GetMachineName(DisasterRecoveryFileValidator.LocalSqlServer);
Assert.True(System.Environment.MachineName == machineName); Assert.True(System.Environment.MachineName == machineName);
} }
[Fact] [Test]
public void GetMachineNameForNamedServer() public void GetMachineNameForNamedServer()
{ {
string testMachineName = "testmachine"; string testMachineName = "testmachine";

Some files were not shown because too many files have changed in this diff Show More