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

View File

@@ -23,6 +23,8 @@
<PackageReference Update="Moq" Version="4.8.2" />
<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.runner.visualstudio" Version="2.4.1" />
<PackageReference Update="Microsoft.NET.Test.Sdk" Version="16.6.1" />

View File

@@ -1,5 +1,5 @@
pool:
name: Hosted VS2017
vmImage: 'windows-latest'
demands:
- Cmd
- npm

View File

@@ -683,23 +683,23 @@ namespace Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode
DbConnectionWrapper connectionWrapper = new DbConnectionWrapper(connection);
connectionWrapper.InfoMessage += messageHandler;
IDbCommand command = connection.CreateCommand();
command.CommandText = script;
command.CommandTimeout = execTimeout;
IDbCommand localCommand = connection.CreateCommand();
localCommand.CommandText = script;
localCommand.CommandTimeout = execTimeout;
DbCommandWrapper commandWrapper = null;
if (isScriptExecutionTracked && DbCommandWrapper.IsSupportedCommand(command))
if (isScriptExecutionTracked && DbCommandWrapper.IsSupportedCommand(localCommand))
{
statementCompletedHandler = new StatementCompletedEventHandler(OnStatementExecutionFinished);
commandWrapper = new DbCommandWrapper(command);
commandWrapper = new DbCommandWrapper(localCommand);
commandWrapper.StatementCompleted += statementCompletedHandler;
}
lock (this)
{
state = BatchState.Executing;
this.command = command;
command = null;
command = localCommand;
localCommand = null;
}
try

View File

@@ -20,7 +20,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SqlServer.DACFx" />
<PackageReference Include="Microsoft.SqlServer.DACFx" />
<PackageReference Include="Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider" />
<PackageReference Include="System.Text.Encoding.CodePages" />
</ItemGroup>
@@ -45,4 +45,23 @@
<ItemGroup>
<EmbeddedResource Include=".\Agent\NotebookResources\NotebookJobScript.ps1" />
</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>

View File

@@ -8,7 +8,8 @@ using Microsoft.SqlTools.Hosting.Contracts;
using Microsoft.SqlTools.Hosting.Contracts.Internal;
using Microsoft.SqlTools.Hosting.Protocol;
using Newtonsoft.Json.Linq;
using NUnit.Framework.Interfaces;
namespace Microsoft.SqlTools.Hosting.UnitTests
{
public static class CommonObjects
@@ -51,6 +52,15 @@ namespace Microsoft.SqlTools.Hosting.UnitTests
&& 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)
{
bool bothNull = ReferenceEquals(obj1, null) && ReferenceEquals(obj2, null);

View File

@@ -1,38 +1,39 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.DataProtocol.Contracts.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
{
[TestFixture]
public class FlagsIntConverterTests
{
[Fact]
[Test]
public void NullableValueCanBeDeserialized()
{
var jsonObject = JObject.Parse("{\"optionalValue\": [1, 2]}");
var contract = jsonObject.ToObject<DataContract>();
Assert.NotNull(contract);
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()
{
var jsonObject = JObject.Parse("{\"Value\": [1, 3]}");
var contract = jsonObject.ToObject<DataContract>();
Assert.NotNull(contract);
Assert.Equal(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value);
Assert.AreEqual(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value);
}
[Fact]
[Test]
public void ExplicitNullCanBeDeserialized()
{
var jsonObject = JObject.Parse("{\"optionalValue\": null}");
@@ -42,7 +43,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
}
[Flags]
[JsonConverter(typeof(FlagsIntConverter))]
[JsonConverter(typeof(FlagsIntConverter))]
private enum TestFlags
{
[FlagsIntConverter.SerializeValue(1)]
@@ -52,7 +53,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
SecondItem = 1 << 1,
[FlagsIntConverter.SerializeValue(3)]
ThirdItem = 1 << 2,
ThirdItem = 1 << 2,
}
private class DataContract

View File

@@ -1,38 +1,39 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using Microsoft.SqlTools.DataProtocol.Contracts.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
{
[TestFixture]
public class FlagsStringConverterTests
{
[Fact]
[Test]
public void NullableValueCanBeDeserialized()
{
var jsonObject = JObject.Parse("{\"optionalValue\": [\"First\", \"Second\"]}");
var contract = jsonObject.ToObject<DataContract>();
Assert.NotNull(contract);
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()
{
var jsonObject = JObject.Parse("{\"Value\": [\"First\", \"Third\"]}");
var contract = jsonObject.ToObject<DataContract>();
Assert.NotNull(contract);
Assert.Equal(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value);
Assert.AreEqual(TestFlags.FirstItem | TestFlags.ThirdItem, contract.Value);
}
[Fact]
[Test]
public void ExplicitNullCanBeDeserialized()
{
var jsonObject = JObject.Parse("{\"optionalValue\": null}");
@@ -42,7 +43,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
}
[Flags]
[JsonConverter(typeof(FlagsStringConverter))]
[JsonConverter(typeof(FlagsStringConverter))]
private enum TestFlags
{
[FlagsStringConverter.SerializeValue("First")]
@@ -52,7 +53,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.Contracts.Utilities
SecondItem = 1 << 1,
[FlagsStringConverter.SerializeValue("Third")]
ThirdItem = 1 << 2,
ThirdItem = 1 << 2,
}
private class DataContract

View File

@@ -7,19 +7,23 @@ using System;
using System.Linq;
using Microsoft.SqlTools.Hosting.Extensibility;
using Microsoft.SqlTools.Hosting.Utility;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
{
[TestFixture]
public class ServiceProviderTests
{
private readonly RegisteredServiceProvider provider;
public ServiceProviderTests()
private RegisteredServiceProvider provider;
[SetUp]
public void SetupServiceProviderTests()
{
provider = new RegisteredServiceProvider();
}
}
[Fact]
[Test]
public void GetServiceShouldReturnNullIfNoServicesRegistered()
{
// Given no service registered
@@ -30,7 +34,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
}
[Fact]
[Test]
public void GetSingleServiceThrowsMultipleServicesRegistered()
{
// Given 2 services registered
@@ -40,44 +44,43 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
Assert.Throws<InvalidOperationException>(() => provider.GetService<MyProviderService>());
}
[Fact]
[Test]
public void GetServicesShouldReturnEmptyIfNoServicesRegistered()
{
// Given no service regisstered
// When I call GetService
var services = provider.GetServices<MyProviderService>();
// Then I expect empty enumerable to be returned
Assert.NotNull(services);
Assert.Empty(services);
Assert.That(services, Is.Empty, "provider.GetServices with no service registered");
}
[Fact]
[Test]
public void GetServiceShouldReturnRegisteredService()
{
MyProviderService service = new MyProviderService();
provider.RegisterSingleService(service);
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()
{
MyProviderService service = new MyProviderService();
provider.RegisterSingleService(service);
provider.RegisterSingleService(service);
var returnedServices = provider.GetServices<MyProviderService>();
Assert.Equal(service, returnedServices.Single());
Assert.AreEqual(service, returnedServices.Single());
}
[Fact]
[Test]
public void RegisterServiceProviderShouldThrowIfServiceIsIncompatible()
{
MyProviderService service = new MyProviderService();
Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(typeof(OtherService), service));
}
[Fact]
[Test]
public void RegisterServiceProviderShouldThrowIfServiceAlreadyRegistered()
{
MyProviderService service = new MyProviderService();
@@ -86,7 +89,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(service));
}
[Fact]
[Test]
public void RegisterShouldThrowIfServiceAlreadyRegistered()
{
MyProviderService service = new MyProviderService();
@@ -95,7 +98,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests
Assert.Throws<InvalidOperationException>(() => provider.Register(() => service.AsSingleItemEnumerable()));
}
[Fact]
[Test]
public void RegisterShouldThrowIfServicesAlreadyRegistered()
{
provider.Register(() => new [] { new MyProviderService(), new MyProviderService() });

View File

@@ -7,8 +7,9 @@
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Moq"/>
<PackageReference Include="xunit"/>
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="nunit"/>
<PackageReference Include="nunit3testadapter"/>
<PackageReference Include="nunit.console"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Microsoft.SqlTools.DataProtocol.Contracts\Microsoft.SqlTools.DataProtocol.Contracts.csproj" />

View File

@@ -4,14 +4,16 @@
//
using System.Collections.Concurrent;
using System.Linq;
using Microsoft.SqlTools.Hosting.Protocol;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{
[TestFixture]
public class EventContextTests
{
[Fact]
[Test]
public void SendEvent()
{
// Setup: Create collection
@@ -20,11 +22,11 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I construct an event context with a message writer
// And send an event with it
var eventContext = new EventContext(bc);
eventContext.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message should be added to the queue
Assert.Single(bc.ToArray());
Assert.Equal(MessageType.Event, bc.ToArray()[0].MessageType);
eventContext.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message should be added to the queue
var messages = bc.ToArray().Select(m => m.MessageType);
Assert.That(messages, Is.EqualTo(new[] { MessageType.Event }), "Single message of type event in the queue after SendEvent");
}
}
}

View File

@@ -12,13 +12,14 @@ using Microsoft.SqlTools.Hosting.Channels;
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{
[TestFixture]
public class JsonRpcHostTests
{
[Fact]
[Test]
public void ConstructWithNullProtocolChannel()
{
// 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
[Fact]
[Test]
public void SetAsyncRequestHandlerNullRequestType()
{
// 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)));
}
[Fact]
[Test]
public void SetAsyncRequestHandlerNullRequestHandler()
{
// 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));
}
[Fact]
[Test]
public void SetSyncRequestHandlerNullRequestHandler()
{
// 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));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SetAsyncRequestHandler(bool nullContents)
[Test]
public async Task SetAsyncRequestHandler([Values]bool nullContents)
{
// Setup: Create a mock request handler
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
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object);
// Then: It should be the only request handler set
Assert.Single(jh.requestHandlers);
Assert.Contains(CommonObjects.RequestType.MethodName, jh.requestHandlers.Keys);
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object);
// Then: It should be the only request handler set
Assert.That(jh.requestHandlers.Keys, Is.EqualTo(new[] { CommonObjects.RequestType.MethodName }), "requestHandlers.Keys after SetAsyncRequestHandler");
// If: I call the stored request handler
await jh.requestHandlers[CommonObjects.RequestType.MethodName](message);
@@ -89,10 +87,8 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Exactly(2));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SetSyncRequestHandler(bool nullContents)
[Test]
public async Task SetSyncRequestHandler([Values]bool nullContents)
{
// Setup: Create a mock request handler
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
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
jh.SetRequestHandler(CommonObjects.RequestType, requestHandler.Object);
// Then: It should be the only request handler set
Assert.Single(jh.requestHandlers);
Assert.Contains(CommonObjects.RequestType.MethodName, jh.requestHandlers.Keys);
// If: I call the stored request handler
jh.SetRequestHandler(CommonObjects.RequestType, requestHandler.Object);
// Then: It should be the only request handler set
Assert.That(jh.requestHandlers.Keys, Is.EqualTo(new[] { CommonObjects.RequestType.MethodName }), "requestHandlers.Keys after SetRequestHandler");
// If: I call the stored request handler
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));
}
[Fact]
[Test]
public async Task SetAsyncRequestHandlerOverrideTrue()
{
// Setup: Create two mock request handlers
@@ -137,8 +132,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler2.Object, true);
// Then: There should only be one request handler
Assert.Single(jh.requestHandlers);
Assert.Contains(CommonObjects.RequestType.MethodName, jh.requestHandlers.Keys);
Assert.That(jh.requestHandlers.Keys, Is.EqualTo(new[] { CommonObjects.RequestType.MethodName }), "requestHandlers.Keys after SetAsyncRequestHandler with override");
// If: I call the stored request handler
await jh.requestHandlers[CommonObjects.RequestType.MethodName](CommonObjects.RequestMessage);
@@ -154,7 +148,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Never);
}
[Fact]
[Test]
public void SetAsyncRequestHandlerOverrideFalse()
{
// Setup: Create a mock request handler
@@ -166,14 +160,14 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: I should get an exception
var jh = new JsonRpcHost(GetChannelBase(null, null).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
#region SetEventHandler Tests
[Fact]
[Test]
public void SetAsyncEventHandlerNullEventType()
{
// 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)));
}
[Fact]
[Test]
public void SetAsyncEventHandlerNull()
{
// 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));
}
[Fact]
[Test]
public void SetSyncEventHandlerNull()
{
// 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));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task SetAsyncEventHandler(bool nullContents)
[Test]
public async Task SetAsyncEventHandler([Values]bool nullContents)
{
// Setup: Create a mock request handler
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
var jh = new JsonRpcHost(GetChannelBase(null, null).Object);
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object);
// Then: It should be the only event handler set
Assert.Single(jh.eventHandlers);
Assert.Contains(CommonObjects.EventType.MethodName, jh.eventHandlers.Keys);
// If: I call the stored event handler
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object);
// Then: It should be the only event handler set
Assert.That(jh.eventHandlers.Keys, Is.EqualTo(new[] { CommonObjects.EventType.MethodName }), "eventHandlers.Keys after SetAsyncRequestHandler");
// If: I call the stored event handler
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));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task SetSyncEventHandler(bool nullContents)
[Test]
public async Task SetSyncEventHandler([Values]bool nullContents)
{
// Setup: Create a mock request handler
var eventHandler = new Mock<Action<CommonObjects.TestMessageContents, EventContext>>();
@@ -248,8 +237,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
jh.SetEventHandler(CommonObjects.EventType, eventHandler.Object);
// Then: It should be the only event handler set
Assert.Single(jh.eventHandlers);
Assert.Contains(CommonObjects.EventType.MethodName, jh.eventHandlers.Keys);
Assert.That(jh.eventHandlers.Keys, Is.EqualTo(new object[] { CommonObjects.EventType.MethodName }), "eventHandlers.Keys after SetEventHandler");
// If: I call the stored event handler
await jh.eventHandlers[CommonObjects.EventType.MethodName](message);
@@ -265,7 +253,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Exactly(2));
}
[Fact]
[Test]
public async Task SetAsyncEventHandlerOverrideTrue()
{
// Setup: Create two mock event handlers
@@ -281,8 +269,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler2.Object, true);
// Then: There should only be one event handler
Assert.Single(jh.eventHandlers);
Assert.Contains(CommonObjects.EventType.MethodName, jh.eventHandlers.Keys);
Assert.That(jh.eventHandlers.Keys, Is.EqualTo(new[] { CommonObjects.EventType.MethodName }), "requestHandlers.Keys after SetAsyncEventHandler with override");
// If: I call the stored event handler
await jh.eventHandlers[CommonObjects.EventType.MethodName](CommonObjects.EventMessage);
@@ -298,7 +285,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Never);
}
[Fact]
[Test]
public void SetAsyncEventHandlerOverrideFalse()
{
// Setup: Create a mock event handler
@@ -310,14 +297,14 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: I should get an exception
var jh = new JsonRpcHost(GetChannelBase(null, null).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
#region SendEvent Tests
[Fact]
[Test]
public void SendEventNotConnected()
{
// 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));
}
[Fact]
[Test]
public void SendEvent()
{
// Setup: Create a Json RPC Host with a connected channel
var jh = new JsonRpcHost(GetChannelBase(null, null, true).Object);
// If: I send an event
jh.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message should be added to the output queue
Assert.Single(jh.outputQueue.ToArray());
var m = jh.outputQueue.ToArray()[0];
Assert.Equal(CommonObjects.TestMessageContents.SerializedContents, m.Contents);
Assert.Equal(CommonObjects.EventType.MethodName, m.Method);
jh.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message should be added to the output queue
Assert.That(jh.outputQueue.ToArray().Select(m => (m.Contents, m.Method)),
Is.EqualTo(new[] { (CommonObjects.TestMessageContents.SerializedContents, CommonObjects.EventType.MethodName) }), "outputQueue after SendEvent");
}
#endregion
#region SendRequest Tests
[Fact]
[Test]
public async Task SendRequestNotConnected()
{
// If: I send an event when the protocol channel isn't connected
// Then: I should get an exception
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()
{
// 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);
// 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
jh.pendingRequests.First().Value.SetResult(CommonObjects.ResponseMessage);
var responseContents = await requestTask;
// Then: The returned results should be the contents of the message
Assert.Equal(CommonObjects.TestMessageContents.DefaultInstance, responseContents);
Assert.AreEqual(CommonObjects.TestMessageContents.DefaultInstance, responseContents);
}
#endregion
#region DispatchMessage Tests
[Fact]
[Test]
public async Task DispatchMessageRequestWithoutHandler()
{
// 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
// 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()
{
// 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
// Then: I should get an exception
await Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.RequestMessage));
Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.RequestMessage));
}
[Theory]
[MemberData(nameof(DispatchMessageWithHandlerData))]
[TestCaseSource(nameof(DispatchMessageWithHandlerData))]
public async Task DispatchMessageRequestWithHandler(Task result)
{
// Setup: Create a JSON RPC host with a request handler setup
@@ -429,7 +413,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
), Times.Once);
}
[Fact]
[Test]
public async Task DispatchmessageResponseWithoutHandler()
{
// 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
// 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()
{
// 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
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()
{
// 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
// 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()
{
// 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
// Then: I should get an exception
await Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.EventMessage));
Assert.ThrowsAsync<Exception>(() => jh.DispatchMessage(CommonObjects.EventMessage));
}
[Theory]
[MemberData(nameof(DispatchMessageWithHandlerData))]
[TestCaseSource(nameof(DispatchMessageWithHandlerData))]
public async Task DispatchMessageEventWithHandler(Task result)
{
// 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
[Fact]
[Test]
public async Task ConsumeInput()
{
// Setup:
@@ -554,7 +537,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
mr.Verify(o => o.ReadMessage(), Times.AtLeastOnce);
}
[Fact]
[Test]
public async Task ConsumeInputEndOfStream()
{
// 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);
}
[Fact]
[Test]
public async Task ConsumeInputException()
{
// Setup:
@@ -591,32 +574,29 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
}
[Fact]
[Test]
public async Task ConsumeInputRequestMethodNotFound()
{
// Setup: Create a message reader that will return a request with method that doesn't exist
var mr = new Mock<MessageReader>(Stream.Null, null);
mr.SetupSequence(o => o.ReadMessage())
.ReturnsAsync(CommonObjects.RequestMessage)
.Returns(Task.FromException<Message>(new EndOfStreamException()));
// If: I start the input consumption loop
.Returns(Task.FromException<Message>(new EndOfStreamException()));
// If: I start the input consumption loop
var jh = new JsonRpcHost(GetChannelBase(mr.Object, null).Object);
await jh.ConsumeInput().WithTimeout(TimeSpan.FromSeconds(1));
// Then:
// ... Read message should have been called twice
mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
// ... There should be an outgoing message with the error
await jh.ConsumeInput().WithTimeout(TimeSpan.FromSeconds(1));
// Then:
// ... Read message should have been called twice
mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
// ...
var outgoing = jh.outputQueue.ToArray();
Assert.Single(outgoing);
Assert.Equal(MessageType.ResponseError, outgoing[0].MessageType);
Assert.Equal(CommonObjects.MessageId, outgoing[0].Id);
Assert.Equal(-32601, outgoing[0].Contents.Value<int>("code"));
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");
}
[Fact]
[Test]
public async Task ConsumeInputRequestException()
{
// Setup:
@@ -641,16 +621,15 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// ... Read message should have been called twice
mr.Verify(o => o.ReadMessage(), Times.Exactly(2));
// ... There should not be any outgoing messages
var outgoing = jh.outputQueue.ToArray();
Assert.Empty(outgoing);
Assert.That(outgoing, Is.Empty, "outputQueue after ConsumeInput should not have any outgoing messages");
}
#endregion
#region ConsumeOutput Loop Tests
[Fact]
[Test]
public async Task ConsumeOutput()
{
// Setup:
@@ -671,7 +650,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
mw.Verify(o => o.WriteMessage(CommonObjects.ResponseMessage), Times.Once);
}
[Fact]
[Test]
public async Task ConsumeOutputCancelled()
{
// 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);
}
[Fact]
[Test]
public async Task ConsumeOutputException()
{
// Setup: Create a mock message writer
@@ -713,7 +692,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
#region Start/Stop Tests
[Fact]
[Test]
public async Task StartStop()
{
// Setup: Create mocked message reader and writer
@@ -737,7 +716,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
cb.Verify(o => o.Stop(), Times.Once);
}
[Fact]
[Test]
public async Task StartMultiple()
{
// 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));
}
[Fact]
[Test]
public void StopMultiple()
{
// Setup: Create json rpc host and start it
@@ -774,7 +753,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.Throws<InvalidOperationException>(() => jh.Stop());
}
[Fact]
[Test]
public void StopBeforeStarting()
{
// 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());
}
[Fact]
[Test]
public async Task WaitForExit()
{
// Setup: Create json rpc host and start it
@@ -801,7 +780,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
await waitForExit.WithTimeout(TimeSpan.FromSeconds(1));
}
[Fact]
[Test]
public void WaitForExitNotStarted()
{
// If: I wait for exit on the JSON RPC host without starting it

View File

@@ -10,15 +10,16 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Newtonsoft.Json;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{
[TestFixture]
public class MessageReaderTests
{
#region Construction Tests
[Fact]
[Test]
public void CreateReaderNullStream()
{
// 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));
}
[Fact]
[Test]
public void CreateReaderStandardEncoding()
{
// If: I create a message reader without including a message encoding
var mr = new MessageReader(Stream.Null);
// 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()
{
// If: I create a message reader with a specific message encoding
var mr = new MessageReader(Stream.Null, Encoding.ASCII);
// Then: The reader's encoding should be ASCII
Assert.Equal(Encoding.ASCII, mr.MessageEncoding);
Assert.AreEqual(Encoding.ASCII, mr.MessageEncoding);
}
#endregion
#region ReadMessage Tests
[Theory]
[InlineData(512)] // Buffer size can fit everything in one read
[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)
[Test]
public async Task ReadMessageSingleRead([Values(512,10,25)]int bufferSize)
{
// 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}");
@@ -70,17 +68,19 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
Assert.NotNull(output);
// ... 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
Assert.Equal(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
Assert.AreEqual(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
}
}
[Theory]
[InlineData("Content-Type: application/json\r\n\r\n")] // Missing content-length header
[InlineData("Content-Length: abc\r\n\r\n")] // Content-length is not a number
public async Task ReadMessageInvalidHeaders(string testString)
[Test]
public async Task ReadMessageInvalidHeaders(
[Values(
"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
byte[] testBytes = Encoding.UTF8.GetBytes(testString);
@@ -90,14 +90,14 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// If: I read a message with invalid headers
// 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)
Assert.Equal(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
Assert.AreEqual(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
}
}
[Fact]
[Test]
public async Task ReadMessageInvalidJson()
{
// 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
// Then:
// ... 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)
Assert.Equal(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
Assert.AreEqual(MessageReader.DefaultBufferSize, mr.MessageBuffer.Length);
}
}
[Fact]
[Test]
public async Task ReadMultipleMessages()
{
// 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()
{
// 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()
{
// 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
// Then: I should get an exception
await Assert.ThrowsAnyAsync<MessageParseException>(() => mr.ReadMessage());
Assert.ThrowsAsync<MessageParseException>(() => mr.ReadMessage());
// If: I read another, valid, message
var msg = await mr.ReadMessage();
@@ -192,7 +192,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
}
}
[Fact]
[Test]
public async Task ReadRecoverFromInvalidContentMessage()
{
// 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
// Then: I should get an exception
await Assert.ThrowsAnyAsync<JsonException>(() => mr.ReadMessage());
Assert.ThrowsAsync<JsonReaderException>(() => mr.ReadMessage());
// If: I read another, valid, message
var msg = await mr.ReadMessage();

View File

@@ -8,15 +8,16 @@ using System.Collections.Generic;
using System.Linq;
using Microsoft.SqlTools.Hosting.Protocol;
using Newtonsoft.Json.Linq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{
[TestFixture]
public class MessageTests
{
#region Construction/Serialization Tests
[Fact]
[Test]
public void CreateRequest()
{
// If: I create a request
@@ -36,7 +37,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
AssertPropertiesSet(expectedResults, message);
}
[Fact]
[Test]
public void CreateError()
{
// If: I create an error
@@ -54,7 +55,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
AssertPropertiesSet(expectedResults, message);
}
[Fact]
[Test]
public void CreateResponse()
{
// If: I create a response
@@ -72,7 +73,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
AssertPropertiesSet(expectedResults, message);
}
[Fact]
[Test]
public void CreateEvent()
{
// If: I create an event
@@ -101,16 +102,16 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// JSON RPC Version
List<string> expectedProperties = new List<string> {"jsonrpc"};
Assert.Equal("2.0", jObject["jsonrpc"]);
Assert.AreEqual("2.0", jObject["jsonrpc"].Value<string>());
// Message Type
Assert.Equal(results.MessageType, message.MessageType);
Assert.AreEqual(results.MessageType, message.MessageType);
// ID
if (results.IdSet)
{
Assert.Equal(CommonObjects.MessageId, message.Id);
Assert.Equal(CommonObjects.MessageId, jObject["id"]);
Assert.AreEqual(CommonObjects.MessageId, message.Id);
Assert.AreEqual(CommonObjects.MessageId, jObject["id"].Value<string>());
expectedProperties.Add("id");
}
else
@@ -121,8 +122,8 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Method
if (results.MethodSetAs != null)
{
Assert.Equal(results.MethodSetAs, message.Method);
Assert.Equal(results.MethodSetAs, jObject["method"]);
Assert.AreEqual(results.MethodSetAs, message.Method);
Assert.AreEqual(results.MethodSetAs, jObject["method"].Value<string>());
expectedProperties.Add("method");
}
else
@@ -133,22 +134,22 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Contents
if (results.ContentsSetAs != null)
{
Assert.Equal(CommonObjects.TestMessageContents.SerializedContents, message.Contents);
Assert.Equal(CommonObjects.TestMessageContents.SerializedContents, jObject[results.ContentsSetAs]);
Assert.AreEqual(CommonObjects.TestMessageContents.SerializedContents, message.Contents);
Assert.AreEqual(CommonObjects.TestMessageContents.SerializedContents, jObject[results.ContentsSetAs]);
expectedProperties.Add(results.ContentsSetAs);
}
// Error
if (results.ErrorSet)
{
Assert.Equal(CommonObjects.TestErrorContents.SerializedContents, message.Contents);
Assert.Equal(CommonObjects.TestErrorContents.SerializedContents, jObject["error"]);
Assert.AreEqual(CommonObjects.TestErrorContents.SerializedContents, message.Contents);
Assert.AreEqual(CommonObjects.TestErrorContents.SerializedContents, jObject["error"]);
expectedProperties.Add("error");
}
// Look for any extra properties set in the JObject
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
@@ -164,7 +165,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
#region Deserialization Tests
[Fact]
[Test]
public void DeserializeMissingJsonRpc()
{
// 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}"));
}
[Fact]
[Test]
public void DeserializeEvent()
{
// 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
Assert.NotNull(m);
Assert.Equal(MessageType.Event, m.MessageType);
Assert.Equal("event", m.Method);
Assert.AreEqual(MessageType.Event, m.MessageType);
Assert.AreEqual("event", m.Method);
Assert.NotNull(m.Contents);
Assert.Null(m.Id);
}
[Fact]
[Test]
public void DeserializeEventMissingMethod()
{
// 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\": {}}"));
}
[Fact]
[Test]
public void DeserializeResponse()
{
// 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
Assert.NotNull(m);
Assert.Equal(MessageType.Response, m.MessageType);
Assert.Equal("123", m.Id);
Assert.AreEqual(MessageType.Response, m.MessageType);
Assert.AreEqual("123", m.Id);
Assert.NotNull(m.Contents);
Assert.Null(m.Method);
}
[Fact]
[Test]
public void DeserializeErrorResponse()
{
// 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
Assert.NotNull(m);
Assert.Equal(MessageType.ResponseError, m.MessageType);
Assert.Equal("123", m.Id);
Assert.AreEqual(MessageType.ResponseError, m.MessageType);
Assert.AreEqual("123", m.Id);
Assert.NotNull(m.Contents);
Assert.Null(m.Method);
}
[Fact]
[Test]
public void DeserializeRequest()
{
// If: I deserialize a request
@@ -230,13 +231,13 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Then: I should get a request message back
Assert.NotNull(m);
Assert.Equal(MessageType.Request, m.MessageType);
Assert.Equal("123", m.Id);
Assert.Equal("request", m.Method);
Assert.AreEqual(MessageType.Request, m.MessageType);
Assert.AreEqual("123", m.Id);
Assert.AreEqual("request", m.Method);
Assert.NotNull(m.Contents);
}
[Fact]
[Test]
public void DeserializeRequestMissingMethod()
{
// 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\"}"));
}
[Fact]
[Test]
public void GetTypedContentsNull()
{
// 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);
}
[Fact]
[Test]
public void GetTypedContentsSimpleValue()
{
// 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>();
// Then: I should get an int back
Assert.Equal(123, c);
Assert.AreEqual(123, c);
}
[Fact]
[Test]
public void GetTypedContentsClassValue()
{
// 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>();
// 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()
{
// If: I have a message that has contents and I get incorrectly typed contents from it
// Then: I should get an exception back
var m = Message.CreateResponse(CommonObjects.MessageId, CommonObjects.TestMessageContents.DefaultInstance);
Assert.ThrowsAny<Exception>(() => m.GetTypedContents<int>());
Assert.Throws<ArgumentException>(() => m.GetTypedContents<int>());
}
#endregion

View File

@@ -10,15 +10,16 @@ using System.Text;
using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Protocol;
using Newtonsoft.Json;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{
[TestFixture]
public class MessageWriterTests
{
#region Construction Tests
[Fact]
[Test]
public void ConstructMissingOutputStream()
{
// If: I attempt to create a message writer without an output stream
@@ -30,17 +31,16 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
#region WriteMessageTests
[Fact]
[Test]
public async Task WriteMessageNullMessage()
{
// If: I write a null message
// Then: I should get an exception
var mw = new MessageWriter(Stream.Null);
await Assert.ThrowsAsync<ArgumentNullException>(() => mw.WriteMessage(null));
var mw = new MessageWriter(Stream.Null);
Assert.ThrowsAsync<ArgumentNullException>(() => mw.WriteMessage(null));
}
[Theory]
[MemberData(nameof(WriteMessageData))]
[TestCaseSource(nameof(WriteMessageData))]
public async Task WriteMessage(object contents, Dictionary<string, object> expectedDict)
{
// 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
var mw = new MessageWriter(outputStream);
await mw.WriteMessage(Message.CreateResponse(CommonObjects.MessageId, contents));
// Then:
// ... The returned bytes on the stream should compose a valid message
Assert.NotEqual(0, outputStream.Position);
await mw.WriteMessage(Message.CreateResponse(CommonObjects.MessageId, contents));
// Then:
// ... The returned bytes on the stream should compose a valid message
Assert.That(outputStream.Position, Is.Not.EqualTo(0), "outputStream.Position after WriteMessage");
var messageDict = ValidateMessageHeaders(output, (int) outputStream.Position);
// ... ID, Params, Method should be present
@@ -97,12 +97,12 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
expectedDict.Add("jsonrpc", "2.0");
// 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
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
string[] outputParts = outputString.Split("\r\n\r\n");
Assert.Equal(2, outputParts.Length);
Assert.AreEqual(2, outputParts.Length);
// The first section is the headers
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
int? contentLength = null;
@@ -126,7 +126,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{
// Headers should look like "Header-Key: HeaderValue"
string[] headerParts = header.Split(':');
Assert.Equal(2, headerParts.Length);
Assert.AreEqual(2, headerParts.Length);
string headerKey = headerParts[0];
string headerValue = headerParts[1].Trim();
@@ -147,7 +147,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
// Make sure the headers are correct
Assert.True(contentTypeCorrect);
Assert.Equal(outputParts[1].Length, contentLength);
Assert.AreEqual(outputParts[1].Length, contentLength);
// Deserialize the body into a dictionary
return JsonConvert.DeserializeObject<Dictionary<string, object>>(outputParts[1]);

View File

@@ -8,15 +8,16 @@ using System.Collections.Concurrent;
using System.Linq;
using Microsoft.SqlTools.Hosting.Contracts.Internal;
using Microsoft.SqlTools.Hosting.Protocol;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
{
[TestFixture]
public class RequestContextTests
{
#region Send Tests
[Fact]
[Test]
public void SendResult()
{
// 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);
rc.SendResult(CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message writer should have sent a response
Assert.Single(bc);
Assert.Equal(MessageType.Response, bc.First().MessageType);
Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.Response }), "The message writer should have sent a response");
}
[Fact]
[Test]
public void SendEvent()
{
// 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
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
rc.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
// Then: The message writer should have sent an event
Assert.Single(bc);
Assert.Equal(MessageType.Event, bc.First().MessageType);
rc.SendEvent(CommonObjects.EventType, CommonObjects.TestMessageContents.DefaultInstance);
Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.Event }), "The message writer should have sent an event");
}
[Fact]
[Test]
public void SendError()
{
// 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
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
rc.SendError(errorMessage, errorCode);
// Then:
// ... The message writer should have sent an error
Assert.Single(bc);
Assert.Equal(MessageType.ResponseError, bc.First().MessageType);
// ... The error object it built should have the reuired fields set
rc.SendError(errorMessage, errorCode);
Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.ResponseError }), "The message writer should have sent an error");
// ... The error object it built should have the reuired fields set
var contents = bc.ToArray()[0].GetTypedContents<Error>();
Assert.Equal(errorCode, contents.Code);
Assert.Equal(errorMessage, contents.Message);
Assert.AreEqual(errorCode, contents.Code);
Assert.AreEqual(errorMessage, contents.Message);
}
[Fact]
[Test]
public void SendException()
{
// Setup: Create a blocking collection to collect the output
@@ -79,18 +73,14 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ProtocolTests
const string errorMessage = "error";
var e = new Exception(errorMessage);
var rc = new RequestContext<CommonObjects.TestMessageContents>(CommonObjects.RequestMessage, bc);
rc.SendError(e);
// Then:
// ... The message writer should have sent an error
Assert.Single(bc);
var firstMessage = bc.First();
Assert.Equal(MessageType.ResponseError, firstMessage.MessageType);
// ... 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);
rc.SendError(e);
Assert.That(bc.Select(m => m.MessageType), Is.EqualTo(new[] { MessageType.ResponseError }), "The message writer should have sent an error");
// ... The error object it built should have the reuired fields set
var contents = bc.First().GetTypedContents<Error>();
Assert.AreEqual(e.HResult, contents.Code);
Assert.AreEqual(errorMessage, contents.Message);
}

View File

@@ -8,13 +8,14 @@ using Microsoft.SqlTools.Hosting.Channels;
using Microsoft.SqlTools.Hosting.Extensibility;
using Microsoft.SqlTools.Hosting.Protocol;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
{
[TestFixture]
public class ExtensibleServiceHostTest
{
[Fact]
[Test]
public void CreateExtensibleHostNullProvider()
{
// 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));
}
[Fact]
[Test]
public void CreateExtensibleHost()
{
// Setup:
@@ -48,10 +49,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
// ... The service should have been initialized
hs.Verify(o => o.InitializeService(esh), Times.Once());
// ... 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()
{
// 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));
}
[Fact]
[Test]
public void CreateDefaultExtensibleHost()
{
// If: I create a default server extensible host
@@ -70,10 +71,9 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
// ... The service provider should be setup
Assert.NotNull(esh.ServiceProvider);
// ... The underlying rpc host should be using the stdio server channel
var jh = esh.jsonRpcHost as JsonRpcHost;
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);
}
}

View File

@@ -14,28 +14,28 @@ using Microsoft.SqlTools.Hosting.Contracts.Internal;
using Microsoft.SqlTools.Hosting.Protocol;
using Moq;
using Newtonsoft.Json.Linq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
{
[TestFixture]
public class ServiceHostTests
{
#region Construction Tests
[Fact]
[Test]
public void ServiceHostConstructDefaultServer()
{
// If: I construct a default server service host
var sh = ServiceHost.CreateDefaultServer();
// Then: The underlying json rpc host should be using the stdio server channel
var jh = sh.jsonRpcHost as JsonRpcHost;
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);
}
[Fact]
[Test]
public void ServiceHostNullParameter()
{
// If: I create a service host with missing parameters
@@ -47,7 +47,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
#region IServiceHost Tests
[Fact]
[Test]
public void RegisterInitializeTask()
{
// Setup: Create mock initialize handler
@@ -59,11 +59,11 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
sh.RegisterInitializeTask(mockHandler);
// 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}));
}
[Fact]
[Test]
public void RegisterInitializeTaskNullHandler()
{
// If: I register a null initialize task
@@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
Assert.Throws<ArgumentNullException>(() => sh.RegisterInitializeTask(null));
}
[Fact]
[Test]
public void RegisterShutdownTask()
{
// Setup: Create mock initialize handler
@@ -84,11 +84,11 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
sh.RegisterShutdownTask(mockHandler);
// 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}));
}
[Fact]
[Test]
public void RegisterShutdownTaskNullHandler()
{
// If: I register a null initialize task
@@ -101,7 +101,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
#region IJsonRpcHost Tests
[Fact]
[Test]
public void SendEvent()
{
// 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);
}
[Fact]
[Test]
public async Task SendRequest()
{
// 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);
}
[Fact]
[Test]
public void SetAsyncEventHandler()
{
// 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);
}
[Fact]
[Test]
public void SetSyncEventHandler()
{
// 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);
}
[Fact]
[Test]
public void SetAsyncRequestHandler()
{
// 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);
}
[Fact]
[Test]
public void SetSyncRequestHandler()
{
// 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);
}
[Fact]
[Test]
public void Start()
{
// If: I start a service host
@@ -186,7 +186,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.Start(), Times.Once);
}
[Fact]
[Test]
public void Stop()
{
// If: I stop a service host
@@ -198,7 +198,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.Stop(), Times.Once);
}
[Fact]
[Test]
public void WaitForExit()
{
// If: I wait for service host to exit
@@ -214,7 +214,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
#region Request Handling Tests
[Fact]
[Test]
public void HandleExitNotification()
{
// If: I handle an exit notification
@@ -226,7 +226,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
jh.Verify(o => o.Stop(), Times.Once);
}
[Fact]
[Test]
public async Task HandleInitializeRequest()
{
// Setup:
@@ -255,14 +255,12 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
// ... The mock handler should have been called twice
mockHandler.Verify(h => h(initParams, mockContext), Times.Exactly(2));
// ... There should have been a response sent
var outgoing = bc.ToArray();
Assert.Single(outgoing);
Assert.Equal(CommonObjects.MessageId, outgoing[0].Id);
Assert.Equal(JToken.FromObject(ir), JToken.FromObject(ir));
Assert.That(outgoing.Select(m => m.Id), Is.EqualTo(new[] { CommonObjects.MessageId }), "There should have been a response sent");
Assert.AreEqual(JToken.FromObject(ir), JToken.FromObject(ir));
}
[Fact]
[Test]
public async Task HandleShutdownRequest()
{
// Setup:
@@ -284,12 +282,10 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ServiceHostTests
// If: I handle a shutdown request
await sh.HandleShutdownRequest(shutdownParams, mockContext);
// Then:
// ... The mock handler should have been called twice
mockHandler.Verify(h => h(shutdownParams, mockContext), Times.Exactly(2));
// ... There should have been a response sent
Assert.Single(bc);
mockHandler.Verify(h => h(shutdownParams, mockContext), Times.Exactly(2), "The mock handler should have been called twice");
Assert.That(bc.Count, Is.EqualTo(1), "There should have been a response sent");
}
#endregion

View File

@@ -7,13 +7,14 @@ using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Utility;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
{
[TestFixture]
public class AsyncLockTests
{
[Fact]
[Test]
public async Task AsyncLockSynchronizesAccess()
{
AsyncLock asyncLock = new AsyncLock();
@@ -21,15 +22,15 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
Task<IDisposable> lockOne = asyncLock.LockAsync();
Task<IDisposable> lockTwo = asyncLock.LockAsync();
Assert.Equal(TaskStatus.RanToCompletion, lockOne.Status);
Assert.Equal(TaskStatus.WaitingForActivation, lockTwo.Status);
Assert.AreEqual(TaskStatus.RanToCompletion, lockOne.Status);
Assert.AreEqual(TaskStatus.WaitingForActivation, lockTwo.Status);
lockOne.Result.Dispose();
await lockTwo;
Assert.Equal(TaskStatus.RanToCompletion, lockTwo.Status);
Assert.AreEqual(TaskStatus.RanToCompletion, lockTwo.Status);
}
[Fact]
[Test]
public void AsyncLockCancelsWhenRequested()
{
CancellationTokenSource cts = new CancellationTokenSource();
@@ -42,8 +43,8 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
cts.Cancel();
lockOne.Result.Dispose();
Assert.Equal(TaskStatus.RanToCompletion, lockOne.Status);
Assert.Equal(TaskStatus.Canceled, lockTwo.Status);
Assert.AreEqual(TaskStatus.RanToCompletion, lockOne.Status);
Assert.AreEqual(TaskStatus.Canceled, lockTwo.Status);
}
}
}

View File

@@ -7,10 +7,11 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.SqlTools.Hosting.Utility;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
{
[TestFixture]
/// <summary>
/// Logger test cases
/// </summary>
@@ -20,7 +21,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests
/// <summary>
/// Test to verify that the logger initialization is generating a valid file
/// </summary>
[Fact]
[Test]
public void LoggerDefaultFile()
{
// delete any existing log files from the current directory

View File

@@ -3,6 +3,4 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
[assembly: NUnit.Framework.NonParallelizable]

View File

@@ -7,10 +7,11 @@ using System;
using System.IO;
using Microsoft.SqlTools.ServiceLayer.BatchParser;
using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
{
[TestFixture]
public class BatchParserSqlCmdTests : IDisposable
{
private BatchParserSqlCmd bpcmd;
@@ -41,62 +42,62 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
}
}
[Fact]
[Test]
public void CheckSetVariable()
{
Assert.Equal(bpcmd.InternalVariables.Count, 3);
Assert.AreEqual(3, bpcmd.InternalVariables.Count);
bpcmd.SetVariable(testPOS, "variable4", "test4");
bpcmd.SetVariable(testPOS, "variable5", "test5");
bpcmd.SetVariable(testPOS, "variable6", "test6");
Assert.Equal(bpcmd.InternalVariables.Count, 6);
Assert.AreEqual(6, bpcmd.InternalVariables.Count);
}
[Fact]
[Test]
public void CheckSetNullValueVariable()
{
Assert.Equal(bpcmd.InternalVariables.Count, 3);
Assert.AreEqual(3, bpcmd.InternalVariables.Count);
bpcmd.SetVariable(testPOS, "variable4", "test4");
Assert.Equal(bpcmd.InternalVariables.Count, 4);
Assert.AreEqual(4, bpcmd.InternalVariables.Count);
bpcmd.SetVariable(testPOS, "variable4", null);
Assert.Equal(bpcmd.InternalVariables.Count, 3);
Assert.AreEqual(3, bpcmd.InternalVariables.Count);
}
[Fact]
[Test]
public void CheckGetVariable()
{
string value = bpcmd.GetVariable(testPOS, "variable1");
Assert.Equal("test1", value);
Assert.AreEqual("test1", value);
value = bpcmd.GetVariable(testPOS, "variable2");
Assert.Equal("test2", value);
Assert.AreEqual("test2", value);
value = bpcmd.GetVariable(testPOS, "variable3");
Assert.Equal("test3", value);
Assert.AreEqual("test3", value);
}
[Fact]
[Test]
public void CheckGetNullVariable()
{
Assert.Null(bpcmd.GetVariable(testPOS, "variable6"));
}
[Fact]
[Test]
public void CheckInclude()
{
TextReader textReader = null;
string outString = "out";
var result = bpcmd.Include(null, out textReader, out outString);
Assert.Equal(result, BatchParserAction.Abort);
Assert.AreEqual(BatchParserAction.Abort, result);
}
[Fact]
[Test]
public void CheckOnError()
{
var errorActionChanged = bpcmd.ErrorActionChanged;
var action = new OnErrorAction();
var result = bpcmd.OnError(null, action);
Assert.Equal(result, BatchParserAction.Continue);
Assert.AreEqual(BatchParserAction.Continue, result);
}
[Fact]
[Test]
public void CheckConnectionChangedDelegate()
{
var initial = bpcmd.ConnectionChanged;
@@ -104,7 +105,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
Assert.Null(bpcmd.ConnectionChanged);
}
[Fact]
[Test]
public void CheckVariableSubstitutionDisabled()
{
bpcmd.DisableVariableSubstitution();

View File

@@ -14,12 +14,13 @@ using Microsoft.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Text;
using Xunit;
using NUnit.Framework;
using Microsoft.SqlTools.ServiceLayer.Connection;
using System.Threading.Tasks;
namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
{
[TestFixture]
public class BatchParserTests : BaselinedTest
{
public BatchParserTests()
@@ -34,7 +35,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
TestInitialize();
}
[Fact]
[Test]
public void VerifyThrowOnUnresolvedVariable()
{
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
/// for use in the sqlcmd script, and sets a value for the variable.
/// </summary>
[Fact]
[Test]
public void VerifyVariableResolverUsingVaribleParameter()
{
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.
[Fact]
[Test]
public void VerifyVariableResolverIsStartIdentifierChar()
{
// 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.
[Fact]
[Test]
public void VerifyVariableResolverIsIdentifierChar()
{
// 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.
[Fact]
[Test]
public void VerifyInvalidNumber()
{
string query = @" SELECT 1+1
@@ -144,7 +145,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
}
// Verify the Batch execution is executed successfully.
[Fact]
[Test]
public void VerifyExecute()
{
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))
{
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.
[Fact]
[Test]
public void VerifyHandleExceptionMessage()
{
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;
Assert.Equal<ScriptExecutionResult>(finalResult, ScriptExecutionResult.Failure);
Assert.AreEqual(ScriptExecutionResult.Failure, finalResult);
}
// Verify the passing query has valid text.
[Fact]
[Test]
public void VerifyHasValidText()
{
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;
Assert.Equal<ScriptExecutionResult>(finalResult, ScriptExecutionResult.Failure);
Assert.AreEqual(ScriptExecutionResult.Failure, finalResult);
}
// Verify the cancel functionality is working fine.
[Fact]
[Test]
public void VerifyCancel()
{
ScriptExecutionResult result = ScriptExecutionResult.All;
@@ -200,14 +201,14 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
batch.Cancel();
result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
}
Assert.Equal<ScriptExecutionResult>(result, ScriptExecutionResult.Cancel);
Assert.AreEqual(ScriptExecutionResult.Cancel, result);
}
//
/// <summary>
/// Verify whether lexer can consume token for SqlCmd variable
/// </summary>
[Fact]
[Test]
public void VerifyLexerSetState()
{
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
// 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()
{
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());
// 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"
[Fact]
[Test]
public void VerifyLexerTypeOfSqlCmdIFisExecute()
{
string query = ":!!if exist foo.txt del foo.txt";
@@ -264,33 +265,26 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
type = lexer.CurrentTokenType;
}
// 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.
[Fact]
[Test]
public void VerifyCustomBatchParserException()
{
string message = "This is userDefined Error";
Token token = new Token(LexerTokenType.Text, new PositionStruct(), new PositionStruct(), message, "test");
BatchParserException batchParserException = new BatchParserException(ErrorCode.VariableNotDefined, token, message);
try
{
throw new BatchParserException(ErrorCode.UnrecognizedToken, token, "test");
}
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);
}
BatchParserException batchParserException = new BatchParserException(ErrorCode.VariableNotDefined, token, message);
Assert.AreEqual(batchParserException.ErrorCode.ToString(), ErrorCode.VariableNotDefined.ToString());
Assert.AreEqual(message, batchParserException.Text);
Assert.AreEqual(LexerTokenType.Text.ToString(), batchParserException.TokenType.ToString());
}
// Verify whether the executionEngine execute script
[Fact]
[Test]
public void VerifyExecuteScript()
{
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;
Assert.Equal<ScriptExecutionResult>(ScriptExecutionResult.Success, result);
Assert.AreEqual(ScriptExecutionResult.Success, result);
}
}
}
// 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()
{
using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -330,7 +324,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
/// <summary>
/// Verify whether the batchParser execute SqlCmd successfully
/// </summary>
[Fact]
[Test]
public void VerifyRunSqlCmd()
{
using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -365,7 +359,7 @@ GO";
/// <summary>
/// Verify whether the batchParser parsed :connect command successfully
/// </summary>
[Fact]
[Test]
public void VerifyConnectSqlCmd()
{
using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -374,14 +368,15 @@ GO";
string serverName = liveConnection.ConnectionInfo.ConnectionDetails.ServerName;
string userName = liveConnection.ConnectionInfo.ConnectionDetails.UserName;
string password = liveConnection.ConnectionInfo.ConnectionDetails.Password;
var credentials = string.IsNullOrEmpty(userName) ? string.Empty : $"-U {userName} -P {password}";
string sqlCmdQuery = $@"
:Connect {serverName} -U {userName} -P {password}
:Connect {serverName}{credentials}
GO
select * from sys.databases where name = 'master'
GO";
string sqlCmdQueryIncorrect = $@"
:Connect {serverName} -u {userName} -p {password}
:Connect {serverName} -u uShouldbeUpperCase -p pShouldbeUpperCase
GO
select * from sys.databases where name = 'master'
GO";
@@ -390,17 +385,23 @@ GO";
using (TestExecutor testExecutor = new TestExecutor(sqlCmdQuery, sqlConn, condition))
{
testExecutor.Run();
Assert.True(testExecutor.ParserExecutionError == false, "Parse Execution error should be false");
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.Multiple(() =>
{
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 (TestExecutor testExecutor = new TestExecutor(sqlCmdQueryIncorrect, sqlConn, condition))
{
testExecutor.Run();
Assert.True(testExecutor.ParserExecutionError == true, "Parse Execution error should be true");
Assert.Multiple(() =>
{
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>
/// Verify whether the batchParser parsed :on error successfully
/// </summary>
[Fact]
[Test]
public void VerifyOnErrorSqlCmd()
{
using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -443,7 +444,7 @@ GO";
/// <summary>
/// Verify whether the batchParser parses Include command i.e. :r successfully
/// </summary>
[Fact]
[Test]
public void VerifyIncludeSqlCmd()
{
string file = "VerifyIncludeSqlCmd_test.sql";
@@ -486,7 +487,7 @@ GO";
}
// Verify whether the executionEngine execute Batch
[Fact]
[Test]
public void VerifyExecuteBatch()
{
using (ExecutionEngine executionEngine = new ExecutionEngine())
@@ -498,7 +499,7 @@ GO";
var executionPromise = new TaskCompletionSource<bool>();
executionEngine.BatchParserExecutionFinished += (object sender, BatchParserExecutionFinishedEventArgs e) =>
{
Assert.Equal(ScriptExecutionResult.Success, e.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success, e.ExecutionResult);
executionPromise.SetResult(true);
};
executionEngine.ExecuteBatch(new ScriptExecutionArgs(query, sqlConn, 15, new ExecutionEngineConditions(), new BatchParserMockEventHandler()));
@@ -508,7 +509,7 @@ GO";
}
}
[Fact]
[Test]
public void CanceltheBatch()
{
Batch batch = new Batch();
@@ -567,7 +568,7 @@ GO";
if (lexerError == false)
{
// Verify that all text from tokens can be recombined into original string
Assert.Equal<string>(inputText, roundtripTextBuilder.ToString());
Assert.AreEqual(inputText, roundtripTextBuilder.ToString());
}
}
}

View File

@@ -6,31 +6,32 @@
using System;
using Microsoft.SqlTools.ServiceLayer.BatchParser;
using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
{
[TestFixture]
public class BatchParserWrapperTests
{
[Fact]
[Test]
public void CheckSimpleSingleSQLBatchStatement()
{
using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
{
string sqlScript = "select * from sys.objects";
var batches = parserWrapper.GetBatches(sqlScript);
Assert.Equal(1, batches.Count);
Assert.AreEqual(1, batches.Count);
BatchDefinition batch = batches[0];
Assert.Equal(sqlScript, batch.BatchText);
Assert.Equal(1, batch.StartLine);
Assert.Equal(1, batch.StartColumn);
Assert.Equal(2, batch.EndLine);
Assert.Equal(sqlScript.Length + 1, batch.EndColumn);
Assert.Equal(1, batch.BatchExecutionCount);
Assert.AreEqual(sqlScript, batch.BatchText);
Assert.AreEqual(1, batch.StartLine);
Assert.AreEqual(1, batch.StartColumn);
Assert.AreEqual(2, batch.EndLine);
Assert.AreEqual(sqlScript.Length + 1, batch.EndColumn);
Assert.AreEqual(1, batch.BatchExecutionCount);
}
}
[Fact]
[Test]
public void CheckSimpleMultipleQLBatchStatement()
{
using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
@@ -44,48 +45,48 @@ namespace Microsoft.SqlTools.ManagedBatchParser.UnitTests.BatchParser
SELECT 'LastLine'";
var batches = parserWrapper.GetBatches(sqlScript);
// 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()
{
using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
{
string sqlScript = "select * from sys.object" + Environment.NewLine + "GO 2";
var batches = parserWrapper.GetBatches(sqlScript);
Assert.Equal(1, batches.Count);
Assert.AreEqual(1, batches.Count);
BatchDefinition batch = batches[0];
Assert.Equal(2, batch.BatchExecutionCount);
Assert.AreEqual(2, batch.BatchExecutionCount);
}
}
[Fact]
[Test]
public void CheckComment()
{
using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
{
string sqlScript = "-- this is a comment --";
var batches = parserWrapper.GetBatches(sqlScript);
Assert.Equal(1, batches.Count);
Assert.AreEqual(1, batches.Count);
BatchDefinition batch = batches[0];
Assert.Equal(sqlScript, batch.BatchText);
Assert.Equal(1, batch.StartLine);
Assert.Equal(1, batch.StartColumn);
Assert.Equal(2, batch.EndLine);
Assert.Equal(sqlScript.Length + 1, batch.EndColumn);
Assert.AreEqual(sqlScript, batch.BatchText);
Assert.AreEqual(1, batch.StartLine);
Assert.AreEqual(1, batch.StartColumn);
Assert.AreEqual(2, batch.EndLine);
Assert.AreEqual(sqlScript.Length + 1, batch.EndColumn);
}
}
[Fact]
[Test]
public void CheckNoOps()
{
using (BatchParserWrapper parserWrapper = new BatchParserWrapper())
{
string sqlScript = "GO";
var batches = parserWrapper.GetBatches(sqlScript);
Assert.Equal(0, batches.Count);
Assert.AreEqual(0, batches.Count);
}
}
}

View File

@@ -19,8 +19,9 @@
<PackageReference Include="System.Net.Http"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Moq" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="nunit" />
<PackageReference Include="nunit3testadapter" />
<PackageReference Include="nunit.console" />
</ItemGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />

View File

@@ -12,15 +12,16 @@ using Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEngine
{
[TestFixture]
/// <summary>
///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
///</summary>
public class ExecutionEngineTest : IDisposable
{
private SqlConnection connection;
@@ -29,11 +30,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
#region Test Initialize And Cleanup
public ExecutionEngineTest()
{
TestInitialize();
}
[SetUp]
// Initialize the tests
public void TestInitialize()
{
@@ -80,7 +77,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
///A test for a simple SQL script
///</summary>
[Fact]
[Test]
public void ExecutionEngineTest_SimpleTest()
{
string sqlStatement = "SELECT * FROM sysobjects";
@@ -97,15 +94,15 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
Assert.Equal(1, executor.BatchFinshedEventCounter);
Assert.AreEqual(1, executor.BatchFinshedEventCounter);
}
/// <summary>
/// Test with a valid script using default execution condition
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_DefaultCondition_ValidScript()
{
string sqlStatement = "select * from sysobjects\nGo\n";
@@ -119,14 +116,14 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
}
// <summary>
// Test with multiple valid scripts in multiple batches
// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_MultiValidScripts()
{
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;
ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
}
/// <summary>
/// Test with SQL comment
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_TestComment()
{
string sqlStatement = "/*test comments*/";
@@ -167,7 +164,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts;
ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
}
@@ -178,7 +175,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// Test with a invalid query using the default execution condition
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_DefaultCondition_InvalidScript()
{
string sqlStatement = "select ** from sysobjects";
@@ -192,17 +189,17 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts;
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(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
Assert.Equal(0, executor.BatchFinshedEventCounter);
Assert.AreEqual(0, executor.BatchFinshedEventCounter);
}
/// <summary>
/// Test with an invalid query using a defined execution condition
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_InvalidScriptWithCondition()
{
string sqlStatement = "select * from authors";
@@ -218,7 +215,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts;
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(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
@@ -227,7 +224,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// Test with multiple invalid scripts in multiple batches
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_MultipleInvalidScript()
{
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;
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(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
@@ -253,7 +250,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// Test with invalid scripts within a single batch
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_MultipleInvalidScript_SingleBatch()
{
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;
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(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
@@ -279,7 +276,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// Test with mixed valid and invalid scripts
/// </summary>
[Fact]
[Test]
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";
@@ -296,13 +293,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts;
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(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
}
[Fact]
[Test]
public void ExecutionEngineTest_DiscardConnection()
{
ExecutionEngine engine = new ExecutionEngine();
@@ -316,14 +313,16 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// Test HaltOnError execution condition
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_HaltOnError()
{
string sqlStatement = "select * from authors\n go\n select * from sysbojects \n go \n";
ExecutionEngineConditions conditions = new ExecutionEngineConditions();
conditions.IsTransactionWrapped = true;
conditions.IsParseOnly = false;
conditions.IsHaltOnError = true;
ExecutionEngineConditions conditions = new ExecutionEngineConditions
{
IsTransactionWrapped = true,
IsParseOnly = false,
IsHaltOnError = true
};
TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions);
executor.Run();
@@ -332,7 +331,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts;
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(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
Assert.True(executor.ResultCountQueue.Count == 0);
@@ -341,7 +340,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// HaltOnError with a single batch
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_HaltOnError_OneBatch()
{
string sqlStatement = "select * from authors\n go 30\n";
@@ -357,17 +356,17 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts;
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(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
Assert.True(executor.ResultCountQueue.Count == 0);
Assert.Equal(0, executor.BatchFinshedEventCounter);
Assert.AreEqual(0, executor.BatchFinshedEventCounter);
}
/// <summary>
/// Test ParseOnly execution condition with valid scripts
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_ParseOnly_ValidScript()
{
string sqlStatement = "select * from sysobjects";
@@ -379,15 +378,15 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions);
executor.Run();
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(executor.ResultCountQueue.Count == 0);
Assert.Equal(0, executor.BatchFinshedEventCounter);
Assert.AreEqual(0, executor.BatchFinshedEventCounter);
}
/// <summary>
/// Test HaltOnError execution condition with invalid scripts
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_ParseOnly_InvalidScript()
{
string sqlStatement = "select ** from authors";
@@ -403,7 +402,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
List<string> batchScripts = executor.BatchScripts;
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.ResultCountQueue.Count == 0);
Assert.True(CompareTwoStringLists(executor.ErrorMessageQueue, expErrorMessage));
@@ -412,7 +411,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// Parse script only without transaction wrapper
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_ParseOnly_ValidScriptWithoutTransaction()
{
string sqlStatement = "select * from sysobjects";
@@ -424,9 +423,9 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions);
executor.Run();
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(executor.ResultCountQueue.Count == 0);
Assert.Equal(0, executor.BatchFinshedEventCounter);
Assert.AreEqual(0, executor.BatchFinshedEventCounter);
}
/// <summary>
@@ -443,13 +442,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
TestExecutor executor = new TestExecutor(sqlStatement, connection, conditions, -1);
executor.Run();
Assert.Equal(executor.ExecutionResult, ScriptExecutionResult.Success);
Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
}
/// <summary>
/// Test with invalid connection
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_InvalidConnection()
{
string sqlStatement = "select * from sysobjects\n go 100\n";
@@ -470,7 +469,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// Test with multiple conditions true
/// </summary>
[Fact]
[Test]
public void TestExecutionEngineConditions()
{
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;
ExecuteSqlBatch(batchScripts, connection);
Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult);
Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts));
}
@@ -497,7 +496,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// Test with SQL commands
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_SQLCmds()
{
string[] sqlStatements = {
@@ -537,7 +536,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// <summary>
/// Test synchronous cancel
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_SyncCancel()
{
string sqlStatement = "waitfor delay '0:0:10'";
@@ -552,14 +551,14 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
executor.Run();
Assert.NotNull(executor.ScriptExecuteThread);
Assert.Equal(ScriptExecutionResult.Cancel, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Cancel, executor.ExecutionResult);
Assert.True(executor.CancelEventFired);
}
/// <summary>
/// Test asynchronous cancel
/// </summary>
[Fact]
[Test]
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" ;
@@ -578,7 +577,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Assert.NotNull(executor.ScriptExecuteThread);
if (executor.ScriptExecuteThread != null)
Assert.True(!executor.ScriptExecuteThread.IsAlive);
Assert.Equal(ScriptExecutionResult.Cancel, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Cancel, executor.ExecutionResult);
}
/// <summary>
@@ -604,13 +603,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Assert.NotNull(executor.ScriptExecuteThread);
if (executor.ScriptExecuteThread != null)
Assert.True(!executor.ScriptExecuteThread.IsAlive);
Assert.Equal(ScriptExecutionResult.Success | ScriptExecutionResult.Cancel, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success | ScriptExecutionResult.Cancel, executor.ExecutionResult);
}
/// <summary>
/// Test async cancel when the execution is done
/// </summary>
[Fact]
[Test]
public void ExecutionEngineTest_ASyncCancelAfterExecutionDone()
{
string sqlStatement = "select 1";
@@ -628,13 +627,13 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Assert.NotNull(executor.ScriptExecuteThread);
if (executor.ScriptExecuteThread != null)
Assert.True(!executor.ScriptExecuteThread.IsAlive);
Assert.Equal(ScriptExecutionResult.Success | ScriptExecutionResult.Cancel, executor.ExecutionResult);
Assert.AreEqual(ScriptExecutionResult.Success | ScriptExecutionResult.Cancel, executor.ExecutionResult);
}
/// <summary>
/// Test multiple threads of execution engine with cancel operation
/// </summary>
[Fact]
[Test]
public async Task ExecutionEngineTest_MultiThreading_WithCancel()
{
string[] sqlStatement = { "waitfor delay '0:0:10'",
@@ -693,7 +692,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
#region Get/Set Methods
[Fact]
[Test]
public void TestShowStatements()
{
Assert.NotNull(ExecutionEngineConditions.ShowPlanXmlStatement(true));
@@ -708,48 +707,48 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Assert.NotNull(ExecutionEngineConditions.ResetStatement);
}
[Fact]
[Test]
public void TestExecutionEngineConditionsSetMethods()
{
ExecutionEngineConditions conditions = new ExecutionEngineConditions();
bool getValue = conditions.IsScriptExecutionTracked;
conditions.IsScriptExecutionTracked = !getValue;
Assert.Equal(conditions.IsScriptExecutionTracked, !getValue);
Assert.AreEqual(conditions.IsScriptExecutionTracked, !getValue);
getValue = conditions.IsEstimatedShowPlan;
conditions.IsEstimatedShowPlan = !getValue;
Assert.Equal(conditions.IsEstimatedShowPlan, !getValue);
Assert.AreEqual(conditions.IsEstimatedShowPlan, !getValue);
getValue = conditions.IsActualShowPlan;
conditions.IsActualShowPlan = !getValue;
Assert.Equal(conditions.IsActualShowPlan, !getValue);
Assert.AreEqual(conditions.IsActualShowPlan, !getValue);
getValue = conditions.IsSuppressProviderMessageHeaders;
conditions.IsSuppressProviderMessageHeaders = !getValue;
Assert.Equal(conditions.IsSuppressProviderMessageHeaders, !getValue);
Assert.AreEqual(conditions.IsSuppressProviderMessageHeaders, !getValue);
getValue = conditions.IsNoExec;
conditions.IsNoExec = !getValue;
Assert.Equal(conditions.IsNoExec, !getValue);
Assert.AreEqual(conditions.IsNoExec, !getValue);
getValue = conditions.IsStatisticsIO;
conditions.IsStatisticsIO = !getValue;
Assert.Equal(conditions.IsStatisticsIO, !getValue);
Assert.AreEqual(conditions.IsStatisticsIO, !getValue);
getValue = conditions.IsShowPlanText;
conditions.IsShowPlanText = !getValue;
Assert.Equal(conditions.IsShowPlanText, !getValue);
Assert.AreEqual(conditions.IsShowPlanText, !getValue);
getValue = conditions.IsStatisticsTime;
conditions.IsStatisticsTime = !getValue;
Assert.Equal(conditions.IsStatisticsTime, !getValue);
Assert.AreEqual(conditions.IsStatisticsTime, !getValue);
getValue = conditions.IsSqlCmd;
conditions.IsSqlCmd = !getValue;
Assert.Equal(conditions.IsSqlCmd, !getValue);
Assert.AreEqual(conditions.IsSqlCmd, !getValue);
conditions.BatchSeparator = "GO";
Assert.Equal(conditions.BatchSeparator, "GO");
Assert.AreEqual("GO", conditions.BatchSeparator);
}
#endregion Get/Set Methods

View File

@@ -9,7 +9,8 @@ using Microsoft.Data.SqlClient;
using System.Threading;
using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode;
using Microsoft.SqlTools.Utility;
using System.Runtime.CompilerServices;
namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEngine
{
internal class TestExecutor : IDisposable
@@ -17,9 +18,9 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
#region Private variables
private string sqlStatement;
private ExecutionEngineConditions conditions = new ExecutionEngineConditions();
private BatchEventHandler eventHandler = new BatchEventHandler();
private SqlConnection connection = null;
private readonly ExecutionEngineConditions conditions = new ExecutionEngineConditions();
private readonly BatchEventHandler eventHandler = new BatchEventHandler();
private readonly SqlConnection connection;
private static Thread _executionThread;
private bool _syncCancel = true;
private bool _isFinished = false;
@@ -31,12 +32,12 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
private List<int> resultCounts = new List<int>();
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 static ScriptExecutionResult execResult = ScriptExecutionResult.All;
private static List<string> batchScripts = new List<string>();
private static Thread exeThread = null;
private static bool parserExecutionError = false;
private bool parserExecutionError = false;
#endregion Private variables
@@ -322,10 +323,14 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
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);
if (execResult == ScriptExecutionResult.All)
execResult = e.ExecutionResult;
else
execResult = execResult | e.ExecutionResult;
if (execResult == ScriptExecutionResult.All)
{
execResult = e.ExecutionResult;
}
else
{
execResult |= e.ExecutionResult;
}
}
/// <summary>
@@ -333,11 +338,12 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
/// </summary>
/// <param name="sender"></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("\t Error Description: " + e.Description);
parserExecutionError = true;
errorMessage.Add(e.Description);
}
/// <summary>
@@ -350,14 +356,18 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn
Console.WriteLine("ON_EXECUTION_FINISHED : Script execution done with result ..." + e.ExecutionResult);
_isFinished = true;
if (execResult == ScriptExecutionResult.All)
execResult = e.ExecutionResult;
else
execResult = execResult | e.ExecutionResult;
if (execResult == ScriptExecutionResult.All)
{
execResult = e.ExecutionResult;
}
else
{
execResult |= e.ExecutionResult;
}
resultCounts = eventHandler.ResultCounts;
sqlMessages = eventHandler.SqlMessages;
errorMessage = eventHandler.ErrorMessages;
errorMessage.AddRange(eventHandler.ErrorMessages);
}
#endregion ParserEvent

View File

@@ -8,7 +8,7 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.Utility
{

View File

@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
using NUnit.Framework;
using Moq;
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Admin.Contracts;
@@ -44,8 +44,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.AdminServices
/// <summary>
/// Validate creating a database with valid input
/// </summary>
// [Fact]
public async void CreateDatabaseWithValidInputTest()
// [Test]
public async Task CreateDatabaseWithValidInputTest()
{
var result = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<CreateDatabaseResponse>>();
@@ -68,8 +68,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.AdminServices
/// <summary>
/// Get a default database info object
/// </summary>
// [Fact]
public async void GetDefaultDatebaseInfoTest()
// [Test]
public async Task GetDefaultDatebaseInfoTest()
{
var result = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<DefaultDatabaseInfoResponse>>();
@@ -89,8 +89,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.AdminServices
/// Get database info test
/// </summary>
/// Test is failing in code coverage runs. Reenable when stable.
/// [Fact]
public async void GetDatabaseInfoTest()
/// [Test]
public async Task GetDatabaseInfoTest()
{
var results = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<GetDatabaseInfoResponse>>();

View File

@@ -11,7 +11,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{
@@ -20,7 +20,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Verify default agent/alerts handlers
/// </summary>
[Fact]
[Test]
public async Task TestHandleAgentAlertsRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -42,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Verify the default "create agent alert" request handler with valid parameters
/// </summary>
[Fact]
[Test]
public async Task TestHandleCreateAgentAlertsRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -86,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Verify the default "update agent alert" request handler with valid parameters
/// </summary>
[Fact]
[Test]
public async Task TestHandleUpdateAgentAlertsRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())

View File

@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleCreateAgentJobStepRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleCreateAgentJobStepRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleUpdateAgentJobStepRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleUpdateAgentJobStepRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -71,7 +71,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleDeleteAgentJobRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleDeleteAgentJobStepRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())

View File

@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleCreateAgentJobRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleCreateAgentJobRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -43,7 +43,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleUpdateAgentJobRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleUpdateAgentJobRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -66,7 +66,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleDeleteAgentJobRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleDeleteAgentJobRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -86,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestAgentJobDefaultsRequest
/// </summary>
[Fact]
[Test]
public async Task TestAgentJobDefaultsRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())

View File

@@ -8,7 +8,7 @@ using Microsoft.SqlTools.ServiceLayer.Utility;
using Microsoft.SqlTools.ServiceLayer.Management;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{
@@ -17,7 +17,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Test case for fetch notebook jobs Request Handler
/// </summary>
[Fact]
[Test]
public async Task TestHandleAgentNotebooksRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -40,16 +40,16 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Tests the create job helper function
/// </summary>
[Fact]
internal async Task TestAgentNotebookCreateHelper()
[Test]
public async Task TestAgentNotebookCreateHelper()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);
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;
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook);
}
}
@@ -57,8 +57,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Tests the create job request handler with an invalid file path
/// </summary>
[Fact]
internal async Task TestHandleCreateAgentNotebookRequestWithInvalidTemplatePath()
[Test]
public async Task TestHandleCreateAgentNotebookRequestWithInvalidTemplatePath()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -75,15 +75,15 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
}, createNotebookContext.Object);
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>
/// creating a job with duplicate name
/// </summary>
[Fact]
internal async Task TestDuplicateJobCreation()
[Test]
public async Task TestDuplicateJobCreation()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -114,8 +114,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Tests the create notebook job handler
/// </summary>
[Fact]
internal async Task TestCreateAgentNotebookHandler()
[Test]
public async Task TestCreateAgentNotebookHandler()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -131,7 +131,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
TemplateFilePath = AgentTestUtils.CreateTemplateNotebookFile()
}, createNotebookContext.Object);
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);
await AgentTestUtils.CleanupNotebookJob(connectionResult, createdNotebook);
}
@@ -140,8 +140,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Tests the delete notebook job handler
/// </summary>
[Fact]
internal async Task TestDeleteAgentNotebookHandler()
[Test]
public async Task TestDeleteAgentNotebookHandler()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -150,7 +150,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
//creating a notebook job
AgentNotebookInfo notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
//verifying it's getting created
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
//deleting the notebook job
var deleteNotebookContext = new Mock<RequestContext<ResultStatus>>();
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.Verify(x => x.SendResult(It.Is<ResultStatus>(p => p.Success == true)));
//verifying if the job is deleted
Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
}
}
/// <summary>
/// deleting a existing notebook job
/// </summary>
[Fact]
internal async Task TestDeleteNonExistentJob()
[Test]
public async Task TestDeleteNonExistentJob()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -193,8 +193,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// updating a non existing notebook job
/// </summary>
[Fact]
internal async Task TestUpdateNonExistentJob()
[Test]
public async Task TestUpdateNonExistentJob()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -219,8 +219,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// update notebook handler with garbage path
/// </summary>
[Fact]
internal async Task TestUpdateWithGarbagePath()
[Test]
public async Task TestUpdateWithGarbagePath()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -230,7 +230,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
//seting up a temp notebook job
var notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
//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>>();
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
await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook);
Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
}
}
[Fact]
internal async Task TestDeletingUpdatedJob()
[Test]
public async Task TestDeletingUpdatedJob()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -261,13 +261,13 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
//seting up a temp notebook job
var notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
//verifying that the notebook is created
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
var originalName = notebook.Name;
//Changing the notebookName
notebook.Name = "myTestNotebookJob" + Guid.NewGuid().ToString();
Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
await AgentNotebookHelper.UpdateNotebook(
service,
@@ -278,7 +278,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
ManagementUtils.asRunType(0)
);
Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
Assert.AreEqual(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
//cleaning up the job
await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook);

View File

@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.Agent.Contracts;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{
@@ -19,7 +19,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Verify default agent/operators handlers
/// </summary>
[Fact]
[Test]
public async Task TestHandleAgentOperatorsRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -41,7 +41,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Verify the default "create agent alert" request handler with valid parameters
/// </summary>
[Fact]
[Test]
public async Task TestHandleCreateAgentOperatorRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -63,7 +63,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleUpdateAgentOperatorRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleUpdateAgentOperatorRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -87,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleDeleteAgentOperatorRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleDeleteAgentOperatorRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())

View File

@@ -14,7 +14,7 @@ using Microsoft.SqlTools.ServiceLayer.Security.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq;
using Xunit;
using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
@@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Verify default agent/proxies handlers
/// </summary>
[Fact]
[Test]
public async Task TestHandleAgentProxiesRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleCreateAgentProxyRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleCreateAgentProxyRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Verify the default "update agent alert" request handler with valid parameters
/// </summary>
[Fact]
[Test]
public async Task TestHandleUpdateAgentProxyRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -96,7 +96,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleDeleteAgentProxyRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleDeleteAgentProxyRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())

View File

@@ -11,7 +11,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq;
using Xunit;
using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// HandleAgentSchedulesRequest
/// </summary>
[Fact]
[Test]
public async Task HandleAgentSchedulesRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleCreateAgentScheduleRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleCreateAgentScheduleRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleUpdateAgentScheduleRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleUpdateAgentScheduleRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -95,7 +95,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// TestHandleDeleteAgentScheduleRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleDeleteAgentScheduleRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())

View File

@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
{
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Verify that a start profiling request starts a profiling session
/// </summary>
[Fact]
[Test]
public async Task TestHandleAgentJobsRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -44,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
/// <summary>
/// Verify that a job history request returns the job history
/// </summary>
[Fact]
[Test]
public async Task TestHandleJobHistoryRequests()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -65,7 +65,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent
}
}
[Fact]
[Test]
public async Task TestHandleAgentJobActionRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())

View File

@@ -3,6 +3,6 @@
// 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]

View File

@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq;
using System;
using System.Threading.Tasks;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
{
@@ -37,8 +37,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
return connectParams;
}
[Fact]
private async void TestAddCMS()
[Test]
public async Task TestAddCMS()
{
string name = "TestAddCMS" + DateTime.Now.ToString();
ConnectParams connectParams = CreateConnectParams();
@@ -63,8 +63,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
requestContext.VerifyAll();
}
[Fact]
private async void TestAddRemoveRegisteredServer()
[Test]
public async Task TestAddRemoveRegisteredServer()
{
string name = "TestAddRemoveRegisteredServer" + DateTime.Now.ToString();
ConnectParams connectParams = await CreateAndConnectWithConnectParams();
@@ -122,8 +122,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
requestContext3.VerifyAll();
}
[Fact]
private async void TestAddRemoveServerGroup()
[Test]
public async Task TestAddRemoveServerGroup()
{
string name = "TestAddRemoveServerGroup" + DateTime.Now.ToString();
ConnectParams connectParams = await CreateAndConnectWithConnectParams();
@@ -174,8 +174,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Cms
requestContext3.VerifyAll();
}
[Fact]
private async void TestAddRemoveNestedGroup()
[Test]
public async Task TestAddRemoveNestedGroup()
{
string name = "TestAddRemoveNestedGroup" + DateTime.Now.ToString();
ConnectParams connectParams = await CreateAndConnectWithConnectParams();

View File

@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
{
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// </summary>
public class ConnectionServiceTests
{
[Fact]
[Test]
public void RunningMultipleQueriesCreatesOnlyOneConnection()
{
// Connect/disconnect twice to ensure reconnection can occur
@@ -34,8 +34,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
string uri = connectionInfo.OwnerUri;
// We should see one ConnectionInfo and one DbConnection
Assert.Equal(1, connectionInfo.CountConnections);
Assert.Equal(1, service.OwnerToConnectionMap.Count);
Assert.AreEqual(1, connectionInfo.CountConnections);
Assert.AreEqual(1, service.OwnerToConnectionMap.Count);
// If we run a query
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -44,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
query.ExecutionTask.Wait();
// We should see two DbConnections
Assert.Equal(2, connectionInfo.CountConnections);
Assert.AreEqual(2, connectionInfo.CountConnections);
// If we run another query
query = new Query(Constants.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory);
@@ -52,18 +52,18 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
query.ExecutionTask.Wait();
// 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
// e.g. loop and do it over again
service.Disconnect(new DisconnectParams() { OwnerUri = connectionInfo.OwnerUri });
// 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()
{
// 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)
{
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)
{
Assert.Equal(connection.Database, newDatabaseName);
Assert.AreEqual(connection.Database, newDatabaseName);
}
}
}
@@ -109,8 +109,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Test HandleGetConnectionStringRequest
/// </summary>
[Fact]
public async void GetCurrentConnectionStringTest()
[Test]
public async Task GetCurrentConnectionStringTest()
{
// If we make a connection to a live database
ConnectionService service = ConnectionService.Instance;

View File

@@ -14,7 +14,7 @@ using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
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.TimeBasedRetryPolicy;
using static Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.SqlSchemaModelErrorCodes;
@@ -122,7 +122,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
}
}
[Fact]
[Test]
public void FixedDelayPolicyTest()
{
TestFixedDelayPolicy policy = new TestFixedDelayPolicy(
@@ -135,7 +135,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(shouldRety);
}
[Fact]
[Test]
public void FixedDelayPolicyExecuteActionTest()
{
TestFixedDelayPolicy policy = new TestFixedDelayPolicy(
@@ -145,7 +145,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
// execute an action that throws a retry limit exception
CancellationToken token = new CancellationToken();
Assert.Equal(policy.ExecuteAction<int>((s) => { throw new RetryLimitExceededException(); }, token), default(int));
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
Assert.Throws<Exception>(() =>
@@ -158,7 +158,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
});
}
[Fact]
[Test]
public void IsRetryableExceptionTest()
{
TestFixedDelayPolicy policy = new TestFixedDelayPolicy(
@@ -169,7 +169,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.False(policy.IsRetryableException(new Exception()));
}
[Fact]
[Test]
public void ProgressiveRetryPolicyTest()
{
TestProgressiveRetryPolicy policy = new TestProgressiveRetryPolicy(
@@ -184,7 +184,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.False(policy.ShouldIgnoreOnFirstTry);
}
[Fact]
[Test]
public void TimeBasedRetryPolicyTest()
{
TestTimeBasedRetryPolicy policy = new TestTimeBasedRetryPolicy(
@@ -200,7 +200,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
}
[Fact]
[Test]
public void GetErrorNumberWithNullExceptionTest()
{
Assert.Null(RetryPolicy.GetErrorNumber(null));
@@ -265,7 +265,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Test ReliableConnectionHelper.GetDefaultDatabaseFilePath()
/// </summary>
[Fact]
[Test]
public void TestGetDefaultDatabaseFilePath()
{
@@ -293,7 +293,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Test ReliableConnectionHelper.GetServerVersion()
/// </summary>
[Fact]
[Test]
public void TestGetServerVersion()
{
using (var connection = CreateTestConnection())
@@ -324,7 +324,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Tests ReliableConnectionHelper.GetCompleteServerName()
/// </summary>
[Fact]
[Test]
public void TestGetCompleteServerName()
{
string name = ReliableConnectionHelper.GetCompleteServerName(@".\SQL2008");
@@ -337,7 +337,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Tests ReliableConnectionHelper.IsDatabaseReadonly()
/// </summary>
[Fact]
[Test]
public void TestIsDatabaseReadonly()
{
var connectionBuilder = CreateTestConnectionStringBuilder();
@@ -350,7 +350,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// /// Tests ReliableConnectionHelper.IsDatabaseReadonly() with null builder parameter
/// </summary>
[Fact]
[Test]
public void TestIsDatabaseReadonlyWithNullBuilder()
{
Assert.Throws<ArgumentNullException>(() => ReliableConnectionHelper.IsDatabaseReadonly(null, null));
@@ -359,7 +359,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Verify ANSI_NULL and QUOTED_IDENTIFIER settings can be set and retrieved for a session
/// </summary>
[Fact]
[Test]
public void VerifyAnsiNullAndQuotedIdentifierSettingsReplayed()
{
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);
// assert cached settings are correct
Assert.Equal("ANSI_NULLS", settings[0].Item1);
Assert.Equal(expectedSessionValue, settings[0].Item2);
Assert.AreEqual("ANSI_NULLS", settings[0].Item1);
Assert.AreEqual(expectedSessionValue, settings[0].Item2);
Assert.Equal("QUOTED_IDENTIFIER", settings[1].Item1);
Assert.Equal(expectedSessionValue, settings[1].Item2);
Assert.AreEqual("QUOTED_IDENTIFIER", settings[1].Item1);
Assert.AreEqual(expectedSessionValue, settings[1].Item2);
// 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");
bool actualAnsiNullsOnValue = ((int)reader[0] == 1);
bool actualQuotedIdentifierOnValue = ((int)reader[1] == 1);
Assert.Equal(ansiNullsValue, actualAnsiNullsOnValue);
Assert.Equal(quotedIdentifersValue, actualQuotedIdentifierOnValue);
Assert.AreEqual(ansiNullsValue, actualAnsiNullsOnValue);
Assert.AreEqual(quotedIdentifersValue, actualQuotedIdentifierOnValue);
}
}
@@ -442,7 +442,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Test that the retry policy factory constructs all possible types of policies successfully.
/// </summary>
[Fact]
[Test]
public void RetryPolicyFactoryConstructsPoliciesSuccessfully()
{
RunIfWrapper.RunIfWindows(() =>
@@ -468,7 +468,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// ReliableConnectionHelper.IsCloud() should be false for a local server
/// </summary>
[Fact]
[Test]
public void TestIsCloudIsFalseForLocalServer()
{
using (var connection = CreateTestConnection())
@@ -483,7 +483,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Tests that ReliableConnectionHelper.OpenConnection() opens a connection if it is closed
/// </summary>
[Fact]
[Test]
public void TestOpenConnectionOpensConnection()
{
using (var connection = CreateTestConnection())
@@ -499,7 +499,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Tests that ReliableConnectionHelper.ExecuteNonQuery() runs successfully
/// </summary>
[Fact]
[Test]
public void TestExecuteNonQuery()
{
var result = ReliableConnectionHelper.ExecuteNonQuery(
@@ -516,7 +516,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Test that TryGetServerVersion() gets server information
/// </summary>
[Fact]
[Test]
public void TestTryGetServerVersion()
{
ReliableConnectionHelper.ServerInfo info = null;
@@ -524,14 +524,13 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(ReliableConnectionHelper.TryGetServerVersion(connBuilder.ConnectionString, out info, null));
Assert.NotNull(info);
Assert.NotNull(info.ServerVersion);
Assert.NotEmpty(info.ServerVersion);
Assert.That(info.ServerVersion, Is.Not.Null.Or.Empty);
}
/// <summary>
/// Test that TryGetServerVersion() fails with invalid connection string
/// </summary>
[Fact]
[Test]
public void TestTryGetServerVersionInvalidConnectionString()
{
RunIfWrapper.RunIfWindows(() =>
@@ -544,7 +543,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Validate ambient static settings
/// </summary>
[Fact]
[Test]
public void AmbientSettingsStaticPropertiesTest()
{
var defaultSettings = AmbientSettings.DefaultSettings;
@@ -578,7 +577,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
/// <summary>
/// Validate ambient settings populate
/// </summary>
[Fact]
[Test]
public void AmbientSettingsPopulateTest()
{
var data = new AmbientSettings.AmbientData();
@@ -626,7 +625,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
data.TraceSettings();
}
[Fact]
[Test]
public void RaiseAmbientRetryMessageTest()
{
bool handlerCalled = false;
@@ -637,7 +636,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(handlerCalled);
}
[Fact]
[Test]
public void RaiseAmbientIgnoreMessageTest()
{
bool handlerCalled = false;
@@ -648,7 +647,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(handlerCalled);
}
[Fact]
[Test]
public void RetryPolicyFactoryTest()
{
Assert.NotNull(RetryPolicyFactory.NoRetryPolicy);
@@ -673,7 +672,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.False(transientPolicy.ShouldIgnoreError(new Exception()));
}
[Fact]
[Test]
public void ReliableConnectionHelperTest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -700,7 +699,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
}
}
[Fact]
[Test]
public void DataSchemaErrorTests()
{
var error = new DataSchemaError();
@@ -722,7 +721,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(DataSchemaError.FormatErrorCode("ex", 1));
}
[Fact]
[Test]
public void InitReliableSqlConnectionTest()
{
var result = LiveConnectionHelper.InitLiveConnectionInfo();
@@ -743,7 +742,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
connection.ClearPool();
}
[Fact]
[Test]
public void ThrottlingReasonTests()
{
var reason = RetryPolicy.ThrottlingReason.Unknown;
@@ -794,7 +793,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(codeReason.ToString());
}
[Fact]
[Test]
public void RetryErrorsTest()
{
var sqlServerRetryError = new SqlServerRetryError(
@@ -817,7 +816,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.True(SqlSchemaModelErrorCodes.IsStatementFilterError(StatementFilter.StatementFilterBaseCode + 1));
}
[Fact]
[Test]
public void RetryCallbackEventArgsTest()
{
var exception = new Exception();
@@ -828,38 +827,38 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
// 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
Assert.Equal(5, args.RetryCount);
Assert.Equal(exception, args.Exception);
Assert.Equal(timespan, args.Delay);
Assert.AreEqual(5, args.RetryCount);
Assert.AreEqual(exception, args.Exception);
Assert.AreEqual(timespan, args.Delay);
}
[Fact]
[Test]
public void CheckStaticVariables()
{
Assert.NotNull(ReliableConnectionHelper.BuilderWithDefaultApplicationName);
}
[Fact]
[Test]
public void SetLockAndCommandTimeoutThrowsOnNull()
{
Assert.Throws(typeof(ArgumentNullException), () => ReliableConnectionHelper.SetLockAndCommandTimeout(null));
}
[Fact]
[Test]
public void StandardExceptionHandlerTests()
{
Assert.True(ReliableConnectionHelper.StandardExceptionHandler(new InvalidCastException()));
Assert.False(ReliableConnectionHelper.StandardExceptionHandler(new Exception()));
}
[Fact]
[Test]
public void GetConnectionStringBuilderNullConnectionString()
{
SqlConnectionStringBuilder builder;
Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder(null, out builder));
}
[Fact]
[Test]
public void GetConnectionStringBuilderExceptionTests()
{
SqlConnectionStringBuilder builder;
@@ -871,7 +870,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder("rabbits**frogs**lizards", out builder));
}
[Fact]
[Test]
public void GetCompleteServerNameTests()
{
Assert.Null(ReliableConnectionHelper.GetCompleteServerName(null));
@@ -881,7 +880,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(ReliableConnectionHelper.GetCompleteServerName("mytestservername"));
}
[Fact]
[Test]
public void ReliableSqlCommandConstructorTests()
{
// verify default constructor doesn't throw
@@ -891,18 +890,18 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(new ReliableSqlConnection.ReliableSqlCommand(null));
}
[Fact]
[Test]
public void ReliableSqlCommandProperties()
{
var command = new ReliableSqlConnection.ReliableSqlCommand();
command.CommandText = "SELECT 1";
Assert.Equal(command.CommandText, "SELECT 1");
Assert.AreEqual("SELECT 1", command.CommandText);
Assert.NotNull(command.CommandTimeout);
Assert.NotNull(command.CommandType);
command.DesignTimeVisible = true;
Assert.True(command.DesignTimeVisible);
command.UpdatedRowSource = UpdateRowSource.None;
Assert.Equal(command.UpdatedRowSource, UpdateRowSource.None);
Assert.AreEqual(UpdateRowSource.None, command.UpdatedRowSource);
Assert.NotNull(command.GetUnderlyingCommand());
Assert.Throws<InvalidOperationException>(() => command.ValidateConnectionIsSet());
command.Prepare();
@@ -910,7 +909,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
command.Cancel();
}
[Fact]
[Test]
public void ReliableConnectionResourcesTests()
{
Assert.NotNull(Resources.ConnectionPassedToIsCloudShouldBeOpen);
@@ -924,19 +923,19 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.NotNull(Resources.UnableToRetrieveAzureSessionId);
}
[Fact]
[Test]
public void CalcExponentialRetryDelayWithSchemaDefaultsTest()
{
Assert.NotNull(RetryPolicyUtils.CalcExponentialRetryDelayWithSchemaDefaults(1));
}
[Fact]
[Test]
public void IsSupportedCommandNullCommandTest()
{
Assert.False(DbCommandWrapper.IsSupportedCommand(null));
}
[Fact]
[Test]
public void StatementCompletedTests()
{
StatementCompletedEventHandler handler = (s, e) => { };

View File

@@ -17,8 +17,8 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.SchemaCompare.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using NUnit.Framework;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DacFx
{
@@ -71,8 +71,8 @@ RETURN 0
/// <summary>
/// Verify the export bacpac request
/// </summary>
[Fact]
public async void ExportBacpac()
[Test]
public async Task ExportBacpac()
{
var result = GetLiveAutoCompleteTestObjects();
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest");
@@ -102,8 +102,8 @@ RETURN 0
/// <summary>
/// Verify the import bacpac request
/// </summary>
[Fact]
public async void ImportBacpac()
[Test]
public async Task ImportBacpac()
{
// first export a bacpac
var result = GetLiveAutoCompleteTestObjects();
@@ -150,8 +150,8 @@ RETURN 0
/// <summary>
/// Verify the extract dacpac request
/// </summary>
[Fact]
public async void ExtractDacpac()
[Test]
public async Task ExtractDacpac()
{
var result = GetLiveAutoCompleteTestObjects();
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExtractTest");
@@ -183,8 +183,8 @@ RETURN 0
/// <summary>
/// Verify the extract request to create Sql file
/// </summary>
[Fact]
public async void ExtractDBToFileTarget()
[Test]
public async Task ExtractDBToFileTarget()
{
var result = GetLiveAutoCompleteTestObjects();
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, doNotCleanupDb: false, databaseName: null, query: SourceScript, dbNamePrefix: "DacFxExtractDBToFileTarget");
@@ -217,8 +217,8 @@ RETURN 0
/// <summary>
/// Verify the extract request to create a Flat file structure
/// </summary>
[Fact]
public async void ExtractDBToFlatTarget()
[Test]
public async Task ExtractDBToFlatTarget()
{
var result = GetLiveAutoCompleteTestObjects();
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
// 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;
Assert.Equal(2, actualCnt);
Assert.AreEqual(2, actualCnt);
}
finally
{
@@ -259,8 +259,8 @@ RETURN 0
/// <summary>
/// Verify the deploy dacpac request
/// </summary>
[Fact]
public async void DeployDacpac()
[Test]
public async Task DeployDacpac()
{
// first extract a db to have a dacpac to import later
var result = GetLiveAutoCompleteTestObjects();
@@ -305,13 +305,14 @@ RETURN 0
targetDb.Cleanup();
}
}
return;
}
/// <summary>
/// Verify the export request being cancelled
/// </summary>
[Fact]
public async void ExportBacpacCancellationTest()
[Test]
public async Task ExportBacpacCancellationTest()
{
var result = GetLiveAutoCompleteTestObjects();
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest");
@@ -353,8 +354,8 @@ RETURN 0
/// <summary>
/// Verify the generate deploy script request
/// </summary>
[Fact]
public async void GenerateDeployScript()
[Test]
public async Task GenerateDeployScript()
{
// first extract a dacpac
var result = GetLiveAutoCompleteTestObjects();
@@ -378,8 +379,8 @@ RETURN 0
service.PerformOperation(generateScriptOperation, TaskExecutionMode.Script);
// Verify script was generated
Assert.NotEmpty(generateScriptOperation.Result.DatabaseScript);
Assert.Contains("CREATE TABLE", generateScriptOperation.Result.DatabaseScript);
Assert.That(generateScriptOperation.Result.DatabaseScript, Is.Not.Empty);
Assert.That(generateScriptOperation.Result.DatabaseScript, Does.Contain("CREATE TABLE"));
VerifyAndCleanup(dacpacPath);
}
@@ -393,8 +394,8 @@ RETURN 0
/// <summary>
/// Verify the generate deploy plan request
/// </summary>
[Fact]
public async void GenerateDeployPlan()
[Test]
public async Task GenerateDeployPlan()
{
var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "DacFxGenerateDeployPlanTest");
@@ -418,9 +419,12 @@ RETURN 0
service.PerformOperation(generateDeployPlanOperation, TaskExecutionMode.Execute);
string report = generateDeployPlanOperation.DeployReport;
Assert.NotNull(report);
Assert.Contains("Create", report);
Assert.Contains("Drop", report);
Assert.Contains("Alter", report);
Assert.Multiple(() =>
{
Assert.That(report, Does.Contain("Create"));
Assert.That(report, Does.Contain("Drop"));
Assert.That(report, Does.Contain("Alter"));
});
VerifyAndCleanup(dacpacPath);
}
@@ -437,8 +441,8 @@ RETURN 0
// <summary>
/// Verify that SqlCmdVars are set correctly for a deploy request
/// </summary>
[Fact]
public async void DeployWithSqlCmdVariables()
[Test]
public async Task DeployWithSqlCmdVariables()
{
var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: storedProcScript, dbNamePrefix: "DacFxDeploySqlCmdVarsTest");
@@ -482,8 +486,8 @@ RETURN 0
}
}
Assert.Contains(deployParams.SqlCommandVariableValues[databaseRefVarName], deployedProc);
Assert.Contains(deployParams.SqlCommandVariableValues[filterValueVarName], deployedProc);
Assert.That(deployedProc, Does.Contain(deployParams.SqlCommandVariableValues[databaseRefVarName]));
Assert.That(deployedProc, Does.Contain(deployParams.SqlCommandVariableValues[filterValueVarName]));
VerifyAndCleanup(dacpacPath);
}
@@ -500,8 +504,8 @@ RETURN 0
// <summary>
/// Verify that SqlCmdVars are set correctly for a generate script request
/// </summary>
[Fact]
public async void GenerateDeployScriptWithSqlCmdVariables()
[Test]
public async Task GenerateDeployScriptWithSqlCmdVariables()
{
var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: storedProcScript, dbNamePrefix: "DacFxGenerateScriptSqlCmdVarsTest");
@@ -528,9 +532,9 @@ RETURN 0
service.PerformOperation(generateScriptOperation, TaskExecutionMode.Script);
// Verify the SqlCmdVars were set correctly in the script
Assert.NotEmpty(generateScriptOperation.Result.DatabaseScript);
Assert.Contains($":setvar {databaseRefVarName} \"{generateScriptParams.SqlCommandVariableValues[databaseRefVarName]}\"", generateScriptOperation.Result.DatabaseScript);
Assert.Contains($":setvar {filterValueVarName} \"{generateScriptParams.SqlCommandVariableValues[filterValueVarName]}\"", generateScriptOperation.Result.DatabaseScript);
Assert.That(generateScriptOperation.Result.DatabaseScript, Is.Not.Empty);
Assert.That(generateScriptOperation.Result.DatabaseScript, Does.Contain($":setvar {databaseRefVarName} \"{generateScriptParams.SqlCommandVariableValues[databaseRefVarName]}\""));
Assert.That(generateScriptOperation.Result.DatabaseScript, Does.Contain($":setvar {filterValueVarName} \"{generateScriptParams.SqlCommandVariableValues[filterValueVarName]}\""));
VerifyAndCleanup(dacpacPath);
}
@@ -543,8 +547,8 @@ RETURN 0
///
/// Verify that options are set correctly for a deploy request
/// </summary>
[Fact]
public async void DeployWithOptions()
[Test]
public async Task DeployWithOptions()
{
var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: SourceScript, dbNamePrefix: "DacFxDeployOptionsTestSource");
@@ -607,10 +611,10 @@ RETURN 0
{
await conn.OpenAsync();
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'; ");
Assert.Equal(expectedViewResult, deployedResult);
Assert.AreEqual(expectedViewResult, deployedResult);
}
finally
{
@@ -622,8 +626,8 @@ RETURN 0
// <summary>
/// Verify that options are set correctly for a generate script request
/// </summary>
[Fact]
public async void GenerateDeployScriptWithOptions()
[Test]
public async Task GenerateDeployScriptWithOptions()
{
var result = GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query: SourceScript, dbNamePrefix: "DacFxDeployOptionsTestSource");
@@ -651,8 +655,8 @@ RETURN 0
var generateScriptFalseOptionOperation = new GenerateDeployScriptOperation(generateScriptFalseOptionParams, result.ConnectionInfo);
service.PerformOperation(generateScriptFalseOptionOperation, TaskExecutionMode.Execute);
Assert.DoesNotContain("table3", generateScriptFalseOptionOperation.Result.DatabaseScript);
Assert.DoesNotContain("CREATE VIEW", generateScriptFalseOptionOperation.Result.DatabaseScript);
Assert.That(generateScriptFalseOptionOperation.Result.DatabaseScript, Does.Not.Contain("table3"));
Assert.That(generateScriptFalseOptionOperation.Result.DatabaseScript, Does.Not.Contain("CREATE VIEW"));
// try to deploy with the option set to true to make sure it works
var generateScriptTrueOptionParams = new GenerateDeployScriptParams
@@ -669,8 +673,8 @@ RETURN 0
var generateScriptTrueOptionOperation = new GenerateDeployScriptOperation(generateScriptTrueOptionParams, result.ConnectionInfo);
service.PerformOperation(generateScriptTrueOptionOperation, TaskExecutionMode.Execute);
Assert.Contains("DROP TABLE [dbo].[table3]", generateScriptTrueOptionOperation.Result.DatabaseScript);
Assert.DoesNotContain("CREATE VIEW", generateScriptTrueOptionOperation.Result.DatabaseScript);
Assert.That(generateScriptTrueOptionOperation.Result.DatabaseScript, Does.Contain("DROP TABLE [dbo].[table3]"));
Assert.That(generateScriptTrueOptionOperation.Result.DatabaseScript, Does.Not.Contain("CREATE VIEW"));
// now generate script without options
var generateScriptNoOptionsParams = new GenerateDeployScriptParams
@@ -682,8 +686,8 @@ RETURN 0
var generateScriptNoOptionsOperation = new GenerateDeployScriptOperation(generateScriptNoOptionsParams, result.ConnectionInfo);
service.PerformOperation(generateScriptNoOptionsOperation, TaskExecutionMode.Execute);
Assert.Contains("table3", generateScriptNoOptionsOperation.Result.DatabaseScript);
Assert.Contains("CREATE VIEW", generateScriptNoOptionsOperation.Result.DatabaseScript);
Assert.That(generateScriptNoOptionsOperation.Result.DatabaseScript, Does.Contain("table3"));
Assert.That(generateScriptNoOptionsOperation.Result.DatabaseScript, Does.Contain("CREATE VIEW"));
VerifyAndCleanup(dacpacPath);
}
@@ -700,8 +704,8 @@ RETURN 0
// <summary>
/// Verify that options can get retrieved from publish profile
/// </summary>
[Fact]
public async void GetOptionsFromProfile()
[Test]
public async Task GetOptionsFromProfile()
{
DeploymentOptions expectedResults = new DeploymentOptions()
{
@@ -729,8 +733,8 @@ RETURN 0
// <summary>
/// Verify that default options are returned if a profile doesn't specify any options
/// </summary>
[Fact]
public async void GetOptionsFromProfileWithoutOptions()
[Test]
public async Task GetOptionsFromProfileWithoutOptions()
{
DeploymentOptions expectedResults = new DeploymentOptions();
expectedResults.ExcludeObjectTypes = null;

View File

@@ -22,7 +22,7 @@ using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
{
@@ -42,8 +42,8 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// Get backup configuration info
/// </summary>
/// Test is failing in code coverage runs. Reenable when stable.
///[Fact]
public async void GetBackupConfigInfoTest()
///[Test]
public async Task GetBackupConfigInfoTest()
{
string databaseName = "testbackup_" + new Random().Next(10000000, 99999999);
using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName))
@@ -72,7 +72,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// <summary>
/// Create simple backup test
/// </summary>
[Fact]
[Test]
public void CreateBackupTest()
{
DisasterRecoveryService service = new DisasterRecoveryService();
@@ -100,7 +100,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
}
}
[Fact]
[Test]
public void ScriptBackupTest()
{
DisasterRecoveryService service = new DisasterRecoveryService();
@@ -137,7 +137,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// <summary>
/// Test creating backup with advanced options set.
/// </summary>
[Fact]
[Test]
public void CreateBackupWithAdvancedOptionsTest()
{
DisasterRecoveryService service = new DisasterRecoveryService();
@@ -190,7 +190,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// <summary>
/// Test creating backup with advanced options set.
/// </summary>
[Fact]
[Test]
public void ScriptBackupWithAdvancedOptionsTest()
{
DisasterRecoveryService service = new DisasterRecoveryService();
@@ -245,7 +245,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; ";
/// <summary>
/// Test the correct script generation for different backup action types
/// </summary>
[Fact]
[Test]
public void ScriptBackupWithDifferentActionTypesTest()
{
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);
// Validate Full backup script
Assert.Contains("BACKUP DATABASE", script, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase);
Assert.That(script, Does.Contain("BACKUP DATABASE").IgnoreCase);
Assert.That(script, Does.Not.Contain("BACKUP LOG").IgnoreCase);
Assert.That(script, Does.Not.Contain("DIFFERENTIAL").IgnoreCase);
// Create log backup script
script = GenerateScriptForBackupType(BackupType.TransactionLog, databaseName);
// Validate Log backup script
Assert.Contains("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("BACKUP DATABASE", script, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase);
Assert.That(script, Does.Contain("BACKUP LOG").IgnoreCase);
Assert.That(script, Does.Not.Contain("BACKUP DATABASE").IgnoreCase);
Assert.That(script, Does.Not.Contain("DIFFERENTIAL").IgnoreCase);
// Create differential backup script
script = GenerateScriptForBackupType(BackupType.Differential, databaseName);
// Validate differential backup script
Assert.Contains("BACKUP DATABASE", script, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase);
Assert.Contains("WITH DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase);
Assert.That(script, Does.Contain("BACKUP DATABASE").IgnoreCase);
Assert.That(script, Does.Not.Contain("BACKUP LOG").IgnoreCase);
Assert.That(script, Does.Contain("WITH DIFFERENTIAL").IgnoreCase);
}
}
//[Fact]
public async void BackupFileBrowserTest()
//[Test]
public async Task BackupFileBrowserTest()
{
string databaseName = "testfilebrowser_" + new Random().Next(10000000, 99999999);
SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);

View File

@@ -13,7 +13,7 @@ using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.Contracts;
using Microsoft.SqlTools.ServiceLayer.FileBrowser;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Management;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
{
@@ -22,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
/// </summary>
public class DisasterRecoveryFileValidatorTests
{
[Fact]
[Test]
public void ValidateDefaultBackupFullFilePath()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -39,10 +39,10 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}, out message);
Assert.True(result);
Assert.Empty(message);
Assert.That(message, Is.Empty);
}
[Fact]
[Test]
public void ValidateDefaultBackupFolderPath()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -56,7 +56,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
Assert.True(result);
}
//[Fact]
//[Test]
public void ValidatorShouldReturnFalseForInvalidPath()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");

View File

@@ -23,7 +23,7 @@ using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests;
using Moq;
using Xunit;
using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
@@ -65,16 +65,16 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
return backupFilesToRecoverDatabase;
}
[Fact]
public async void RestorePlanShouldCreatedSuccessfullyForFullBackup()
[Test]
public async Task RestorePlanShouldCreatedSuccessfullyForFullBackup()
{
await VerifyBackupFileCreated();
bool canRestore = true;
await VerifyRestore(fullBackupFilePath, canRestore);
}
[Fact]
public async void RestoreShouldNotRestoreAnyBackupSetsIfFullNotSelected()
[Test]
public async Task RestoreShouldNotRestoreAnyBackupSetsIfFullNotSelected()
{
var backupFiles = await GetBackupFilesToRecoverDatabaseCreated();
//Remove the full backupset
@@ -85,8 +85,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
await VerifyRestoreMultipleBackupSets(backupFiles, indexToDelete, expectedTable, TaskExecutionModeFlag.Execute);
}
[Fact]
public async void RestoreShouldRestoreFromAnotherDatabase()
[Test]
public async Task RestoreShouldRestoreFromAnotherDatabase()
{
await GetBackupFilesToRecoverDatabaseCreated();
@@ -106,8 +106,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
public async void RestoreShouldFailIfThereAreOtherConnectionsToDatabase()
[Test]
public async Task RestoreShouldFailIfThereAreOtherConnectionsToDatabase()
{
await GetBackupFilesToRecoverDatabaseCreated();
@@ -138,8 +138,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
public async void RestoreShouldFailIfThereAreOtherConnectionsToDatabase2()
[Test]
public async Task RestoreShouldFailIfThereAreOtherConnectionsToDatabase2()
{
await GetBackupFilesToRecoverDatabaseCreated();
@@ -173,8 +173,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
public async void RestoreShouldCloseOtherConnectionsBeforeExecuting()
[Test]
public async Task RestoreShouldCloseOtherConnectionsBeforeExecuting()
{
await GetBackupFilesToRecoverDatabaseCreated();
@@ -213,8 +213,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
public async void RestoreShouldRestoreTheBackupSetsThatAreSelected()
[Test]
public async Task RestoreShouldRestoreTheBackupSetsThatAreSelected()
{
var backupFiles = await GetBackupFilesToRecoverDatabaseCreated();
//Remove the last backupset
@@ -225,8 +225,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
await VerifyRestoreMultipleBackupSets(backupFiles, indexToDelete, expectedTable);
}
[Fact]
public async void RestoreShouldNotRestoreTheLogBackupSetsIfOneNotSelected()
[Test]
public async Task RestoreShouldNotRestoreTheLogBackupSetsIfOneNotSelected()
{
var backupFiles = await GetBackupFilesToRecoverDatabaseCreated();
//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++)
{
DatabaseFileInfo databaseInfo = response.BackupSetsToRestore[i];
Assert.Equal(databaseInfo.IsSelected, expectedSelectedIndexes.Contains(i));
Assert.AreEqual(databaseInfo.IsSelected, expectedSelectedIndexes.Contains(i));
}
}
finally
@@ -288,8 +288,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
public async void RestorePlanShouldCreatedSuccessfullyOnExistingDatabaseGivenReplaceOption()
[Test]
public async Task RestorePlanShouldCreatedSuccessfullyOnExistingDatabaseGivenReplaceOption()
{
SqlTestDb testDb = null;
try
@@ -312,8 +312,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
public async void RestorePlanShouldFailOnExistingDatabaseNotGivenReplaceOption()
[Test]
public async Task RestorePlanShouldFailOnExistingDatabaseNotGivenReplaceOption()
{
SqlTestDb testDb = null;
try
@@ -334,8 +334,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
//[Fact]
public async void RestoreShouldCreatedSuccessfullyGivenTwoBackupFiles()
//[Test]
public async Task RestoreShouldCreatedSuccessfullyGivenTwoBackupFiles()
{
string[] backupFileNames = new string[] { "FullBackup.bak", "DiffBackup.bak" };
@@ -344,8 +344,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
Assert.True(response.BackupSetsToRestore.Count() == 2);
}
//[Fact]
public async void RestoreShouldFailGivenTwoBackupFilesButFilterFullBackup()
//[Test]
public async Task RestoreShouldFailGivenTwoBackupFilesButFilterFullBackup()
{
string[] backupFileNames = new string[] { "FullBackup.bak", "DiffBackup.bak" };
@@ -360,8 +360,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
//[Fact]
public async void RestoreShouldCompletedSuccessfullyGivenTwoBackupFilesButFilterDifferentialBackup()
//[Test]
public async Task RestoreShouldCompletedSuccessfullyGivenTwoBackupFilesButFilterDifferentialBackup()
{
string[] backupFileNames = new string[] { "FullBackup.bak", "DiffBackup.bak" };
@@ -376,8 +376,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
public async void RestoreShouldExecuteSuccessfullyForFullBackup()
[Test]
public async Task RestoreShouldExecuteSuccessfullyForFullBackup()
{
await VerifyBackupFileCreated();
@@ -387,8 +387,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
Assert.NotNull(restorePlan.BackupSetsToRestore);
}
[Fact]
public async void RestoreToAnotherDatabaseShouldExecuteSuccessfullyForFullBackup()
[Test]
public async Task RestoreToAnotherDatabaseShouldExecuteSuccessfullyForFullBackup()
{
await VerifyBackupFileCreated();
@@ -397,23 +397,23 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
var restorePlan = await VerifyRestore(backupFileName, canRestore, TaskExecutionModeFlag.ExecuteAndScript, "NewRestoredDatabase");
}
//[Fact]
public async void RestorePlanShouldCreatedSuccessfullyForDiffBackup()
//[Test]
public async Task RestorePlanShouldCreatedSuccessfullyForDiffBackup()
{
string backupFileName = "DiffBackup.bak";
bool canRestore = true;
await VerifyRestore(backupFileName, canRestore);
}
//[Fact]
public async void RestorePlanShouldCreatedSuccessfullyForTransactionLogBackup()
//[Test]
public async Task RestorePlanShouldCreatedSuccessfullyForTransactionLogBackup()
{
string backupFileName = "TransactionLogBackup.bak";
bool canRestore = true;
await VerifyRestore(backupFileName, canRestore);
}
[Fact]
[Test]
public async Task RestorePlanRequestShouldReturnResponseWithDbFiles()
{
await VerifyBackupFileCreated();
@@ -439,7 +439,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
[Test]
public async Task CancelRestorePlanRequestShouldCancelSuccessfully()
{
await VerifyBackupFileCreated();
@@ -473,7 +473,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
[Test]
public async Task RestoreConfigInfoRequestShouldReturnResponse()
{
await VerifyBackupFileCreated();
@@ -499,7 +499,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
[Test]
public async Task RestoreDatabaseRequestShouldStartTheRestoreTask()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -526,7 +526,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
}
}
[Fact]
[Test]
public async Task RestorePlanRequestShouldReturnErrorMessageGivenInvalidFilePath()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -625,7 +625,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
Assert.NotNull(response);
Assert.False(string.IsNullOrWhiteSpace(response.SessionId));
Assert.Equal(response.CanRestore, canRestore);
Assert.AreEqual(response.CanRestore, canRestore);
if (canRestore)
{
Assert.True(response.DbFiles.Any());
@@ -633,7 +633,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
{
targetDatabase = response.DatabaseName;
}
Assert.Equal(response.DatabaseName, targetDatabase);
Assert.AreEqual(response.DatabaseName, targetDatabase);
Assert.NotNull(response.PlanDetails);
Assert.True(response.PlanDetails.Any());
Assert.NotNull(response.PlanDetails[RestoreOptionsHelper.BackupTailLog]);
@@ -649,7 +649,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
{
request.SessionId = response.SessionId;
restoreDataObject = service.CreateRestoreDatabaseTaskDataObject(request);
Assert.Equal(response.SessionId, restoreDataObject.SessionId);
Assert.AreEqual(response.SessionId, restoreDataObject.SessionId);
request.RelocateDbFiles = !restoreDataObject.DbFilesLocationAreValid();
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
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))

View File

@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.FileBrowser.Contracts;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
{
@@ -21,8 +21,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
{
#region Request handle tests
[Fact]
public async void HandleFileBrowserOpenRequestTest()
[Test]
public async Task HandleFileBrowserOpenRequestTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
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)));
}
[Fact]
public async void HandleFileBrowserExpandRequestTest()
[Test]
public async Task HandleFileBrowserExpandRequestTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
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)));
}
[Fact]
public async void HandleFileBrowserValidateRequestTest()
[Test]
public async Task HandleFileBrowserValidateRequestTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
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)));
}
[Fact]
public async void HandleFileBrowserCloseRequestTest()
[Test]
public async Task HandleFileBrowserCloseRequestTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
FileBrowserService service = new FileBrowserService();
@@ -96,8 +96,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
#endregion
[Fact]
public async void OpenFileBrowserTest()
[Test]
public async Task OpenFileBrowserTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
FileBrowserService service = new FileBrowserService();
@@ -123,8 +123,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
efv.Validate();
}
[Fact]
public async void ValidateSelectedFilesWithNullValidatorTest()
[Test]
public async Task ValidateSelectedFilesWithNullValidatorTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo();
FileBrowserService service = new FileBrowserService();
@@ -146,8 +146,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.FileBrowser
efv.Validate();
}
[Fact]
public async void InvalidFileValidationTest()
[Test]
public async Task InvalidFileValidationTest()
{
FileBrowserService service = new FileBrowserService();
service.RegisterValidatePathsCallback("TestService", ValidatePaths);

View File

@@ -17,15 +17,15 @@ using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
{
public class ExternalLanguageServiceTests : ServiceTestBase
{
[Fact]
public async void VerifyExternalLanguageStatusRequest()
[Test]
public async Task VerifyExternalLanguageStatusRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -50,8 +50,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}
}
[Fact]
public async void VerifyExternalLanguageDeleteRequest()
[Test]
public async Task VerifyExternalLanguageDeleteRequest()
{
ExternalLanguage language = new ExternalLanguage
{
@@ -80,8 +80,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}));
}
[Fact]
public async void VerifyExternalLanguageDeleteRequestFailures()
[Test]
public async Task VerifyExternalLanguageDeleteRequestFailures()
{
ExternalLanguage language = new ExternalLanguage
{
@@ -106,8 +106,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
});
}
[Fact]
public async void VerifyExternalLanguageDeleteRequestConnectionFailures()
[Test]
public async Task VerifyExternalLanguageDeleteRequestConnectionFailures()
{
ExternalLanguage language = new ExternalLanguage
{
@@ -131,8 +131,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
});
}
[Fact]
public async void VerifyExternalLanguageUpdateRequest()
[Test]
public async Task VerifyExternalLanguageUpdateRequest()
{
ExternalLanguage language = new ExternalLanguage
{
@@ -161,8 +161,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}));
}
[Fact]
public async void VerifyExternalLanguageUpdateRequestFailures()
[Test]
public async Task VerifyExternalLanguageUpdateRequestFailures()
{
ExternalLanguage language = new ExternalLanguage
{
@@ -187,8 +187,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
});
}
[Fact]
public async void VerifyExternalLanguageUpdateRequestConnectionFailures()
[Test]
public async Task VerifyExternalLanguageUpdateRequestConnectionFailures()
{
ExternalLanguage language = new ExternalLanguage
{
@@ -212,8 +212,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
});
}
[Fact]
public async void VerifyExternalLanguageListRequest()
[Test]
public async Task VerifyExternalLanguageListRequest()
{
ExternalLanguage language = new ExternalLanguage
{
@@ -241,8 +241,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}));
}
[Fact]
public async void VerifyExternalLanguagListRequestFailures()
[Test]
public async Task VerifyExternalLanguagListRequestFailures()
{
ExternalLanguage language = new ExternalLanguage
{
@@ -266,8 +266,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
});
}
[Fact]
public async void VerifyExternalLanguagListRequestConnectionFailures()
[Test]
public async Task VerifyExternalLanguagListRequestConnectionFailures()
{
ExternalLanguage language = new ExternalLanguage
{
@@ -323,8 +323,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageExtensibility
}
}
[Fact]
public async void VerifyExternalLanguageStatusRequestSendErrorGivenInvalidConnection()
[Test]
public async Task VerifyExternalLanguageStatusRequestSendErrorGivenInvalidConnection()
{
ExternalLanguageStatusResponseParams result = null;
var requestContext = RequestContextMocks.Create<ExternalLanguageStatusResponseParams>(r => result = r).AddErrorHandling(null);

View File

@@ -22,7 +22,7 @@ using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
{
@@ -51,7 +51,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary>
/// Test the service initialization code path and verify nothing throws
/// </summary>
[Fact]
[Test]
public void ServiceInitialization()
{
try
@@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary>
/// Test the service initialization code path and verify nothing throws
/// </summary>
//[Fact]
//[Test]
public void PrepopulateCommonMetadata()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -89,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary>
/// This test tests auto completion
/// </summary>
[Fact]
[Test]
public void AutoCompleteFindCompletions()
{
var result = GetLiveAutoCompleteTestObjects();
@@ -123,8 +123,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// 2. Initializing a completion extension implementation
/// 3. Excuting an auto completion with extension enabled
/// </summary>
[Fact]
public async void AutoCompleteWithExtension()
[Test]
public async Task AutoCompleteWithExtension()
{
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
/// provide signature help.
/// </summary>
[Fact]
[Test]
public async Task GetSignatureHelpReturnsNotNullIfParseInfoInitialized()
{
// When we make a connection to a live database
@@ -257,7 +257,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary>
/// Test overwriting the binding queue context
/// </summary>
[Fact]
[Test]
public void OverwriteBindingContext()
{
var result = LiveConnectionHelper.InitLiveConnectionInfo();
@@ -279,7 +279,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// <summary>
/// Verifies that clearing the Intellisense cache correctly refreshes the cache with new info from the DB.
/// </summary>
[Fact]
[Test]
public async Task RebuildIntellisenseCacheClearsScriptParseInfoCorrectly()
{
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.
// Will change to better handling once we have specific SQLCMD intellisense in Language Service
/// </summary>
[Fact]
[Test]
public async Task HandleRequestToChangeToSqlcmdFile()
{

View File

@@ -15,7 +15,7 @@ using System;
using System.Data.Common;
using System.IO;
using System.Threading;
using Xunit;
using NUnit.Framework;
using ConnectionType = Microsoft.SqlTools.ServiceLayer.Connection.ConnectionType;
using Location = Microsoft.SqlTools.ServiceLayer.Workspace.Contracts.Location;
using System.Collections.Generic;
@@ -86,7 +86,7 @@ GO";
/// <summary>
/// Test get definition for a table object with active connection
/// </summary>
[Fact]
[Test]
public void GetValidTableDefinitionTest()
{
// Get live connectionInfo and serverConnection
@@ -105,7 +105,7 @@ GO";
Cleanup(locations);
}
[Fact]
[Test]
public void LoggerGetValidTableDefinitionTest()
{
TestLogger test = new TestLogger()
@@ -126,7 +126,7 @@ GO";
/// <summary>
/// Test get definition for a invalid table object with active connection
/// </summary>
[Fact]
[Test]
public void GetTableDefinitionInvalidObjectTest()
{
// Get live connectionInfo and serverConnection
@@ -146,7 +146,7 @@ GO";
/// <summary>
/// Test get definition for a valid table object with schema and active connection
/// </summary>
[Fact]
[Test]
public void GetTableDefinitionWithSchemaTest()
{
// Get live connectionInfo and serverConnection
@@ -168,7 +168,7 @@ GO";
/// <summary>
/// Test GetDefinition with an unsupported type(schema - dbo). Expect a error result.
/// </summary>
[Fact]
[Test]
public void GetUnsupportedDefinitionErrorTest()
{
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -187,7 +187,7 @@ GO";
/// <summary>
/// Get Definition for a object with no definition. Expect a error result
/// </summary>
[Fact]
[Test]
public void GetDefinitionWithNoResultsFoundError()
{
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -206,13 +206,13 @@ GO";
Assert.NotNull(result);
Assert.True(result.IsErrorResult);
Assert.Equal(SR.PeekDefinitionNoResultsError, result.Message);
Assert.AreEqual(SR.PeekDefinitionNoResultsError, result.Message);
}
/// <summary>
/// Test GetDefinition with a forced timeout. Expect a error result.
/// </summary>
[Fact]
[Test]
public void GetDefinitionTimeoutTest()
{
// Given a binding queue that will automatically time out
@@ -268,13 +268,13 @@ GO";
Assert.NotNull(result);
Assert.True(result.IsErrorResult);
// Check timeout message
Assert.Equal(SR.PeekDefinitionTimedoutError, result.Message);
Assert.AreEqual(SR.PeekDefinitionTimedoutError, result.Message);
}
/// <summary>
/// Test get definition for a view object with active connection
/// </summary>
[Fact]
[Test]
public void GetValidViewDefinitionTest()
{
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -293,7 +293,7 @@ GO";
/// <summary>
/// Test get definition for an invalid view object with no schema name and with active connection
/// </summary>
[Fact]
[Test]
public void GetViewDefinitionInvalidObjectTest()
{
// Get live connectionInfo and serverConnection
@@ -312,7 +312,7 @@ GO";
/// <summary>
/// Test get definition for a stored procedure object with active connection
/// </summary>
[Fact]
[Test]
public void GetStoredProcedureDefinitionTest()
{
// Get live connectionInfo and serverConnection
@@ -333,7 +333,7 @@ GO";
/// <summary>
/// Test get definition for a stored procedure object that does not exist with active connection
/// </summary>
[Fact]
[Test]
public void GetStoredProcedureDefinitionFailureTest()
{
// Get live connectionInfo and serverConnection
@@ -352,7 +352,7 @@ GO";
/// <summary>
/// Test get definition for a stored procedure object with active connection and no schema
/// </summary>
[Fact]
[Test]
public void GetStoredProcedureDefinitionWithoutSchemaTest()
{
// Get live connectionInfo and serverConnection
@@ -372,7 +372,7 @@ GO";
/// <summary>
/// Test get definition for a scalar valued function object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetScalarValuedFunctionDefinitionWithSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName);
@@ -421,7 +421,7 @@ GO";
/// <summary>
/// Test get definition for a table valued function object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetTableValuedFunctionDefinitionWithSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, ScalarValuedFunctionTypeName);
@@ -430,7 +430,7 @@ GO";
/// <summary>
/// Test get definition for a scalar valued function object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
[Test]
public async Task GetScalarValuedFunctionDefinitionWithNonExistentFailureTest()
{
string objectName = "doesNotExist";
@@ -443,7 +443,7 @@ GO";
/// <summary>
/// Test get definition for a table valued function object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
[Test]
public async Task GetTableValuedFunctionDefinitionWithNonExistentObjectFailureTest()
{
string objectName = "doesNotExist";
@@ -455,7 +455,7 @@ GO";
/// <summary>
/// Test get definition for a scalar valued function object with active connection. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetScalarValuedFunctionDefinitionWithoutSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName, null);
@@ -464,7 +464,7 @@ GO";
/// <summary>
/// Test get definition for a table valued function object with active connection. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetTableValuedFunctionDefinitionWithoutSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, ScalarValuedFunctionTypeName, null);
@@ -474,7 +474,7 @@ GO";
/// <summary>
/// Test get definition for a user defined data type object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetUserDefinedDataTypeDefinitionWithSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName);
@@ -483,7 +483,7 @@ GO";
/// <summary>
/// Test get definition for a user defined data type object with active connection. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetUserDefinedDataTypeDefinitionWithoutSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName, null);
@@ -492,7 +492,7 @@ GO";
/// <summary>
/// Test get definition for a user defined data type object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
[Test]
public async Task GetUserDefinedDataTypeDefinitionWithNonExistentFailureTest()
{
string objectName = "doesNotExist";
@@ -504,7 +504,7 @@ GO";
/// <summary>
/// Test get definition for a user defined table type object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetUserDefinedTableTypeDefinitionWithSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName);
@@ -513,7 +513,7 @@ GO";
/// <summary>
/// Test get definition for a user defined table type object with active connection. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetUserDefinedTableTypeDefinitionWithoutSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName, null);
@@ -522,7 +522,7 @@ GO";
/// <summary>
/// Test get definition for a user defined table type object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
[Test]
public async Task GetUserDefinedTableTypeDefinitionWithNonExistentFailureTest()
{
string objectName = "doesNotExist";
@@ -535,7 +535,7 @@ GO";
/// <summary>
/// Test get definition for a synonym object with active connection and explicit schema name. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetSynonymDefinitionWithSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName);
@@ -545,7 +545,7 @@ GO";
/// <summary>
/// Test get definition for a Synonym object with active connection. Expect non-null locations
/// </summary>
[Fact]
[Test]
public async Task GetSynonymDefinitionWithoutSchemaNameSuccessTest()
{
await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName, null);
@@ -554,7 +554,7 @@ GO";
/// <summary>
/// Test get definition for a Synonym object that doesn't exist with active connection. Expect null locations
/// </summary>
[Fact]
[Test]
public async Task GetSynonymDefinitionWithNonExistentFailureTest()
{
string objectName = "doesNotExist";
@@ -567,7 +567,7 @@ GO";
/// Test get definition using declaration type for a view object with active connection
/// Expect a non-null result with location
/// </summary>
[Fact]
[Test]
public void GetDefinitionUsingDeclarationTypeWithValidObjectTest()
{
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -589,7 +589,7 @@ GO";
/// Test get definition using declaration type for a non existent view object with active connection
/// Expect a non-null result with location
/// </summary>
[Fact]
[Test]
public void GetDefinitionUsingDeclarationTypeWithNonexistentObjectTest()
{
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -608,7 +608,7 @@ GO";
/// Test get definition using quickInfo text for a view object with active connection
/// Expect a non-null result with location
/// </summary>
[Fact]
[Test]
public void GetDefinitionUsingQuickInfoTextWithValidObjectTest()
{
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -631,7 +631,7 @@ GO";
/// Test get definition using quickInfo text for a view object with active connection
/// Expect a non-null result with location
/// </summary>
[Fact]
[Test]
public void GetDefinitionUsingQuickInfoTextWithNonexistentObjectTest()
{
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -652,7 +652,7 @@ GO";
/// Given that there is no query connection
/// Expect database name to be "master"
/// </summary>
[Fact]
[Test]
public void GetDatabaseWithNoQueryConnectionTest()
{
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -663,7 +663,7 @@ GO";
Scripter scripter = new Scripter(serverConnection, connInfo);
//Check if database name is the default server connection database name
Assert.Equal(scripter.Database.Name, "master");
Assert.AreEqual("master", scripter.Database.Name);
}
/// <summary>
@@ -671,7 +671,7 @@ GO";
/// Give that there is a query connection
/// Expect database name to be query connection's database name
/// </summary>
[Fact]
[Test]
public void GetDatabaseWithQueryConnectionTest()
{
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
@@ -686,7 +686,7 @@ GO";
Scripter scripter = new Scripter(serverConnection, connInfo);
//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
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
/// objects
/// </summary>
[Fact]
public async void GetDefinitionFromChildrenAndParents()
[Test]
public async Task GetDefinitionFromChildrenAndParents()
{
string queryString = "select * from master.sys.objects";
// place the cursor on every token
@@ -743,8 +743,8 @@ GO";
Assert.NotNull(masterResult);
// And I expect the all results to be the same
Assert.True(CompareLocations(objectResult.Locations, sysResult.Locations));
Assert.True(CompareLocations(objectResult.Locations, masterResult.Locations));
Assert.That(objectResult.Locations, Is.EqualTo(sysResult.Locations), "objectResult and sysResult Locations");
Assert.That(objectResult.Locations, Is.EqualTo(masterResult.Locations), "objectResult and masterResult Locations");
Cleanup(objectResult.Locations);
Cleanup(sysResult.Locations);
@@ -753,8 +753,8 @@ GO";
connInfo.RemoveAllConnections();
}
[Fact]
public async void GetDefinitionFromProcedures()
[Test]
public async Task GetDefinitionFromProcedures()
{
string queryString = "EXEC master.dbo.sp_MSrepl_startup";

View File

@@ -17,7 +17,7 @@ using Microsoft.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
@@ -70,7 +70,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
/// <summary>
/// Verify that the metadata service correctly returns details for user tables
/// </summary>
[Fact]
[Test]
public void MetadataReturnsUserTable()
{
this.testTableName += new Random().Next(1000000, 9999999).ToString();
@@ -100,8 +100,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
DeleteTestTable(sqlConn);
}
[Fact]
public async void GetTableInfoReturnsValidResults()
[Test]
public async Task GetTableInfoReturnsValidResults()
{
this.testTableName += new Random().Next(1000000, 9999999).ToString();
@@ -127,8 +127,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
requestContext.VerifyAll();
}
[Fact]
public async void GetViewInfoReturnsValidResults()
[Test]
public async Task GetViewInfoReturnsValidResults()
{
var result = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<TableMetadataResult>>();
@@ -146,8 +146,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Metadata
requestContext.VerifyAll();
}
[Fact]
public async void VerifyMetadataList()
[Test]
public async Task VerifyMetadataList()
{
string query = @"CREATE TABLE testTable1 (c1 int)
GO

View File

@@ -20,8 +20,9 @@
<PackageReference Include="Moq" />
<PackageReference Include="System.Net.Http"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="nunit" />
<PackageReference Include="nunit3testadapter" />
<PackageReference Include="nunit.console" />
</ItemGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />

View File

@@ -17,7 +17,7 @@ using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Test.Common.Baselined;
using Microsoft.SqlTools.ServiceLayer.Test.Common.Extensions;
using Xunit;
using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.ObjectExplorer.ObjectExplorerService;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
@@ -26,8 +26,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
{
private ObjectExplorerService _service = TestServiceProvider.Instance.ObjectExplorerService;
[Fact]
public async void CreateSessionAndExpandOnTheServerShouldReturnServerAsTheRoot()
[Test]
public async Task CreateSessionAndExpandOnTheServerShouldReturnServerAsTheRoot()
{
var query = "";
string databaseName = null;
@@ -37,8 +37,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
});
}
[Fact]
public async void CreateSessionWithTempdbAndExpandOnTheServerShouldReturnServerAsTheRoot()
[Test]
public async Task CreateSessionWithTempdbAndExpandOnTheServerShouldReturnServerAsTheRoot()
{
var query = "";
string databaseName = "tempdb";
@@ -48,8 +48,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
});
}
[Fact]
public async void VerifyServerLogins()
[Test]
public async Task VerifyServerLogins()
{
var query = $@"If Exists (select loginname from master.dbo.syslogins
where name = 'OEServerLogin')
@@ -77,8 +77,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
});
}
[Fact]
public async void VerifyServerTriggers()
[Test]
public async Task VerifyServerTriggers()
{
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]
public async void CreateSessionAndExpandOnTheDatabaseShouldReturnDatabaseAsTheRoot()
[Test]
public async Task CreateSessionAndExpandOnTheDatabaseShouldReturnDatabaseAsTheRoot()
{
var query = "";
string databaseName = "#testDb#";
@@ -124,8 +124,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
});
}
[Fact]
public async void RefreshNodeShouldGetTheDataFromDatabase()
[Test]
public async Task RefreshNodeShouldGetTheDataFromDatabase()
{
var query = "Create table t1 (c1 int)";
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.
/// The expand should return an error that says database if offline
/// </summary>
[Fact]
public async void ExpandOfflineDatabaseShouldReturnError()
[Test]
public async Task ExpandOfflineDatabaseShouldReturnError()
{
var query = "ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE";
string databaseName = "master";
@@ -162,8 +162,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
});
}
[Fact]
public async void RefreshShouldCleanTheCache()
[Test]
public async Task RefreshShouldCleanTheCache()
{
string query = @"Create table t1 (c1 int)
GO
@@ -220,7 +220,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
var tableChildren = (await _service.ExpandNode(session, tablePath, true)).Nodes;
//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
rootChildrenCache = session.Root.GetChildren();
@@ -228,8 +228,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
Assert.True(tablesCache.Any());
}
[Fact]
public async void VerifyAllSqlObjects()
[Test]
public async Task VerifyAllSqlObjects()
{
var queryFileName = "AllSqlObjects.sql";
string baselineFileName = "AllSqlObjects.txt";
@@ -237,9 +237,9 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
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
public async void VerifySystemObjects()
public async Task VerifySystemObjects()
{
string queryFileName = null;
string baselineFileName = null;
@@ -299,19 +299,19 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
Assert.NotNull(session);
Assert.NotNull(session.Root);
NodeInfo nodeInfo = session.Root.ToNodeInfo();
Assert.Equal(nodeInfo.IsLeaf, false);
Assert.AreEqual(false, nodeInfo.IsLeaf);
NodeInfo databaseNode = null;
if (serverNode)
{
Assert.Equal(nodeInfo.NodeType, NodeTypes.Server.ToString());
Assert.AreEqual(nodeInfo.NodeType, NodeTypes.Server.ToString());
var children = session.Root.Expand(new CancellationToken());
//All server children should be folder nodes
foreach (var item in children)
{
Assert.Equal(item.NodeType, "Folder");
Assert.AreEqual("Folder", item.NodeType);
}
var databasesRoot = children.FirstOrDefault(x => x.NodeTypeId == NodeTypes.Databases);
@@ -331,7 +331,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
}
else
{
Assert.Equal(nodeInfo.NodeType, NodeTypes.Database.ToString());
Assert.AreEqual(nodeInfo.NodeType, NodeTypes.Database.ToString());
databaseNode = session.Root.ToNodeInfo();
Assert.True(databaseNode.Label.Contains(databaseName));
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.Root);
NodeInfo nodeInfo = session.Root.ToNodeInfo();
Assert.Equal(nodeInfo.IsLeaf, false);
Assert.Equal(nodeInfo.NodeType, NodeTypes.Database.ToString());
Assert.AreEqual(false, nodeInfo.IsLeaf);
Assert.AreEqual(nodeInfo.NodeType, NodeTypes.Database.ToString());
Assert.True(nodeInfo.Label.Contains(databaseName));
var children = (await _service.ExpandNode(session, session.Root.GetNodePath())).Nodes;
//All server children should be folder nodes
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);

View File

@@ -18,7 +18,7 @@ using Microsoft.SqlTools.ServiceLayer.Profiler;
using Microsoft.SqlTools.ServiceLayer.Profiler.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Profiler
{
@@ -27,7 +27,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Profiler
/// <summary>
/// Verify that a start profiling request starts a profiling session
/// </summary>
//[Fact]
//[Test]
public async Task TestHandleStartAndStopProfilingRequests()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -76,7 +76,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Profiler
/// <summary>
/// Verify the profiler service XEvent session factory
/// </summary>
//[Fact]
//[Test]
public void TestCreateXEventSession()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");

View File

@@ -8,7 +8,7 @@ using System.Data.Common;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataStorage
{
@@ -30,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt
/// <summary>
/// Validate GetBytesWithMaxCapacity
/// </summary>
[Fact]
[Test]
public void GetBytesWithMaxCapacityTest()
{
var storageReader = GetTestStorageDataReader(
@@ -47,7 +47,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt
/// <summary>
/// Validate GetCharsWithMaxCapacity
/// </summary>
[Fact]
[Test]
public void GetCharsWithMaxCapacityTest()
{
var storageReader = GetTestStorageDataReader(
@@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt
/// <summary>
/// Validate GetXmlWithMaxCapacity
/// </summary>
[Fact]
[Test]
public void GetXmlWithMaxCapacityTest()
{
var storageReader = GetTestStorageDataReader(
@@ -86,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt
/// <summary>
/// Validate StringWriterWithMaxCapacity Write test
/// </summary>
[Fact]
[Test]
public void StringWriterWithMaxCapacityTest()
{
var writer = new StorageDataReader.StringWriterWithMaxCapacity(null, 4);

View File

@@ -6,19 +6,20 @@
using System;
using System.Collections.Concurrent;
using System.Data.Common;
using System.Linq;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
{
public class ExecuteTests
{
[Fact]
[Test]
public void RollbackTransactionFailsWithoutBeginTransaction()
{
const string refactorText = "ROLLBACK TRANSACTION";
@@ -37,7 +38,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
Assert.True(query.Batches[0].HasError);
}
[Fact]
[Test]
public void TransactionsSucceedAcrossQueries()
{
const string beginText = "BEGIN TRANSACTION";
@@ -56,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
Assert.False(rollbackQuery.Batches[0].HasError);
}
[Fact]
[Test]
public void TempTablesPersistAcrossQueries()
{
const string createTempText = "CREATE TABLE #someTempTable (id int)";
@@ -75,7 +76,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
Assert.False(insertTempQuery.Batches[0].HasError);
}
[Fact]
[Test]
public void DatabaseChangesWhenCallingUseDatabase()
{
const string master = "master";
@@ -92,27 +93,15 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
// If I use master, the current database should be master
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
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
CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory);
Assert.Equal(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);
Assert.AreEqual(master, connInfo.ConnectionDetails.DatabaseName);
}
public static Query CreateAndExecuteQuery(string queryText, ConnectionInfo connectionInfo, IFileStreamFactory fileStreamFactory, bool IsSqlCmd = false)

View File

@@ -9,13 +9,13 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using System;
using System.IO;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
{
public class SqlCmdExecutionTest
{
[Fact]
[Test]
public void TestConnectSqlCmdCommand()
{
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -41,7 +41,7 @@ GO";
Assert.True(query.Batches[0].HasError, "Query should have error");
}
[Fact]
[Test]
public void TestOnErrorSqlCmdCommand()
{
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
@@ -73,7 +73,7 @@ GO";
Assert.False(query.Batches[1].HasExecuted, "last batch should NOT be executed");
}
[Fact]
[Test]
public void TestIncludeSqlCmdCommand()
{
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();

View File

@@ -12,7 +12,7 @@ using Moq;
using System;
using System.IO;
using System.Threading.Tasks;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SchemaCompare
{
@@ -265,8 +265,8 @@ END
{
// validate script generation failed because there were no differences
Assert.False(generateScriptOperation1.ScriptGenerationResult.Success);
Assert.Equal("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.", generateScriptOperation1.ScriptGenerationResult.Message);
Assert.AreEqual("Performing script generation is not possible for this comparison result.", ex.Message);
}
var schemaCompareParams2 = new SchemaCompareParams
@@ -309,8 +309,8 @@ END
/// <summary>
/// Verify the schema compare request comparing two dacpacs with and without ignore column option
/// </summary>
[Fact]
public async void SchemaCompareDacpacToDacpacOptions()
[Test]
public async Task SchemaCompareDacpacToDacpacOptions()
{
await SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions());
}
@@ -318,8 +318,8 @@ END
/// <summary>
/// Verify the schema compare request comparing two dacpacs with and excluding table valued functions
/// </summary>
[Fact]
public async void SchemaCompareDacpacToDacpacObjectTypes()
[Test]
public async Task SchemaCompareDacpacToDacpacObjectTypes()
{
await SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions());
}
@@ -327,8 +327,8 @@ END
/// <summary>
/// Verify the schema compare request comparing two databases with and without ignore column option
/// </summary>
[Fact]
public async void SchemaCompareDatabaseToDatabaseOptions()
[Test]
public async Task SchemaCompareDatabaseToDatabaseOptions()
{
await SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions());
}
@@ -336,8 +336,8 @@ END
/// <summary>
/// Verify the schema compare request comparing two databases with and excluding table valued functions
/// </summary>
[Fact]
public async void SchemaCompareDatabaseToDatabaseObjectTypes()
[Test]
public async Task SchemaCompareDatabaseToDatabaseObjectTypes()
{
await SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions());
}
@@ -345,8 +345,8 @@ END
/// <summary>
/// Verify the schema compare script generation comparing dacpac and db with and without ignore column option
/// </summary>
[Fact]
public async void SchemaCompareGenerateScriptDacpacToDatabaseOptions()
[Test]
public async Task SchemaCompareGenerateScriptDacpacToDatabaseOptions()
{
await SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabaseWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions());
}
@@ -354,8 +354,8 @@ END
/// <summary>
/// Verify the schema compare script generation comparing dacpac and db with and excluding table valued function
/// </summary>
[Fact]
public async void SchemaCompareGenerateScriptDacpacToDatabaseObjectTypes()
[Test]
public async Task SchemaCompareGenerateScriptDacpacToDatabaseObjectTypes()
{
await SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabaseWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions());
}
@@ -363,7 +363,7 @@ END
/// <summary>
/// Verify the schema compare default creation test
/// </summary>
[Fact]
[Test]
public void ValidateSchemaCompareOptionsDefaultAgainstDacFx()
{
DeploymentOptions deployOptions = new DeploymentOptions();
@@ -384,8 +384,8 @@ END
/// <summary>
/// Verify the schema compare default creation test
/// </summary>
[Fact]
public async void ValidateSchemaCompareGetDefaultOptionsCallFromService()
[Test]
public async Task ValidateSchemaCompareGetDefaultOptionsCallFromService()
{
DeploymentOptions deployOptions = new DeploymentOptions();
var schemaCompareRequestContext = new Mock<RequestContext<SchemaCompareOptionsResult>>();

View File

@@ -16,8 +16,9 @@ using Microsoft.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using NUnit.Framework;
using System.Diagnostics;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SchemaCompare
{
public class SchemaCompareServiceTests
@@ -78,8 +79,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare request comparing two dacpacs
/// </summary>
[Fact]
public async void SchemaCompareDacpacToDacpac()
[Test]
public async Task SchemaCompareDacpacToDacpac()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
@@ -122,8 +123,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare request comparing a two databases
/// </summary>
[Fact]
public async void SchemaCompareDatabaseToDatabase()
[Test]
public async Task SchemaCompareDatabaseToDatabase()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -161,8 +162,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare request comparing a database to a dacpac
/// </summary>
[Fact]
public async void SchemaCompareDatabaseToDacpac()
[Test]
public async Task SchemaCompareDatabaseToDacpac()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -202,8 +203,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare generate script request comparing a database to a database
/// </summary>
[Fact]
public async void SchemaCompareGenerateScriptDatabaseToDatabase()
[Test]
public async Task SchemaCompareGenerateScriptDatabaseToDatabase()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
var schemaCompareRequestContext = new Mock<RequestContext<SchemaCompareResult>>();
@@ -249,8 +250,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare generate script request comparing a dacpac to a database
/// </summary>
[Fact]
public async void SchemaCompareGenerateScriptDacpacToDatabase()
[Test]
public async Task SchemaCompareGenerateScriptDacpacToDatabase()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -300,8 +301,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare publish changes request comparing a dacpac to a database
/// </summary>
[Fact]
public async void SchemaComparePublishChangesDacpacToDatabase()
[Test]
public async Task SchemaComparePublishChangesDacpacToDatabase()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -349,14 +350,14 @@ WITH VALUES
SchemaComparePublishChangesOperation publishChangesOperation = new SchemaComparePublishChangesOperation(publishChangesParams, schemaCompareOperation.ComparisonResult);
publishChangesOperation.Execute(TaskExecutionMode.Execute);
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
schemaCompareOperation.Execute(TaskExecutionMode.Execute);
Assert.True(schemaCompareOperation.ComparisonResult.IsValid);
Assert.True(schemaCompareOperation.ComparisonResult.IsEqual);
Assert.Empty(schemaCompareOperation.ComparisonResult.Differences);
Assert.That(schemaCompareOperation.ComparisonResult.Differences, Is.Empty);
// cleanup
SchemaCompareTestUtils.VerifyAndCleanup(sourceDacpacFilePath);
@@ -371,8 +372,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare publish changes request comparing a database to a database
/// </summary>
[Fact]
public async void SchemaComparePublishChangesDatabaseToDatabase()
[Test]
public async Task SchemaComparePublishChangesDatabaseToDatabase()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -416,14 +417,14 @@ WITH VALUES
SchemaComparePublishChangesOperation publishChangesOperation = new SchemaComparePublishChangesOperation(publishChangesParams, schemaCompareOperation.ComparisonResult);
publishChangesOperation.Execute(TaskExecutionMode.Execute);
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
schemaCompareOperation.Execute(TaskExecutionMode.Execute);
Assert.True(schemaCompareOperation.ComparisonResult.IsValid);
Assert.True(schemaCompareOperation.ComparisonResult.IsEqual);
Assert.Empty(schemaCompareOperation.ComparisonResult.Differences);
Assert.That(schemaCompareOperation.ComparisonResult.Differences, Is.Empty);
}
finally
{
@@ -435,8 +436,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare Scmp File Save for database endpoints
/// </summary>
[Fact]
public async void SchemaCompareSaveScmpFileForDatabases()
[Test]
public async Task SchemaCompareSaveScmpFileForDatabases()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
@@ -465,8 +466,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare Scmp File Save for dacpac endpoints
/// </summary>
[Fact]
public async void SchemaCompareSaveScmpFileForDacpacs()
[Test]
public async Task SchemaCompareSaveScmpFileForDacpacs()
{
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget");
@@ -497,8 +498,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare Scmp File Save for dacpac and db endpoints combination
/// </summary>
[Fact]
public async void SchemaCompareSaveScmpFileForDacpacToDB()
[Test]
public async Task SchemaCompareSaveScmpFileForDacpacToDB()
{
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget");
@@ -528,8 +529,8 @@ WITH VALUES
/// <summary>
/// Verify opening an scmp comparing two databases
/// </summary>
[Fact]
public async void SchemaCompareOpenScmpDatabaseToDatabaseRequest()
[Test]
public async Task SchemaCompareOpenScmpDatabaseToDatabaseRequest()
{
await CreateAndOpenScmp(SchemaCompareEndpointType.Database, SchemaCompareEndpointType.Database);
}
@@ -537,8 +538,8 @@ WITH VALUES
/// <summary>
/// Verify opening an scmp comparing a dacpac and database
/// </summary>
[Fact]
public async void SchemaCompareOpenScmpDacpacToDatabaseRequest()
[Test]
public async Task SchemaCompareOpenScmpDacpacToDatabaseRequest()
{
await CreateAndOpenScmp(SchemaCompareEndpointType.Dacpac, SchemaCompareEndpointType.Database);
}
@@ -546,8 +547,8 @@ WITH VALUES
/// <summary>
/// Verify opening an scmp comparing two dacpacs
/// </summary>
[Fact]
public async void SchemaCompareOpenScmpDacpacToDacpacRequest()
[Test]
public async Task SchemaCompareOpenScmpDacpacToDacpacRequest()
{
await CreateAndOpenScmp(SchemaCompareEndpointType.Dacpac, SchemaCompareEndpointType.Dacpac);
}
@@ -555,7 +556,7 @@ WITH VALUES
/// <summary>
/// Verify the schema compare Service Calls ends to end
/// </summary>
[Fact]
[Test]
public async Task VerifySchemaCompareServiceCalls()
{
string operationId = Guid.NewGuid().ToString();
@@ -695,8 +696,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare cancel
/// </summary>
[Fact]
public async void SchemaCompareCancelCompareOperation()
[Test]
public async Task SchemaCompareCancelCompareOperation()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");
@@ -746,8 +747,8 @@ WITH VALUES
/// test to verify recent dacfx bugs
/// does not need all combinations of db and dacpacs
/// </summary>
//[Fact] disabling the failing test is failing now.
public async void SchemaCompareCEKAndFilegoupTest()
//[Test] disabling the failing test is failing now.
public async Task SchemaCompareCEKAndFilegoupTest()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, CreateKey, "SchemaCompareSource");
@@ -819,8 +820,8 @@ WITH VALUES
/// <summary>
/// Verify the schema compare request with failing exclude request because of dependencies and that include will include dependencies
/// </summary>
[Fact]
public async void SchemaCompareIncludeExcludeWithDependencies()
[Test]
public async Task SchemaCompareIncludeExcludeWithDependencies()
{
var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
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
SchemaComparison compare = new SchemaComparison(sourceEndpoint, targetEndpoint);
SchemaComparisonResult result = compare.Compare();
Assert.NotEmpty(result.Differences);
Assert.That(result.Differences, Is.Not.Empty);
SchemaDifference difference = result.Differences.First();
if (difference.SourceObject != null)
{
@@ -1059,10 +1060,10 @@ WITH VALUES
Assert.NotNull(schemaCompareOpenScmpOperation.Result);
Assert.True(schemaCompareOpenScmpOperation.Result.Success);
Assert.NotEmpty(schemaCompareOpenScmpOperation.Result.ExcludedSourceElements);
Assert.Equal(1, schemaCompareOpenScmpOperation.Result.ExcludedSourceElements.Count());
Assert.Empty(schemaCompareOpenScmpOperation.Result.ExcludedTargetElements);
Assert.Equal(targetDb.DatabaseName, schemaCompareOpenScmpOperation.Result.OriginalTargetName);
Assert.That(schemaCompareOpenScmpOperation.Result.ExcludedSourceElements, Is.Not.Empty);
Assert.AreEqual(1, schemaCompareOpenScmpOperation.Result.ExcludedSourceElements.Count());
Assert.That(schemaCompareOpenScmpOperation.Result.ExcludedTargetElements, Is.Empty);
Assert.AreEqual(targetDb.DatabaseName, schemaCompareOpenScmpOperation.Result.OriginalTargetName);
ValidateResultEndpointInfo(sourceEndpoint, schemaCompareOpenScmpOperation.Result.SourceEndpointInfo, sourceDb.ConnectionString);
ValidateResultEndpointInfo(targetEndpoint, schemaCompareOpenScmpOperation.Result.TargetEndpointInfo, targetDb.ConnectionString);
@@ -1093,13 +1094,13 @@ WITH VALUES
if (resultEndpoint.EndpointType == SchemaCompareEndpointType.Dacpac)
{
SchemaCompareDacpacEndpoint dacpacEndpoint = originalEndpoint as SchemaCompareDacpacEndpoint;
Assert.Equal(dacpacEndpoint.FilePath, resultEndpoint.PackageFilePath);
Assert.AreEqual(dacpacEndpoint.FilePath, resultEndpoint.PackageFilePath);
}
else
{
SchemaCompareDatabaseEndpoint databaseEndpoint = originalEndpoint as SchemaCompareDatabaseEndpoint;
Assert.Equal(databaseEndpoint.DatabaseName, resultEndpoint.DatabaseName);
Assert.Contains(resultEndpoint.ConnectionDetails.ConnectionString, connectionString); // connectionString has password but resultEndpoint doesn't
Assert.AreEqual(databaseEndpoint.DatabaseName, resultEndpoint.DatabaseName);
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)
{
Assert.Equal(dacfxObject.Name.Parts.Count, diffObjectName.Length);
Assert.AreEqual(dacfxObject.Name.Parts.Count, diffObjectName.Length);
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 excludedObject = new SchemaComparisonExcludedObjectId(diffObjectTypeType, new ObjectIdentifier(diffObjectName));
Assert.Equal(dacFxExcludedObject.Identifier.ToString(), excludedObject.Identifier.ToString());
Assert.Equal(dacFxExcludedObject.TypeName, excludedObject.TypeName);
Assert.AreEqual(dacFxExcludedObject.Identifier.ToString(), excludedObject.Identifier.ToString());
Assert.AreEqual(dacFxExcludedObject.TypeName, excludedObject.TypeName);
string dacFxType = dacFxExcludedObject.TypeName;
Assert.Equal(dacFxType, diffObjectTypeType);
Assert.AreEqual(dacFxType, diffObjectTypeType);
}
private void CreateAndValidateScmpFile(SchemaCompareEndpointInfo sourceInfo, SchemaCompareEndpointInfo targetInfo, bool isSourceDb, bool isTargetDb)
@@ -1236,7 +1237,8 @@ WITH VALUES
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");
while (TaskService.Instance.TaskManager.Tasks.Any() && retry > 0)
{
@@ -1259,6 +1261,7 @@ WITH VALUES
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))}]");
Console.WriteLine($"ValidateTask{expectedTaskName} completed at retry = {retry}");
TaskService.Instance.TaskManager.Reset();
}
}

View File

@@ -15,7 +15,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
@@ -76,8 +76,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
/// <summary>
/// Verify the script object request
/// </summary>
[Fact]
public async void ScriptingScript()
[Test]
public async Task ScriptingScript()
{
foreach (string obj in objects)
{
@@ -86,8 +86,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
}
}
[Fact]
public async void VerifyScriptAsCreateTable()
[Test]
public async Task VerifyScriptAsCreateTable()
{
string query = @"CREATE TABLE testTable1 (c1 int)
GO
@@ -110,8 +110,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAsForMultipleObjects(query, new List<ScriptingObject> { scriptingObject }, scriptCreateDrop, expectedScripts);
}
[Fact]
public async void VerifyScriptAsExecuteTableFailes()
[Test]
public async Task VerifyScriptAsExecuteTableFailes()
{
string query = "CREATE TABLE testTable1 (c1 int)";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Execute;
@@ -125,8 +125,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
}
[Fact]
public async void VerifyScriptAsAlter()
[Test]
public async Task VerifyScriptAsAlter()
{
string query = @"CREATE PROCEDURE testSp1 @StartProductID [int] AS BEGIN Select * from sys.all_columns END
GO
@@ -168,8 +168,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
}
// TODO: Fix flaky test. See https://github.com/Microsoft/sqltoolsservice/issues/631
// [Fact]
public async void VerifyScriptAsExecuteStoredProcedure()
// [Test]
public async Task VerifyScriptAsExecuteStoredProcedure()
{
string query = @"CREATE PROCEDURE testSp1
@BusinessEntityID [int],
@@ -192,8 +192,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
}
[Fact]
public async void VerifyScriptAsSelectTable()
[Test]
public async Task VerifyScriptAsSelectTable()
{
string query = "CREATE TABLE testTable1 (c1 int)";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Select;
@@ -208,8 +208,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
}
[Fact]
public async void VerifyScriptAsCreateView()
[Test]
public async Task VerifyScriptAsCreateView()
{
string query = "CREATE VIEW testView1 AS SELECT * from sys.all_columns";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Create;
@@ -224,8 +224,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
}
[Fact]
public async void VerifyScriptAsCreateStoredProcedure()
[Test]
public async Task VerifyScriptAsCreateStoredProcedure()
{
string query = "CREATE PROCEDURE testSp1 AS BEGIN Select * from sys.all_columns END";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Create;
@@ -240,8 +240,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
}
[Fact]
public async void VerifyScriptAsDropTable()
[Test]
public async Task VerifyScriptAsDropTable()
{
string query = "CREATE TABLE testTable1 (c1 int)";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Delete;
@@ -256,8 +256,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
}
[Fact]
public async void VerifyScriptAsDropView()
[Test]
public async Task VerifyScriptAsDropView()
{
string query = "CREATE VIEW testView1 AS SELECT * from sys.all_columns";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Delete;
@@ -272,8 +272,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Scripting
await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript);
}
[Fact]
public async void VerifyScriptAsDropStoredProcedure()
[Test]
public async Task VerifyScriptAsDropStoredProcedure()
{
string query = "CREATE PROCEDURE testSp1 AS BEGIN Select * from sys.all_columns END";
ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Delete;

View File

@@ -14,7 +14,7 @@ using Microsoft.SqlTools.ServiceLayer.Security.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Moq;
using Xunit;
using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security
@@ -27,7 +27,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security
/// <summary>
/// TestHandleCreateCredentialRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleCreateCredentialRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -49,7 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security
/// <summary>
/// TestHandleUpdateCredentialRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleUpdateCredentialRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security
/// <summary>
/// TestHandleDeleteCredentialRequest
/// </summary>
[Fact]
[Test]
public async Task TestHandleDeleteCredentialRequest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())

View File

@@ -13,22 +13,22 @@ using Moq;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServices
{
public class ServerConfigurationsServiceTests
{
[Fact]
public async void VerifyListingConfigs()
[Test]
public async Task VerifyListingConfigs()
{
List<ServerConfigProperty> configs = await GetAllConfigs();
Assert.NotNull(configs);
Assert.True(configs.Count > 0);
}
[Fact]
public async void VerifyUpdatingConfigs()
[Test]
public async Task VerifyUpdatingConfigs()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
@@ -59,14 +59,14 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServic
await ServerConfigService.Instance.HandleServerConfigViewRequest(requestParams, requestContext.Object);
Assert.NotNull(result);
Assert.Equal(result.ConfigProperty.ConfigValue, sampleConfig.ConfigValue);
Assert.AreEqual(result.ConfigProperty.ConfigValue, sampleConfig.ConfigValue);
await ServerConfigService.Instance.HandleServerConfigUpdateRequest(updateRequestParams, updateRequestContext.Object);
Assert.NotNull(updateResult);
Assert.Equal(updateResult.ConfigProperty.ConfigValue, newValue);
Assert.AreEqual(updateResult.ConfigProperty.ConfigValue, newValue);
updateRequestParams.ConfigValue = sampleConfig.ConfigValue;
await ServerConfigService.Instance.HandleServerConfigUpdateRequest(updateRequestParams, updateRequestContext.Object);
Assert.NotNull(updateResult);
Assert.Equal(updateResult.ConfigProperty.ConfigValue, sampleConfig.ConfigValue);
Assert.AreEqual(updateResult.ConfigProperty.ConfigValue, sampleConfig.ConfigValue);
ServerConfigService.Instance.ConnectionServiceInstance.Disconnect(new DisconnectParams
{
OwnerUri = queryTempFile.FilePath,
@@ -97,8 +97,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServic
}
[Fact]
public async void VerifyConfigViewRequestSendErrorGivenInvalidConnection()
[Test]
public async Task VerifyConfigViewRequestSendErrorGivenInvalidConnection()
{
ServerConfigViewResponseParams result = 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>()));
}
[Fact]
public async void VerifyConfigUpdateRequestSendErrorGivenInvalidConnection()
[Test]
public async Task VerifyConfigUpdateRequestSendErrorGivenInvalidConnection()
{
ServerConfigUpdateResponseParams result = 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>()));
}
[Fact]
public async void VerifyConfigListRequestSendErrorGivenInvalidConnection()
[Test]
public async Task VerifyConfigListRequestSendErrorGivenInvalidConnection()
{
ServerConfigListResponseParams result = null;
var requestContext = RequestContextMocks.Create<ServerConfigListResponseParams>(r => result = r).AddErrorHandling(null);

View File

@@ -20,8 +20,6 @@ using Microsoft.SqlTools.ServiceLayer.SqlAssessment;
using Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using NUnit.Framework;
using Xunit;
using Assert = Xunit.Assert;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
{
@@ -31,8 +29,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
private static readonly string[] AllowedSeverityLevels = { "Information", "Warning", "Critical" };
[Fact]
public async void InvokeSqlAssessmentServerTest()
[Test]
public async Task InvokeSqlAssessmentServerTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -46,23 +44,19 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
SqlObjectType.Server,
liveConnection);
Assert.All(
response.Items,
i =>
{
Assert.NotNull(i.Message);
Assert.NotEmpty(i.Message);
Assert.Equal(serverInfo.ServerName, i.TargetName);
if (i.Kind == 0)
{
AssertInfoPresent(i);
}
});
Assert.Multiple(() =>
{
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));
foreach (var i in response.Items.Where(i => i.Kind == 0))
{
AssertInfoPresent(i);
}
});
}
[Fact]
public async void GetAssessmentItemsServerTest()
[Test]
public async Task GetAssessmentItemsServerTest()
{
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
@@ -76,17 +70,18 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
SqlObjectType.Server,
liveConnection);
Assert.All(
response.Items,
i =>
Assert.Multiple(() =>
{
Assert.That(response.Items.Select(i => i.TargetName), Has.All.EqualTo(serverInfo.ServerName));
foreach (var i in response.Items)
{
AssertInfoPresent(i);
Assert.Equal(serverInfo.ServerName, i.TargetName);
});
}
});
}
[Fact]
public async void GetAssessmentItemsDatabaseTest()
[Test]
public async Task GetAssessmentItemsDatabaseTest()
{
const string DatabaseName = "tempdb";
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName);
@@ -95,17 +90,18 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
SqlObjectType.Database,
liveConnection);
Assert.All(
response.Items,
i =>
Assert.Multiple(() =>
{
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);
});
}
});
}
[Fact]
public async void InvokeSqlAssessmentIDatabaseTest()
[Test]
public async Task InvokeSqlAssessmentIDatabaseTest()
{
const string DatabaseName = "tempdb";
var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName);
@@ -114,19 +110,15 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
SqlObjectType.Database,
liveConnection);
Assert.All(
response.Items,
i =>
Assert.Multiple(() =>
{
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);
Assert.NotNull(i.Message);
Assert.NotEmpty(i.Message);
if (i.Kind == 0)
{
AssertInfoPresent(i);
}
});
AssertInfoPresent(i);
}
});
}
private static async Task<AssessmentResult<TResult>> CallAssessment<TResult>(
@@ -176,13 +168,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
Assert.NotNull(response);
if (response.Success)
{
Assert.All(
response.Items,
i =>
{
Assert.Equal(sqlObjectType, i.TargetType);
Assert.Contains(i.Level, AllowedSeverityLevels);
});
Assert.That(response.Items.Select(i => i.TargetType), Has.All.EqualTo(sqlObjectType));
Assert.That(response.Items.Select(i => i.Level), Has.All.AnyOf(AllowedSeverityLevels));
}
return response;
@@ -225,17 +212,13 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.SqlAssessment
private void AssertInfoPresent(AssessmentItemInfo item)
{
Assert.NotNull(item.CheckId);
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.Multiple(() =>
{
Assert.NotNull(t);
Assert.NotEmpty(t);
Assert.That(item.CheckId, Is.Not.Null.Or.Empty);
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);
});
}
}

View File

@@ -20,7 +20,7 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Moq;
using Xunit;
using NUnit.Framework;
using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnectionHelper;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.TaskServices
@@ -37,25 +37,25 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.TaskServices
service.InitializeService(serviceHostMock.Object);
}
[Fact]
[Test]
public async Task VerifyTaskExecuteTheQueryGivenExecutionModeExecute()
{
await VerifyTaskWithExecutionMode(TaskExecutionMode.Execute);
}
[Fact]
[Test]
public async Task VerifyTaskGenerateScriptOnlyGivenExecutionModeScript()
{
await VerifyTaskWithExecutionMode(TaskExecutionMode.Script);
}
[Fact]
[Test]
public async Task VerifyTaskNotExecuteAndGenerateScriptGivenExecutionModeExecuteAndScript()
{
await VerifyTaskWithExecutionMode(TaskExecutionMode.ExecuteAndScript);
}
[Fact]
[Test]
public async Task VerifyTaskSendsFailureNotificationGivenInvalidQuery()
{
await VerifyTaskWithExecutionMode(TaskExecutionMode.ExecuteAndScript, true);
@@ -103,7 +103,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.TaskServices
bool expected = executionMode == TaskExecutionMode.Execute || executionMode == TaskExecutionMode.ExecuteAndScript;
Server serverToverfiy = CreateServerObject(connectionResult.ConnectionInfo);
bool actual = serverToverfiy.Databases[testDb.DatabaseName].Tables.Contains(taskOperation.TableName, "test");
Assert.Equal(expected, actual);
Assert.AreEqual(expected, actual);
}
else
{

View File

@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility
{

View File

@@ -7,7 +7,7 @@ using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common.Baselined
{

View File

@@ -10,8 +10,9 @@
<ItemGroup>
<PackageReference Include="Moq" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="nunit" />
<PackageReference Include="nunit3testadapter" />
<PackageReference Include="nunit.console" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Scripts/CreateTestDatabaseObjects.sql" />

View File

@@ -11,7 +11,7 @@ using Microsoft.SqlTools.Hosting.Contracts;
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Moq;
using Xunit;
using NUnit.Framework;
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
return AddSimpleErrorValidation((msg, code) =>
{
Assert.NotEmpty(msg);
Assert.That(msg, Is.Not.Null.Or.Empty, $"AddStandardErrorValidation msg for {code}");
});
}

View File

@@ -7,7 +7,7 @@ using System;
using System.Globalization;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Xunit;
using NUnit.Framework;
using Microsoft.Data.SqlClient;
using System.Threading.Tasks;
using Microsoft.SqlServer.Management.Common;

View File

@@ -8,7 +8,7 @@ using System.Collections.Generic;
using System.Globalization;
using Microsoft.SqlTools.Credentials.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{

View File

@@ -9,7 +9,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{

View File

@@ -18,7 +18,7 @@ using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.TestDriver.Driver;
using Microsoft.SqlTools.ServiceLayer.TestDriver.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{

View File

@@ -16,7 +16,7 @@ using Microsoft.SqlTools.ServiceLayer.ObjectExplorer;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{

View File

@@ -6,11 +6,12 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using NUnit.Framework;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{
[TestFixture]
/// <summary>
/// Language Service end-to-end integration tests
/// </summary>
@@ -19,16 +20,16 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary>
/// Try to connect with invalid credentials
/// </summary>
[Fact]
[Test]
public async Task InvalidConnection()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
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");
await testService.Connect(queryTempFile.FilePath, InvalidConnectParams, 300000);
await testService.Connect(queryTempFile.FilePath, InvalidConnectParams, 60000);
Thread.Sleep(1000);
@@ -41,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary>
/// Validate list databases request
/// </summary>
[Fact]
[Test]
public async Task ListDatabasesTest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())

View File

@@ -10,10 +10,11 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{
[TestFixture]
/// <summary>
/// Language Service end-to-end integration tests
/// </summary>
@@ -23,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary>
/// Validate hover tooltip scenarios
/// </summary>
[Fact]
[Test]
public async Task HoverTest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -64,7 +65,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary>
/// Validation autocompletion suggestions scenarios
/// </summary>
[Fact]
[Test]
public async Task CompletionTest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -111,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary>
/// Validate diagnostic scenarios
/// </summary>
[Fact]
[Test]
public async Task DiagnosticsTests()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -214,7 +215,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// Peek Definition/ Go to definition
/// </summary>
/// <returns></returns>
[Fact]
[Test]
public async Task DefinitionTest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -260,7 +261,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary>
/// Validate the configuration change event
/// </summary>
[Fact]
[Test]
public async Task ChangeConfigurationTest()
{
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
@@ -286,7 +287,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
}
}
[Fact]
[Test]
public async Task NotificationIsSentAfterOnConnectionAutoCompleteUpdate()
{
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
var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000);
Assert.NotNull(readyParams);
Assert.Equal(queryTempFile.FilePath, readyParams.OwnerUri);
Assert.AreEqual(queryTempFile.FilePath, readyParams.OwnerUri);
await testService.Disconnect(queryTempFile.FilePath);
}
}
[Fact]
[Test]
public async Task FunctionSignatureCompletionReturnsEmptySignatureHelpObjectWhenThereAreNoMatches()
{
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
var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000);
Assert.NotNull(readyParams);
Assert.Equal(ownerUri, readyParams.OwnerUri);
Assert.AreEqual(ownerUri, readyParams.OwnerUri);
// Send a function signature help Request
var position = new TextDocumentPosition()
@@ -346,7 +347,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
}
}
[Fact]
[Test]
public async Task FunctionSignatureCompletionReturnsCorrectFunction()
{
string sqlText = "EXEC sys.fn_isrolemember ";
@@ -362,7 +363,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
// Wait for intellisense to be ready
var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000);
Assert.NotNull(readyParams);
Assert.Equal(ownerUri, readyParams.OwnerUri);
Assert.AreEqual(ownerUri, readyParams.OwnerUri);
// Send a function signature help Request
var position = new TextDocumentPosition()
@@ -381,18 +382,17 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
Assert.NotNull(signatureHelp);
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;
Assert.NotNull(label);
Assert.NotEmpty(label);
Assert.True(label.Contains("fn_isrolemember"));
Assert.That(label, Is.Not.Null.Or.Empty, "label");
Assert.That(label, Contains.Substring("fn_isrolemember"), "label contents");
await testService.Disconnect(ownerUri);
}
}
[Fact]
[Test]
public async Task FunctionSignatureCompletionReturnsCorrectParametersAtEachPosition()
{
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
var readyParams = await testService.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000);
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 (,)
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.ActiveSignature);
Assert.True(signatureHelp.ActiveSignature.HasValue);
Assert.NotEmpty(signatureHelp.Signatures);
Assert.That(signatureHelp.Signatures, Is.Not.Empty, "Signatures");
var activeSignature = signatureHelp.Signatures[signatureHelp.ActiveSignature.Value];
Assert.NotNull(activeSignature);
var label = activeSignature.Label;
Assert.NotNull(label);
Assert.NotEmpty(label);
Assert.True(label.Contains(expectedFunctionName));
Assert.That(label, Is.Not.Null.Or.Empty, "label");
Assert.That(label, Contains.Substring(expectedFunctionName), "label contents");
Assert.NotNull(signatureHelp.ActiveParameter);
Assert.True(signatureHelp.ActiveParameter.HasValue);
Assert.Equal(expectedParameterIndex, signatureHelp.ActiveParameter.Value);
Assert.AreEqual(expectedParameterIndex, signatureHelp.ActiveParameter.Value);
var parameter = activeSignature.Parameters[signatureHelp.ActiveParameter.Value];
Assert.NotNull(parameter);
Assert.NotNull(parameter.Label);
Assert.NotEmpty(parameter.Label);
Assert.Equal(expectedParameterName, parameter.Label);
Assert.That(parameter.Label, Is.Not.Null.Or.Empty, "parameter.Label");
Assert.AreEqual(expectedParameterName, parameter.Label);
}
}
}

View File

@@ -21,8 +21,9 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="nunit" />
<PackageReference Include="nunit.console" />
<PackageReference Include="nunit3testadapter"/>
</ItemGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />

View File

@@ -9,9 +9,9 @@ using System.Reflection;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.TestDriver.Driver;
using Microsoft.SqlTools.Utility;
using Xunit;
using NUnit.Framework;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
[assembly: NonParallelizable]
// turn off entry point since this is xUnit project
#if false

View File

@@ -5,14 +5,14 @@
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{
public class QueryExecutionTests
{
/* Commenting out these tests until they are fixed (12/1/16)
[Fact]
[Test]
public async Task TestQueryCancelReliability()
{
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()
{
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()
{
const int queryCount = 10;
@@ -102,7 +102,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
}
}
[Fact]
[Test]
public async Task TestSaveResultsDoesNotBlockOtherRequests()
{
const string query = "SELECT * FROM sys.objects";
@@ -146,7 +146,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
}
}
[Fact]
[Test]
public async Task TestQueryingSubsetDoesNotBlockOtherRequests()
{
const string query = "SELECT * FROM sys.objects";
@@ -183,7 +183,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
}
}
[Fact]
[Test]
public async Task TestCancelQueryWhileOtherOperationsAreInProgress()
{
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()
{
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()
{
const string query = "SELECT * FROM sys.objects";

View File

@@ -6,28 +6,31 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Scripting.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{
[TestFixture]
/// <summary>
/// Scripting service end-to-end integration tests that use the SqlScriptPublishModel type to generate scripts.
/// </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()
{
using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -40,11 +43,11 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingListObjectsResult result = await testService.ListScriptingObjects(requestParams);
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()
{
using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -65,7 +68,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
}
}
[Fact]
[Test]
public async Task ScriptDatabaseSchemaAndData()
{
using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -86,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
}
}
[Fact]
[Test]
public async Task ScriptTable()
{
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));
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30));
Assert.True(parameters.Success);
Assert.Equal<int>(1, planEvent.Count);
Assert.AreEqual(1, planEvent.Count);
}
}
[Fact]
[Test]
public async Task ScriptTableUsingIncludeFilter()
{
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));
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30));
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()
{
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));
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30));
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()
{
using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -211,13 +218,13 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingResult result = await testService.Script(requestParams);
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(15));
Assert.True(parameters.HasError);
Assert.True(parameters.ErrorMessage.Contains("An error occurred while scripting the objects."));
Assert.Contains("The Table '[dbo].[TableDoesNotExist]' does not exist on the server.", parameters.ErrorDetails);
Assert.That(parameters.ErrorMessage, Contains.Substring("An error occurred while scripting the objects."), "parameters.ErrorMessage");
Assert.That(parameters.ErrorDetails, Contains.Substring("The Table '[dbo].[TableDoesNotExist]' does not exist on the server."), "parameters.ErrorDetails");
}
}
[Fact]
public async void ScriptSchemaCancel()
[Test]
public async Task ScriptSchemaCancel()
{
using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
{
@@ -232,15 +239,15 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
};
var result = Task.Run(() => testService.Script(requestParams));
ScriptingProgressNotificationParams progressParams = await testService.Driver.WaitForEvent(ScriptingProgressNotificationEvent.Type, TimeSpan.FromSeconds(10));
Task.Run(() => testService.CancelScript(progressParams.OperationId).Wait());
ScriptingProgressNotificationParams progressParams = await testService.Driver.WaitForEvent(ScriptingProgressNotificationEvent.Type, TimeSpan.FromSeconds(60));
await Task.Run(() => testService.CancelScript(progressParams.OperationId));
ScriptingCompleteParams cancelEvent = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(10));
Assert.True(cancelEvent.Canceled);
}
}
[Fact]
[Test]
public async Task ScriptSchemaInvalidConnectionString()
{
using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -258,11 +265,11 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingResult result = await testService.Script(requestParams);
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(10));
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()
{
using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -280,11 +287,11 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptingResult result = await testService.Script(requestParams);
ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(10));
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()
{
using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
@@ -359,7 +366,6 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
}
}
public void Dispose() { }
public class ScriptingFixture : IDisposable
{

View File

@@ -5,21 +5,23 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
using NUnit.Framework;
using Range = Microsoft.SqlTools.ServiceLayer.Workspace.Contracts.Range;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{
[TestFixture]
public class StressTests
{
/// <summary>
/// Simulate typing by a user to stress test the language service
/// </summary>
//[Fact]
//[Test]
public async Task TestLanguageService()
{
const string textToType = "SELECT * FROM sys.objects GO " +
@@ -144,7 +146,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary>
/// Repeatedly execute queries to stress test the query execution service.
/// </summary>
//[Fact]
//[Test]
public async Task TestQueryExecutionService()
{
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);
Assert.NotNull(queryResult);
Assert.NotNull(queryResult.BatchSummaries);
Assert.NotEmpty(queryResult.BatchSummaries);
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.That(queryResult.BatchSummaries, Is.Not.Null, "queryResult.BatchSummaries");
Assert.That(queryResult.BatchSummaries.Select(b => b.ResultSetSummaries), Has.Exactly(4).Not.Null, "ResultSetSummaries in the queryResult");
Assert.NotNull(await testService.ExecuteSubset(queryTempFile.FilePath, 0, 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>
/// Repeatedly connect and disconnect to stress test the connection service.
/// </summary>
//[Fact]
//[Test]
public async Task TestConnectionService()
{
string ownerUri = "file:///my/test/file.sql";

View File

@@ -7,10 +7,11 @@ using System.IO;
using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{
[TestFixture]
/// <summary>
/// Language Service end-to-end integration tests
/// </summary>
@@ -19,7 +20,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
/// <summary>
/// Validate workspace lifecycle events
/// </summary>
[Fact]
[Test]
public async Task InitializeRequestTest()
{
using (TestServiceDriverProvider testService = new TestServiceDriverProvider())

View File

@@ -49,9 +49,14 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Driver
string serviceHostArguments = "--enable-logging";
if (string.IsNullOrWhiteSpace(serviceHostExecutable))
{
// Include a fallback value to for running tests within visual studio
serviceHostExecutable =
@"..\..\..\..\..\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);

View File

@@ -9,8 +9,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../src/Microsoft.SqlTools.Hosting/Microsoft.SqlTools.Hosting.csproj" />

View File

@@ -4,13 +4,7 @@
//
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
using Xunit.Sdk;
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)
{
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
{
if (methodInfo == null)
{
Console.WriteLine("Invalid method name");
}
else
{
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));
}
{
throw new NotImplementedException("This code needs to change to use 'dotnet test' or nunit directly");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return await Task.FromResult(-1);
}
}
}
}

View File

@@ -3,35 +3,31 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Security;
using Xunit;
using Microsoft.SqlTools.ServiceLayer.Admin;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using NUnit.Framework;
using Microsoft.SqlTools.ServiceLayer.Management;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Admin
{
[TestFixture]
/// <summary>
/// Tests for AdminService Class
/// </summary>
public class AdminServiceTests
{
[Fact]
[Test]
public void TestBuildingSecureStringFromPassword()
{
string password = "test_password";
var secureString = CDataContainer.BuildSecureStringFromPassword(password);
Assert.Equal(password.Length, secureString.Length);
Assert.AreEqual(password.Length, secureString.Length);
}
[Fact]
[Test]
public void TestBuildingSecureStringFromNullPassword()
{
string password = null;
var secureString = CDataContainer.BuildSecureStringFromPassword(password);
Assert.Equal(0, secureString.Length);
Assert.AreEqual(0, secureString.Length);
}
}
}

View File

@@ -3,6 +3,6 @@
// 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]

View File

@@ -12,12 +12,13 @@ using Microsoft.Data.SqlClient;
using Microsoft.SqlTools.ServiceLayer.AutoParameterizaition;
using Microsoft.SqlTools.ServiceLayer.AutoParameterizaition.Exceptions;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
using NUnit.Framework;
using static System.Linq.Enumerable;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
{
[TestFixture]
/// <summary>
/// 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
@@ -38,7 +39,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// - Are declared and initialized in the same statement(inline initialization).
/// - Are initialized using a single literal.
/// </summary>
[Fact]
[Test]
public void SqlParameterizerShouldParameterizeValidVariables()
{
const string ssn = "795-73-9838";
@@ -56,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
DbCommand command = new SqlCommand { CommandText = sql };
command.Parameterize();
Assert.Equal(expected: 3, actual: command.Parameters.Count);
Assert.AreEqual(expected: 3, actual: command.Parameters.Count);
}
/// <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 third is using an expression used instead of a literal and so should not be parameterized.
/// </summary>
[Fact]
[Test]
public void SqlParameterizerShouldNotParameterizeInvalidVariables()
{
string sql = $@"
@@ -82,7 +83,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
DbCommand command = new SqlCommand { CommandText = sql };
command.Parameterize();
Assert.Equal(expected: 0, actual: command.Parameters.Count);
Assert.AreEqual(expected: 0, actual: command.Parameters.Count);
}
/// <summary>
@@ -90,7 +91,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// Batch statements larger than 300000 characters (Approximately 600 Kb) should
/// throw <c>ParameterizationScriptTooLargeException</c>.
/// </summary>
[Fact]
[Test]
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>.
/// Better to catch the error here than on the server.
/// </summary>
[Fact]
[Test]
public void SqlParameterizerShouldThrowWhenSqlIsInvalid()
{
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.
/// If not, a <c>ParameterizationFormatException</c> should get thrown.
/// </summary>
[Fact]
[Test]
public void SqlParameterizerShouldThrowWhenLiteralHasTypeMismatch()
{
// 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:
/// BeginExecuteReader: CommandText property has not been initialized
/// </summary>
[Fact]
[Test]
public void CommentOnlyBatchesShouldNotBeErasedFromCommandText()
{
string sql = $@"
@@ -169,7 +170,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
command.Parameterize();
Assert.False(string.IsNullOrEmpty(command.CommandText));
Assert.Equal(expected: sql, actual: command.CommandText);
Assert.AreEqual(expected: sql, actual: command.CommandText);
}
#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>
/// method, if a null script is passed in, the reuslt should be an empty collection.
/// </summary>
[Fact]
[Test]
public void CodeSenseShouldReturnEmptyListWhenGivenANullScript()
{
string sql = null;
IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql);
Assert.NotNull(result);
Assert.Empty(result);
Assert.That(result, Is.Empty);
}
/// <summary>
/// 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.
/// </summary>
[Fact]
[Test]
public void CodeSenseShouldReturnEmptyListWhenGivenAParameterlessScript()
{
// SQL with no parameters
@@ -206,7 +207,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql);
Assert.NotNull(result);
Assert.Empty(result);
Assert.That(result, Is.Empty);
}
/// <summary>
@@ -214,7 +215,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// 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.
/// </summary>
[Fact]
[Test]
public void CodeSenseShouldReturnMaxStringLengthScriptFileMarkerErrorItemWhenScriptIsTooLong()
{
// SQL length of 300 characters
@@ -235,10 +236,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
Console.WriteLine(result[0].Message);
Assert.NotEmpty(result);
Assert.Equal(expected: 1, actual: result.Count);
Assert.Equal(expected: ScriptFileMarkerLevel.Error, actual: result[0].Level);
Assert.Equal(expected: expectedMessage, actual: result[0].Message);
Assert.That(result, Is.Not.Empty);
Assert.AreEqual(expected: 1, actual: result.Count);
Assert.AreEqual(expected: ScriptFileMarkerLevel.Error, actual: result[0].Level);
Assert.AreEqual(expected: expectedMessage, actual: result[0].Message);
}
/// <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
/// three informational code sense items. These will be returned to ADS to display to the user as intelli-sense.
/// </summary>
[Fact]
[Test]
public void CodeSenseShouldReturnInformationalCodeSenseItemsForValidParameters()
{
const string ssn = "795-73-9838";
@@ -263,8 +264,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql);
Assert.NotEmpty(result);
Assert.Equal(expected: 3, actual: result.Count);
Assert.That(result, Is.Not.Empty);
Assert.AreEqual(expected: 3, actual: result.Count);
Assert.True(Enumerable.All(result, i => i.Level == ScriptFileMarkerLevel.Information));
}

View File

@@ -7,13 +7,14 @@
using System.Threading;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion
{
[TestFixture]
public class AutoCompletionResultTest
{
[Fact]
[Test]
public void CompletionShouldRecordDuration()
{
AutoCompletionResult result = new AutoCompletionResult();

View File

@@ -6,13 +6,14 @@
using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion
{
[TestFixture]
public class ScriptDocumentInfoTest
{
[Fact]
[Test]
public void MetricsShouldGetSortedGivenUnSortedArray()
{
TextDocumentPosition doc = new TextDocumentPosition()
@@ -35,11 +36,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion
ScriptParseInfo scriptParseInfo = new ScriptParseInfo();
ScriptDocumentInfo docInfo = new ScriptDocumentInfo(doc, scriptFile, scriptParseInfo);
Assert.Equal(docInfo.StartLine, 1);
Assert.Equal(docInfo.ParserLine, 2);
Assert.Equal(docInfo.StartColumn, 44);
Assert.Equal(docInfo.EndColumn, 14);
Assert.Equal(docInfo.ParserColumn, 15);
Assert.AreEqual(1, docInfo.StartLine);
Assert.AreEqual(2, docInfo.ParserLine);
Assert.AreEqual(44, docInfo.StartColumn);
Assert.AreEqual(14, docInfo.EndColumn);
Assert.AreEqual(15, docInfo.ParserColumn);
}
}
}

View File

@@ -4,12 +4,13 @@
//
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Xunit;
using NUnit.Framework;
using Microsoft.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{
[TestFixture]
/// <summary>
/// Tests for Sever Information Caching Class
/// </summary>
@@ -22,12 +23,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
cache = new CachedServerInfo();
}
[Fact]
[Test]
public void CacheMatchesNullDbNameToEmptyString()
{
// Set sqlDw result into cache
string dataSource = "testDataSource";
DatabaseEngineEdition engineEdition;
string dataSource = "testDataSource";
SqlConnectionStringBuilder testSource = new SqlConnectionStringBuilder
{
DataSource = dataSource,
@@ -36,31 +36,26 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
cache.AddOrUpdateCache(testSource, DatabaseEngineEdition.SqlDataWarehouse, CachedServerInfo.CacheVariable.EngineEdition);
// 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
Assert.Equal(cache.TryGetEngineEdition(new SqlConnectionStringBuilder
Assert.AreEqual(DatabaseEngineEdition.SqlDataWarehouse, cache.TryGetEngineEdition(new SqlConnectionStringBuilder
{
DataSource = dataSource
// Initial Catalog is null. Can't set explicitly as this throws
}, out engineEdition), DatabaseEngineEdition.SqlDataWarehouse);
}, out _));
// But expect NotEqual for a different DB
Assert.NotEqual(cache.TryGetEngineEdition(new SqlConnectionStringBuilder
Assert.That(cache.TryGetEngineEdition(new SqlConnectionStringBuilder
{
DataSource = dataSource,
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
[InlineData("", DatabaseEngineEdition.SqlDataWarehouse)] // is SqlDW instance
[InlineData("myDb", DatabaseEngineEdition.SqlDataWarehouse)] // is SqlDW instance
[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)
[Test]
public void AddOrUpdateEngineEdition([Values(null, "", "myDb")] string dbName,
[Values(DatabaseEngineEdition.SqlDataWarehouse, DatabaseEngineEdition.SqlOnDemand)] DatabaseEngineEdition state)
{
// Set result into cache
DatabaseEngineEdition engineEdition;
@@ -75,15 +70,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
cache.AddOrUpdateCache(testSource, state, CachedServerInfo.CacheVariable.EngineEdition);
// Expect the same returned result
Assert.NotEqual(cache.TryGetEngineEdition(testSource, out engineEdition), DatabaseEngineEdition.Unknown);
Assert.Equal(engineEdition, state);
Assert.Multiple(() =>
{
Assert.That(cache.TryGetEngineEdition(testSource, out engineEdition), Is.Not.EqualTo(DatabaseEngineEdition.Unknown) );
Assert.That(engineEdition, Is.EqualTo(state), "Expect the same returned result");
});
}
[Theory]
[InlineData(DatabaseEngineEdition.SqlDataWarehouse)] // is SqlDW instance
[InlineData(DatabaseEngineEdition.SqlOnDemand)] // is SqlOnDemand Instance
public void AddOrUpdateEngineEditionToggle(DatabaseEngineEdition state)
[Test]
public void AddOrUpdateEngineEditionToggle([Values(DatabaseEngineEdition.SqlDataWarehouse, DatabaseEngineEdition.SqlOnDemand)] DatabaseEngineEdition state)
{
// Set result into cache
DatabaseEngineEdition engineEdition;
@@ -93,21 +88,25 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
};
cache.AddOrUpdateCache(testSource, state, CachedServerInfo.CacheVariable.EngineEdition);
// Expect the same returned result
Assert.NotEqual(cache.TryGetEngineEdition(testSource, out engineEdition), DatabaseEngineEdition.Unknown);
Assert.Equal(engineEdition, state);
Assert.Multiple(() =>
{
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.SqlOnDemand : DatabaseEngineEdition.SqlDataWarehouse;
cache.AddOrUpdateCache(testSource, newState, CachedServerInfo.CacheVariable.EngineEdition);
// Expect the opposite returned result
Assert.NotEqual(cache.TryGetEngineEdition(testSource, out engineEdition), DatabaseEngineEdition.Unknown);
Assert.Equal(engineEdition, newState);
Assert.Multiple(() =>
{
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()
{
bool state = true;
@@ -142,22 +141,21 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
Assert.True(cache.TryGetIsSqlDw(differentServerSameDb, out isSqlDwResult3));
// Assert cache is set on a per connection basis
Assert.Equal(isSqlDwResult, state);
Assert.Equal(isSqlDwResult2, !state);
Assert.Equal(isSqlDwResult3, !state);
Assert.AreEqual(isSqlDwResult, state);
Assert.AreEqual(isSqlDwResult2, !state);
Assert.AreEqual(isSqlDwResult3, !state);
}
*/
[Fact]
[Test]
public void AskforEngineEditionBeforeCached()
{
DatabaseEngineEdition engineEdition;
Assert.Equal(cache.TryGetEngineEdition(new SqlConnectionStringBuilder
{
Assert.AreEqual(DatabaseEngineEdition.Unknown, cache.TryGetEngineEdition(new SqlConnectionStringBuilder
{
DataSource = "testDataSourceUnCached"
},
out engineEdition), DatabaseEngineEdition.Unknown);
out _));
}
}
}

View File

@@ -6,17 +6,18 @@
using System.Linq;
using Microsoft.SqlTools.Hosting.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Xunit;
using NUnit.Framework;
using Microsoft.SqlTools.ServiceLayer.Connection;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{
[TestFixture]
/// <summary>
/// Tests for ConnectionDetails Class
/// </summary>
public class ConnectionDetailsTests
{
[Fact]
[Test]
public void ConnectionDetailsWithoutAnyOptionShouldReturnNullOrDefaultForOptions()
{
ConnectionDetails details = new ConnectionDetails();
@@ -25,39 +26,39 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
var expectedForInt = default(int?);
var expectedForBoolean = default(bool?);
Assert.Equal(details.ApplicationIntent, expectedForStrings);
Assert.Equal(details.ApplicationName, expectedForStrings);
Assert.Equal(details.AttachDbFilename, expectedForStrings);
Assert.Equal(details.AuthenticationType, expectedForStrings);
Assert.Equal(details.CurrentLanguage, expectedForStrings);
Assert.Equal(details.DatabaseName, expectedForStrings);
Assert.Equal(details.FailoverPartner, expectedForStrings);
Assert.Equal(details.Password, expectedForStrings);
Assert.Equal(details.ServerName, expectedForStrings);
Assert.Equal(details.TypeSystemVersion, expectedForStrings);
Assert.Equal(details.UserName, expectedForStrings);
Assert.Equal(details.WorkstationId, expectedForStrings);
Assert.Equal(details.ConnectRetryInterval, expectedForInt);
Assert.Equal(details.ConnectRetryCount, expectedForInt);
Assert.Equal(details.ConnectTimeout, expectedForInt);
Assert.Equal(details.LoadBalanceTimeout, expectedForInt);
Assert.Equal(details.MaxPoolSize, expectedForInt);
Assert.Equal(details.MinPoolSize, expectedForInt);
Assert.Equal(details.PacketSize, expectedForInt);
Assert.Equal(details.ColumnEncryptionSetting, expectedForStrings);
Assert.Equal(details.EnclaveAttestationUrl, expectedForStrings);
Assert.Equal(details.EnclaveAttestationProtocol, expectedForStrings);
Assert.Equal(details.Encrypt, expectedForBoolean);
Assert.Equal(details.MultipleActiveResultSets, expectedForBoolean);
Assert.Equal(details.MultiSubnetFailover, expectedForBoolean);
Assert.Equal(details.PersistSecurityInfo, expectedForBoolean);
Assert.Equal(details.Pooling, expectedForBoolean);
Assert.Equal(details.Replication, expectedForBoolean);
Assert.Equal(details.TrustServerCertificate, expectedForBoolean);
Assert.Equal(details.Port, expectedForInt);
Assert.AreEqual(details.ApplicationIntent, expectedForStrings);
Assert.AreEqual(details.ApplicationName, expectedForStrings);
Assert.AreEqual(details.AttachDbFilename, expectedForStrings);
Assert.AreEqual(details.AuthenticationType, expectedForStrings);
Assert.AreEqual(details.CurrentLanguage, expectedForStrings);
Assert.AreEqual(details.DatabaseName, expectedForStrings);
Assert.AreEqual(details.FailoverPartner, expectedForStrings);
Assert.AreEqual(details.Password, expectedForStrings);
Assert.AreEqual(details.ServerName, expectedForStrings);
Assert.AreEqual(details.TypeSystemVersion, expectedForStrings);
Assert.AreEqual(details.UserName, expectedForStrings);
Assert.AreEqual(details.WorkstationId, expectedForStrings);
Assert.AreEqual(details.ConnectRetryInterval, expectedForInt);
Assert.AreEqual(details.ConnectRetryCount, expectedForInt);
Assert.AreEqual(details.ConnectTimeout, expectedForInt);
Assert.AreEqual(details.LoadBalanceTimeout, expectedForInt);
Assert.AreEqual(details.MaxPoolSize, expectedForInt);
Assert.AreEqual(details.MinPoolSize, expectedForInt);
Assert.AreEqual(details.PacketSize, expectedForInt);
Assert.AreEqual(details.ColumnEncryptionSetting, expectedForStrings);
Assert.AreEqual(details.EnclaveAttestationUrl, expectedForStrings);
Assert.AreEqual(details.EnclaveAttestationProtocol, expectedForStrings);
Assert.AreEqual(details.Encrypt, expectedForBoolean);
Assert.AreEqual(details.MultipleActiveResultSets, expectedForBoolean);
Assert.AreEqual(details.MultiSubnetFailover, expectedForBoolean);
Assert.AreEqual(details.PersistSecurityInfo, expectedForBoolean);
Assert.AreEqual(details.Pooling, expectedForBoolean);
Assert.AreEqual(details.Replication, expectedForBoolean);
Assert.AreEqual(details.TrustServerCertificate, expectedForBoolean);
Assert.AreEqual(details.Port, expectedForInt);
}
[Fact]
[Test]
public void ConnectionDetailsPropertySettersShouldSetOptionValuesCorrectly()
{
ConnectionDetails details = new ConnectionDetails();
@@ -97,39 +98,39 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
details.Port = expectedForInt + index++;
index = 0;
Assert.Equal(details.ApplicationIntent, expectedForStrings + index++);
Assert.Equal(details.ApplicationName, expectedForStrings + index++);
Assert.Equal(details.AttachDbFilename, expectedForStrings + index++);
Assert.Equal(details.AuthenticationType, expectedForStrings + index++);
Assert.Equal(details.CurrentLanguage, expectedForStrings + index++);
Assert.Equal(details.DatabaseName, expectedForStrings + index++);
Assert.Equal(details.FailoverPartner, expectedForStrings + index++);
Assert.Equal(details.Password, expectedForStrings + index++);
Assert.Equal(details.ServerName, expectedForStrings + index++);
Assert.Equal(details.TypeSystemVersion, expectedForStrings + index++);
Assert.Equal(details.UserName, expectedForStrings + index++);
Assert.Equal(details.WorkstationId, expectedForStrings + index++);
Assert.Equal(details.ConnectRetryInterval, expectedForInt + index++);
Assert.Equal(details.ConnectRetryCount, expectedForInt + index++);
Assert.Equal(details.ConnectTimeout, expectedForInt + index++);
Assert.Equal(details.LoadBalanceTimeout, expectedForInt + index++);
Assert.Equal(details.MaxPoolSize, expectedForInt + index++);
Assert.Equal(details.MinPoolSize, expectedForInt + index++);
Assert.Equal(details.PacketSize, expectedForInt + index++);
Assert.Equal(details.ColumnEncryptionSetting, expectedForStrings + index++);
Assert.Equal(details.EnclaveAttestationProtocol, expectedForStrings + index++);
Assert.Equal(details.EnclaveAttestationUrl, expectedForStrings + index++);
Assert.Equal(details.Encrypt, (index++ % 2 == 0));
Assert.Equal(details.MultipleActiveResultSets, (index++ % 2 == 0));
Assert.Equal(details.MultiSubnetFailover, (index++ % 2 == 0));
Assert.Equal(details.PersistSecurityInfo, (index++ % 2 == 0));
Assert.Equal(details.Pooling, (index++ % 2 == 0));
Assert.Equal(details.Replication, (index++ % 2 == 0));
Assert.Equal(details.TrustServerCertificate, (index++ % 2 == 0));
Assert.Equal(details.Port, (expectedForInt + index++));
Assert.AreEqual(details.ApplicationIntent, expectedForStrings + index++);
Assert.AreEqual(details.ApplicationName, expectedForStrings + index++);
Assert.AreEqual(details.AttachDbFilename, expectedForStrings + index++);
Assert.AreEqual(details.AuthenticationType, expectedForStrings + index++);
Assert.AreEqual(details.CurrentLanguage, expectedForStrings + index++);
Assert.AreEqual(details.DatabaseName, expectedForStrings + index++);
Assert.AreEqual(details.FailoverPartner, expectedForStrings + index++);
Assert.AreEqual(details.Password, expectedForStrings + index++);
Assert.AreEqual(details.ServerName, expectedForStrings + index++);
Assert.AreEqual(details.TypeSystemVersion, expectedForStrings + index++);
Assert.AreEqual(details.UserName, expectedForStrings + index++);
Assert.AreEqual(details.WorkstationId, expectedForStrings + index++);
Assert.AreEqual(details.ConnectRetryInterval, expectedForInt + index++);
Assert.AreEqual(details.ConnectRetryCount, expectedForInt + index++);
Assert.AreEqual(details.ConnectTimeout, expectedForInt + index++);
Assert.AreEqual(details.LoadBalanceTimeout, expectedForInt + index++);
Assert.AreEqual(details.MaxPoolSize, expectedForInt + index++);
Assert.AreEqual(details.MinPoolSize, expectedForInt + index++);
Assert.AreEqual(details.PacketSize, expectedForInt + index++);
Assert.AreEqual(details.ColumnEncryptionSetting, expectedForStrings + index++);
Assert.AreEqual(details.EnclaveAttestationProtocol, expectedForStrings + index++);
Assert.AreEqual(details.EnclaveAttestationUrl, expectedForStrings + index++);
Assert.AreEqual(details.Encrypt, (index++ % 2 == 0));
Assert.AreEqual(details.MultipleActiveResultSets, (index++ % 2 == 0));
Assert.AreEqual(details.MultiSubnetFailover, (index++ % 2 == 0));
Assert.AreEqual(details.PersistSecurityInfo, (index++ % 2 == 0));
Assert.AreEqual(details.Pooling, (index++ % 2 == 0));
Assert.AreEqual(details.Replication, (index++ % 2 == 0));
Assert.AreEqual(details.TrustServerCertificate, (index++ % 2 == 0));
Assert.AreEqual(details.Port, (expectedForInt + index++));
}
[Fact]
[Test]
public void ConnectionDetailsOptionsShouldBeDefinedInConnectionProviderOptions()
{
ConnectionDetails details = new ConnectionDetails();
@@ -195,7 +196,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
}
[Fact]
[Test]
public void SettingConnectiomTimeoutToLongShouldStillReturnInt()
{
ConnectionDetails details = new ConnectionDetails();
@@ -204,27 +205,27 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
int? expectedValue = 30;
details.Options["connectTimeout"] = timeout;
Assert.Equal(details.ConnectTimeout, expectedValue);
Assert.AreEqual(details.ConnectTimeout, expectedValue);
}
[Fact]
[Test]
public void ConnectTimeoutShouldReturnNullIfNotSet()
{
ConnectionDetails details = new ConnectionDetails();
int? expectedValue = null;
Assert.Equal(details.ConnectTimeout, expectedValue);
Assert.AreEqual(details.ConnectTimeout, expectedValue);
}
[Fact]
[Test]
public void ConnectTimeoutShouldReturnNullIfSetToNull()
{
ConnectionDetails details = new ConnectionDetails();
details.Options["connectTimeout"] = null;
int? expectedValue = null;
Assert.Equal(details.ConnectTimeout, expectedValue);
Assert.AreEqual(details.ConnectTimeout, expectedValue);
}
[Fact]
[Test]
public void SettingEncryptToStringShouldStillReturnBoolean()
{
ConnectionDetails details = new ConnectionDetails();
@@ -233,10 +234,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
bool? expectedValue = true;
details.Options["encrypt"] = encrypt;
Assert.Equal(details.Encrypt, expectedValue);
Assert.AreEqual(details.Encrypt, expectedValue);
}
[Fact]
[Test]
public void SettingEncryptToLowecaseStringShouldStillReturnBoolean()
{
ConnectionDetails details = new ConnectionDetails();
@@ -245,27 +246,27 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
bool? expectedValue = true;
details.Options["encrypt"] = encrypt;
Assert.Equal(details.Encrypt, expectedValue);
Assert.AreEqual(details.Encrypt, expectedValue);
}
[Fact]
[Test]
public void EncryptShouldReturnNullIfNotSet()
{
ConnectionDetails details = new ConnectionDetails();
bool? expectedValue = null;
Assert.Equal(details.Encrypt, expectedValue);
Assert.AreEqual(details.Encrypt, expectedValue);
}
[Fact]
[Test]
public void EncryptShouldReturnNullIfSetToNull()
{
ConnectionDetails details = new ConnectionDetails();
details.Options["encrypt"] = null;
int? expectedValue = null;
Assert.Equal(details.ConnectTimeout, expectedValue);
Assert.AreEqual(details.ConnectTimeout, expectedValue);
}
[Fact]
[Test]
public void SettingConnectiomTimeoutToLongWhichCannotBeConvertedToIntShouldNotCrash()
{
ConnectionDetails details = new ConnectionDetails();
@@ -275,8 +276,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
details.Options["connectTimeout"] = timeout;
details.Options["encrypt"] = true;
Assert.Equal(details.ConnectTimeout, expectedValue);
Assert.Equal(details.Encrypt, true);
Assert.AreEqual(details.ConnectTimeout, expectedValue);
Assert.AreEqual(true, details.Encrypt);
}
}
}

View File

@@ -6,16 +6,17 @@
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Moq;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{
[TestFixture]
public class DatabaseLocksManagerTests
{
private const string server1 = "server1";
private const string database1 = "database1";
[Fact]
[Test]
public void GainFullAccessShouldDisconnectTheConnections()
{
var connectionLock = new Mock<IConnectedBindingQueue>();
@@ -30,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
}
}
[Fact]
[Test]
public void ReleaseAccessShouldConnectTheConnections()
{
var connectionLock = new Mock<IConnectedBindingQueue>();
@@ -45,7 +46,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
}
}
//[Fact]
//[Test]
public void SecondProcessToGainAccessShouldWaitForTheFirstProcess()
{
var connectionLock = new Mock<IConnectedBindingQueue>();
@@ -62,9 +63,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{
secondTimeGettingAccessFails = true;
}
Assert.Equal(secondTimeGettingAccessFails, true);
Assert.AreEqual(true, secondTimeGettingAccessFails);
databaseLocksManager.ReleaseAccess(server1, database1);
Assert.Equal(databaseLocksManager.GainFullAccessToDatabase(server1, database1), true);
Assert.AreEqual(true, databaseLocksManager.GainFullAccessToDatabase(server1, database1));
databaseLocksManager.ReleaseAccess(server1, database1);
}
}

View File

@@ -7,16 +7,17 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{
[TestFixture]
/// <summary>
/// Tests for ReliableConnection code
/// </summary>
public class ReliableConnectionTests
{
[Fact]
[Test]
public void ReliableSqlConnectionUsesAzureToken()
{
ConnectionDetails details = TestObjects.GetTestConnectionDetails();
@@ -30,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
var reliableConnection = new ReliableSqlConnection(connectionString, retryPolicy, retryPolicy, azureAccountToken);
// Then the connection's azureAccountToken gets set
Assert.Equal(azureAccountToken, reliableConnection.GetUnderlyingConnection().AccessToken);
Assert.AreEqual(azureAccountToken, reliableConnection.GetUnderlyingConnection().AccessToken);
}
}
}

View File

@@ -12,16 +12,17 @@ using Microsoft.SqlTools.Credentials.Contracts;
using Microsoft.SqlTools.Credentials.Linux;
using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
{
[TestFixture]
/// <summary>
/// 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
/// tests are being run on
/// </summary>
public class CredentialServiceTests : IDisposable
public class CredentialServiceTests
{
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
// even if previous runs stopped midway through
private readonly ICredentialStore credStore;
private readonly CredentialService service;
/// <summary>
/// Constructor called once for every test
/// </summary>
public CredentialServiceTests()
private ICredentialStore credStore;
private CredentialService service;
[SetUp]
public void SetupCredentialServiceTests()
{
credStore = CredentialService.GetStoreForOS(Config);
service = new CredentialService(credStore, Config);
DeleteDefaultCreds();
}
[TearDown]
public void Dispose()
{
DeleteDefaultCreds();
@@ -73,7 +74,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
#endif
}
[Fact]
[Test]
public async Task SaveCredentialThrowsIfCredentialIdMissing()
{
string errorResponse = null;
@@ -81,10 +82,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
await service.HandleSaveCredentialRequest(new Credential(null), contextMock.Object);
TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentException", errorResponse);
Assert.That(errorResponse, Does.Contain("ArgumentException"));
}
[Fact]
[Test]
public async Task SaveCredentialThrowsIfPasswordMissing()
{
string errorResponse = null;
@@ -95,7 +96,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
Assert.True(errorResponse.Contains("ArgumentException") || errorResponse.Contains("ArgumentNullException"));
}
[Fact]
[Test]
public async Task SaveCredentialWorksForSingleCredential()
{
await TestUtils.RunAndVerify<bool>(
@@ -103,7 +104,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: Assert.True);
}
[Fact]
[Test]
public async Task SaveCredentialWorksForEmptyPassword()
{
await TestUtils.RunAndVerify<bool>(
@@ -111,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: Assert.True);
}
[Fact]
[Test]
public async Task SaveCredentialSupportsSavingCredentialMultipleTimes()
{
await TestUtils.RunAndVerify<bool>(
@@ -123,7 +124,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: Assert.True);
}
[Fact]
[Test]
public async Task ReadCredentialWorksForSingleCredential()
{
// 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),
verify: (actual =>
{
Assert.Equal(Password1, actual.Password);
Assert.AreEqual(Password1, actual.Password);
}));
}
[Fact]
[Test]
public async Task ReadCredentialWorksForMultipleCredentials()
{
@@ -159,17 +160,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId, null), requestContext),
verify: (actual =>
{
Assert.Equal(Password1, actual.Password);
Assert.AreEqual(Password1, actual.Password);
}));
await TestUtils.RunAndVerify<Credential>(
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(OtherCredId, null), requestContext),
verify: (actual =>
{
Assert.Equal(OtherPassword, actual.Password);
Assert.AreEqual(OtherPassword, actual.Password);
}));
}
[Fact]
[Test]
public async Task ReadCredentialHandlesPasswordUpdate()
{
// 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),
verify: (actual =>
{
Assert.Equal(Password2, actual.Password);
Assert.AreEqual(Password2, actual.Password);
}));
}
[Fact]
[Test]
public async Task ReadCredentialThrowsIfCredentialIsNull()
{
string errorResponse = null;
@@ -200,10 +201,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
// Verify throws on null, and this is sent as an error
await service.HandleReadCredentialRequest(null, contextMock.Object);
TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentNullException", errorResponse);
Assert.That(errorResponse, Does.Contain("ArgumentNullException"));
}
[Fact]
[Test]
public async Task ReadCredentialThrowsIfIdMissing()
{
string errorResponse = null;
@@ -212,10 +213,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
// Verify throws with no ID
await service.HandleReadCredentialRequest(new Credential(), contextMock.Object);
TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentException", errorResponse);
Assert.That(errorResponse, Does.Contain("ArgumentException"));
}
[Fact]
[Test]
public async Task ReadCredentialReturnsNullPasswordForMissingCredential()
{
// Given a credential whose password doesn't exist
@@ -228,12 +229,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: (actual =>
{
Assert.NotNull(actual);
Assert.Equal(credWithNoPassword, actual.CredentialId);
Assert.AreEqual(credWithNoPassword, actual.CredentialId);
Assert.Null(actual.Password);
}));
}
[Fact]
[Test]
public async Task DeleteCredentialThrowsIfIdMissing()
{
object errorResponse = null;
@@ -245,7 +246,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
Assert.True(((string)errorResponse).Contains("ArgumentException"));
}
[Fact]
[Test]
public async Task DeleteCredentialReturnsTrueOnlyIfCredentialExisted()
{
// Save should be true

View File

@@ -6,13 +6,14 @@
using Microsoft.SqlTools.Credentials;
using Microsoft.SqlTools.Credentials.Linux;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Linux
{
[TestFixture]
public class LinuxInteropTests
{
[Fact]
[Test]
public void GetEUidReturnsInt()
{
#if !WINDOWS_ONLY_BUILD
@@ -23,14 +24,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Linux
#endif
}
[Fact]
[Test]
public void GetHomeDirectoryFromPwFindsHomeDir()
{
#if !WINDOWS_ONLY_BUILD
RunIfWrapper.RunIfLinux(() =>
{
string userDir = LinuxCredentialStore.GetHomeDirectoryFromPw();
Assert.StartsWith("/", userDir);
Assert.That(userDir, Does.StartWith("/"), "GetHomeDirectoryFromPw");
});
#endif
}

View File

@@ -6,13 +6,14 @@
using System;
using Microsoft.SqlTools.Credentials.Win32;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
{
[TestFixture]
public class CredentialSetTests
{
[Fact]
[Test]
public void CredentialSetCreate()
{
RunIfWrapper.RunIfWindows(() =>
@@ -21,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void CredentialSetCreateWithTarget()
{
RunIfWrapper.RunIfWindows(() =>
@@ -30,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void CredentialSetShouldBeIDisposable()
{
RunIfWrapper.RunIfWindows(() =>
@@ -39,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void CredentialSetLoad()
{
RunIfWrapper.RunIfWindows(() =>
@@ -56,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
CredentialSet set = new CredentialSet();
set.Load();
Assert.NotNull(set);
Assert.NotEmpty(set);
Assert.That(set, Is.Not.Empty);
credential.Delete();
@@ -64,19 +65,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void CredentialSetLoadShouldReturnSelf()
{
RunIfWrapper.RunIfWindows(() =>
{
CredentialSet set = new CredentialSet();
Assert.IsType<CredentialSet>(set.Load());
Assert.That(set.Load(), Is.SameAs(set));
set.Dispose();
});
}
[Fact]
[Test]
public void CredentialSetLoadWithTargetFilter()
{
RunIfWrapper.RunIfWindows(() =>
@@ -90,7 +91,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
credential.Save();
CredentialSet set = new CredentialSet("filtertarget");
Assert.Equal(1, set.Load().Count);
Assert.AreEqual(1, set.Load().Count);
set.Dispose();
});
}

View File

@@ -6,13 +6,14 @@
using System;
using Microsoft.SqlTools.Credentials.Win32;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
{
[TestFixture]
public class Win32CredentialTests
{
[Fact]
[Test]
public void Credential_Create_ShouldNotThrowNull()
{
RunIfWrapper.RunIfWindows(() =>
@@ -21,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_Create_With_Username_ShouldNotThrowNull()
{
RunIfWrapper.RunIfWindows(() =>
@@ -30,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_Create_With_Username_And_Password_ShouldNotThrowNull()
{
RunIfWrapper.RunIfWindows(() =>
@@ -39,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_Create_With_Username_Password_Target_ShouldNotThrowNull()
{
RunIfWrapper.RunIfWindows(() =>
@@ -48,7 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_ShouldBe_IDisposable()
{
RunIfWrapper.RunIfWindows(() =>
@@ -57,7 +58,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_Dispose_ShouldNotThrowException()
{
RunIfWrapper.RunIfWindows(() =>
@@ -66,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_ShouldThrowObjectDisposedException()
{
RunIfWrapper.RunIfWindows(() =>
@@ -77,7 +78,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_Save()
{
RunIfWrapper.RunIfWindows(() =>
@@ -88,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_Delete()
{
RunIfWrapper.RunIfWindows(() =>
@@ -98,7 +99,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_Delete_NullTerminator()
{
RunIfWrapper.RunIfWindows(() =>
@@ -109,7 +110,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
});
}
[Fact]
[Test]
public void Credential_Load()
{
RunIfWrapper.RunIfWindows(() =>
@@ -120,15 +121,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
Win32Credential credential = new Win32Credential { Target = "target", Type = CredentialType.Generic };
Assert.True(credential.Load());
Assert.NotEmpty(credential.Username);
Assert.That(credential.Username, Is.Not.Empty);
Assert.NotNull(credential.Password);
Assert.Equal("username", credential.Username);
Assert.Equal("password", credential.Password);
Assert.Equal("target", credential.Target);
Assert.AreEqual("username", credential.Username);
Assert.AreEqual("password", credential.Password);
Assert.AreEqual("target", credential.Target);
});
}
[Fact]
[Test]
public void Credential_Exists_Target_ShouldNotBeNull()
{
RunIfWrapper.RunIfWindows(() =>

View File

@@ -5,13 +5,14 @@
using System;
using Microsoft.SqlTools.ServiceLayer.DacFx;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DacFx
{
[TestFixture]
public class DacFxTests
{
[Fact]
[Test]
public void ExtractParseVersionShouldThrowExceptionGivenInvalidVersion()
{
string invalidVersion = "invalidVerison";

View File

@@ -7,7 +7,7 @@ using Microsoft.SqlTools.ServiceLayer.DisasterRecovery;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Moq;
using System.Threading.Tasks;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
{
@@ -17,7 +17,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Create and run a backup task
/// </summary>
/// <returns></returns>
[Fact]
[Test]
public async Task VerifyRunningBackupTask()
{
using (SqlTaskManager manager = new SqlTaskManager())
@@ -28,7 +28,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.NotNull(sqlTask);
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
});
await taskToVerify;
@@ -39,7 +39,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Generate script for backup task
/// </summary>
/// <returns></returns>
[Fact]
[Test]
public async Task VerifyScriptBackupTask()
{
using (SqlTaskManager manager = new SqlTaskManager())
@@ -52,7 +52,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.NotNull(sqlTask);
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
});
await taskToVerify;
@@ -63,7 +63,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Create and run multiple backup tasks
/// </summary>
/// <returns></returns>
[Fact]
[Test]
public async Task VerifyRunningMultipleBackupTasks()
{
using (SqlTaskManager manager = new SqlTaskManager())
@@ -78,12 +78,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
});
Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task =>
{
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus);
Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus);
});
await Task.WhenAll(taskToVerify, taskToVerify2);
@@ -94,7 +94,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Cancel a backup task
/// </summary>
/// <returns></returns>
[Fact]
[Test]
public async Task VerifyCancelBackupTask()
{
using (SqlTaskManager manager = new SqlTaskManager())
@@ -105,8 +105,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.NotNull(sqlTask);
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{
Assert.Equal(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
Assert.Equal(sqlTask.IsCancelRequested, true);
Assert.AreEqual(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
Assert.AreEqual(true, sqlTask.IsCancelRequested);
((BackupOperationStub)backupOperation).BackupSemaphore.Release();
manager.Reset();
});
@@ -120,7 +120,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Cancel multiple backup tasks
/// </summary>
/// <returns></returns>
[Fact]
[Test]
public async Task VerifyCancelMultipleBackupTasks()
{
using (SqlTaskManager manager = new SqlTaskManager())
@@ -137,16 +137,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{
Assert.Equal(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
Assert.Equal(sqlTask.IsCancelRequested, true);
Assert.AreEqual(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
Assert.AreEqual(true, sqlTask.IsCancelRequested);
((BackupOperationStub)backupOperation).BackupSemaphore.Release();
manager.Reset();
});
Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task =>
{
Assert.Equal(SqlTaskStatus.Canceled, sqlTask2.TaskStatus);
Assert.Equal(sqlTask2.IsCancelRequested, true);
Assert.AreEqual(SqlTaskStatus.Canceled, sqlTask2.TaskStatus);
Assert.AreEqual(true, sqlTask2.IsCancelRequested);
((BackupOperationStub)backupOperation2).BackupSemaphore.Release();
manager.Reset();
});
@@ -161,7 +161,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// Create two backup tasks and cancel one task
/// </summary>
/// <returns></returns>
[Fact]
[Test]
public async Task VerifyCombinationRunAndCancelBackupTasks()
{
using (SqlTaskManager manager = new SqlTaskManager())
@@ -179,15 +179,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
{
Assert.Equal(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
Assert.Equal(sqlTask.IsCancelRequested, true);
Assert.AreEqual(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
Assert.AreEqual(true, sqlTask.IsCancelRequested);
((BackupOperationStub)backupOperation).BackupSemaphore.Release();
manager.Reset();
});
Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task =>
{
Assert.Equal(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus);
Assert.AreEqual(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus);
});
manager.CancelTask(sqlTask.TaskId);

View File

@@ -8,19 +8,19 @@ using System.Collections.Generic;
using System.Text;
using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.Contracts;
using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.RestoreOperation;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
{
public class DatabaseFileInfoTests
{
[Fact]
[Test]
public void DatabaseFileInfoConstructorShouldThrowExceptionGivenNull()
{
Assert.Throws<ArgumentNullException>(() => new DatabaseFileInfo(null));
}
[Fact]
[Test]
public void DatabaseFileInfoShouldReturnNullGivenEmptyProperties()
{
LocalizedPropertyInfo[] properties = new LocalizedPropertyInfo[] { };
@@ -29,7 +29,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.True(string.IsNullOrEmpty(fileInfo.GetPropertyValueAsString(BackupSetInfo.BackupComponentPropertyName)));
}
[Fact]
[Test]
public void DatabaseFileInfoShouldReturnValuesGivenValidProperties()
{
LocalizedPropertyInfo[] properties = new LocalizedPropertyInfo[] {
@@ -46,8 +46,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
};
var fileInfo = new DatabaseFileInfo(properties);
Assert.Equal(fileInfo.Id, "id");
Assert.Equal(fileInfo.GetPropertyValueAsString("name"), "1");
Assert.AreEqual("id", fileInfo.Id);
Assert.AreEqual("1", fileInfo.GetPropertyValueAsString("name"));
}
}
}

View File

@@ -4,7 +4,7 @@
//
using Microsoft.SqlTools.ServiceLayer.DisasterRecovery;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
{
@@ -13,7 +13,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
/// </summary>
public class DisasterRecoveryFileValidatorUnitTests
{
[Fact]
[Test]
public void ValidatorShouldReturnTrueForNullArgument()
{
string message;
@@ -21,14 +21,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
Assert.True(result);
}
[Fact]
[Test]
public void GetMachineNameForLocalServer()
{
string machineName = DisasterRecoveryFileValidator.GetMachineName(DisasterRecoveryFileValidator.LocalSqlServer);
Assert.True(System.Environment.MachineName == machineName);
}
[Fact]
[Test]
public void GetMachineNameForNamedServer()
{
string testMachineName = "testmachine";

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