From 839acf67cda8b41c1fdd4a241ebfecbae51f0f17 Mon Sep 17 00:00:00 2001 From: David Shiflet Date: Wed, 5 Aug 2020 13:43:14 -0400 Subject: [PATCH] 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 --- Packages.props | 2 + azure-pipelines/build.yml | 2 +- .../BatchParser/ExecutionEngineCode/Batch.cs | 14 +- .../Microsoft.SqlTools.ServiceLayer.csproj | 21 +- .../CommonObjects.cs | 12 +- .../Utilities/FlagsIntConverterTests.cs | 27 +- .../Utilities/FlagsStringConverterTests.cs | 27 +- .../ServiceProviderTests.cs | 41 +- ...icrosoft.SqlTools.Hosting.UnitTests.csproj | 5 +- .../ProtocolTests/EventContextTests.cs | 16 +- .../ProtocolTests/JsonRpcHostTests.cs | 209 +++---- .../ProtocolTests/MessageReaderTests.cs | 56 +- .../ProtocolTests/MessageTests.cs | 79 +-- .../ProtocolTests/MessageWriterTests.cs | 36 +- .../ProtocolTests/RequestContextTests.cs | 60 +- .../ExtensibleServiceHostTest.cs | 16 +- .../ServiceHostTests/ServiceHostTests.cs | 62 +- .../UtilityTests/AsyncLockTests.cs | 17 +- .../UtilityTests/LoggerTests.cs | 5 +- .../AssemblyInfo.cs | 4 +- .../BatchParser/BatchParserSqlCmdTests.cs | 39 +- .../BatchParser/BatchParserTests.cs | 101 ++-- .../BatchParser/BatchParserWrapperTests.cs | 47 +- ...ManagedBatchParser.IntegrationTests.csproj | 5 +- .../ExecutionEngineTest.cs | 139 +++-- .../TSQLExecutionEngine/TestExecutor.cs | 42 +- .../Utility/LiveConnectionHelper.cs | 2 +- .../Admin/DatabaseAdminTests.cs | 14 +- .../Agent/AgentAlertTests.cs | 8 +- .../Agent/AgentJobStepTests.cs | 8 +- .../Agent/AgentJobTests.cs | 10 +- .../Agent/AgentNotebookTests.cs | 62 +- .../Agent/AgentOperatorTests.cs | 10 +- .../Agent/AgentProxyTests.cs | 10 +- .../Agent/AgentScheduleTests.cs | 10 +- .../Agent/AgentServiceTests.cs | 8 +- .../AssemblyInfo.cs | 4 +- .../Cms/CmsServiceTests.cs | 18 +- .../Connection/ConnectionServiceTests.cs | 24 +- .../Connection/ReliableConnectionTests.cs | 111 ++-- .../DacFx/DacFxserviceTests.cs | 104 ++-- .../DisasterRecovery/BackupServiceTests.cs | 38 +- .../DisasterRecoveryFileValidatorTests.cs | 10 +- .../RestoreDatabaseServiceTests.cs | 90 +-- .../FileBrowser/FileBrowserServiceTests.cs | 30 +- .../ExternalLanguageServiceTests.cs | 46 +- .../LanguageServer/LanguageServiceTests.cs | 20 +- .../LanguageServer/PeekDefinitionTests.cs | 88 +-- .../Metadata/MetadataServiceTests.cs | 16 +- ...Tools.ServiceLayer.IntegrationTests.csproj | 5 +- .../ObjectExplorerServiceTests.cs | 58 +- .../Profiler/ProfilerServiceTests.cs | 6 +- .../DataStorage/StorageDataReaderTests.cs | 10 +- .../QueryExecution/ExecuteTests.cs | 29 +- .../QueryExecution/SqlCmdExecutionTest.cs | 8 +- .../SchemaCompareServiceOptionsTests.cs | 36 +- .../SchemaCompareServiceTests.cs | 109 ++-- .../Scripting/ScriptingServiceTests.cs | 46 +- .../Security/CredentialTests.cs | 8 +- .../ServerConfigurationsServiceTests.cs | 28 +- .../SqlAssessmentServiceTests.cs | 107 ++-- .../TaskServices/TaskServiceTests.cs | 12 +- .../Utility/LiveConnectionHelper.cs | 2 +- .../Baselined/BaselinedTest.cs | 2 +- ...t.SqlTools.ServiceLayer.Test.Common.csproj | 5 +- .../EventFlowValidator.cs | 4 +- .../SqlTestDb.cs | 2 +- .../TestConnectionProfileService.cs | 2 +- .../TestLogger.cs | 2 +- .../TestServiceDriverProvider.cs | 2 +- .../TestServiceProvider.cs | 2 +- .../ConnectionTests.cs | 11 +- .../LanguageServiceTests.cs | 50 +- ...Tools.ServiceLayer.TestDriver.Tests.csproj | 5 +- .../Program.cs | 4 +- .../QueryExecutionTests.cs | 18 +- .../SqlScriptPublishModelTests.cs | 64 +- .../StressTests.cs | 18 +- .../WorkspaceTests.cs | 5 +- .../Driver/ServiceTestDriver.cs | 5 + ...ft.SqlTools.ServiceLayer.TestDriver.csproj | 2 - .../Utility/TestRunner.cs | 97 +-- .../Admin/AdminServiceTests.cs | 16 +- .../AssemblyInfo.cs | 4 +- .../SqlParameterizerTests.cs | 45 +- .../Completion/AutoCompletionResultTest.cs | 5 +- .../Completion/ScriptDocumentInfoTest.cs | 15 +- .../Connection/CachedServerInfoTests.cs | 78 ++- .../Connection/ConnectionDetailsTests.cs | 163 ++--- .../Connection/ConnectionServiceTests.cs | 568 ++++++++---------- .../Connection/DatabaseLocksManagerTests.cs | 13 +- .../Connection/ReliableConnectionTests.cs | 7 +- .../Credentials/CredentialServiceTests.cs | 59 +- .../Credentials/Linux/LinuxInteropTests.cs | 11 +- .../Credentials/Win32/CredentialSetTests.cs | 21 +- .../Credentials/Win32/Win32CredentialTests.cs | 35 +- .../DacFx/DacFxTests.cs | 5 +- .../DisasterRecovery/BackupTests.cs | 40 +- .../DisasterRecovery/DatabaseFileInfoTests.cs | 12 +- .../DisasterRecoveryFileValidatorUnitTests.cs | 8 +- .../LocalizedPropertyInfoTests.cs | 10 +- .../RestoreOptionsHelperTests.cs | 174 +++--- .../EditData/CellUpdateTests.cs | 134 +++-- .../EditData/EditCellTests.cs | 12 +- .../EditData/FilterMetadataTest.cs | 16 +- .../EditData/RowCreateTests.cs | 202 +++---- .../EditData/RowDeleteTests.cs | 61 +- .../EditData/RowEditBaseTests.cs | 69 +-- .../EditData/RowUpdateTests.cs | 150 ++--- .../EditData/ServiceIntegrationTests.cs | 91 ++- .../EditData/SessionTests.cs | 231 ++++--- .../Extensibility/ExtensionTests.cs | 24 +- .../Extensibility/ServiceProviderTests.cs | 30 +- .../FileBrowser/FileBrowserTests.cs | 12 +- .../BinaryQueryExpressionFormatterTests.cs | 18 +- .../CommonTableExpressionFormatterTests.cs | 28 +- .../CreateProcedureFormatterTests.cs | 40 +- .../Formatter/CreateTableFormatterTests.cs | 40 +- .../Formatter/CreateViewFormatterTests.cs | 24 +- .../Formatter/FormatterSettingsTests.cs | 32 +- .../Formatter/FormatterUnitTestBase.cs | 2 +- .../Formatter/GeneralFormatterTests.cs | 18 +- .../Formatter/InsertFormatterTests.cs | 26 +- .../SqlSelectStatementFormatterTests.cs | 28 +- .../Formatter/TSqlFormatterServiceTests.cs | 39 +- .../ExternalLanguageOperationTests.cs | 16 +- .../LanguageServer/AutocompleteTests.cs | 40 +- .../LanguageServer/BindingQueueTests.cs | 28 +- .../LanguageServer/CompletionServiceTest.cs | 12 +- .../LanguageServer/InteractionMetricsTest.cs | 32 +- .../LanguageServer/LanguageServiceTestBase.cs | 2 +- .../LanguageServer/LanguageServiceTests.cs | 54 +- .../LanguageServer/PeekDefinitionTests.cs | 68 +-- .../LanguageServer/SqlCompletionItemTests.cs | 168 +++--- .../Messaging/MessageDispatcherTests.cs | 10 +- .../Messaging/MessageReaderTests.cs | 53 +- .../Messaging/MessageWriterTests.cs | 18 +- ...oft.SqlTools.ServiceLayer.UnitTests.csproj | 6 +- .../ObjectExplorer/NodePathGeneratorTests.cs | 30 +- .../ObjectExplorer/NodeTests.cs | 101 ++-- .../ObjectExplorerServiceTests.cs | 66 +- .../ServerVersionHelperTests.cs | 42 +- .../ObjectExplorer/SmoQueryModelTests.cs | 22 +- .../ObjectExplorer/UsersChildFactoryTests.cs | 10 +- .../Profiler/ProfilerServiceTests.cs | 13 +- .../Profiler/ProfilerSessionTests.cs | 24 +- .../Profiler/ProfilerTestObjects.cs | 2 +- .../QueryExecution/CancelTests.cs | 24 +- .../SaveAsCsvFileStreamWriterTests.cs | 94 +-- .../SaveAsExcelFileStreamWriterHelperTests.cs | 54 +- .../SaveAsJsonFileStreamWriterTests.cs | 30 +- ...erviceBufferFileStreamReaderWriterTests.cs | 244 ++++---- .../QueryExecution/DbCellValueTests.cs | 18 +- .../QueryExecution/DisposeTests.cs | 16 +- .../QueryExecution/Execution/BatchTests.cs | 135 ++--- .../Execution/DbColumnWrapperTests.cs | 6 +- .../QueryExecution/Execution/QueryTests.cs | 84 +-- .../Execution/ResultSetTests.cs | 138 ++--- .../Execution/ServiceIntegrationTests.cs | 119 ++-- .../QueryExecution/ExecutionPlanTests.cs | 51 +- .../QueryExecution/SaveResults/BatchTests.cs | 8 +- .../QueryExecution/SaveResults/QueryTests.cs | 8 +- .../SaveResults/ResultSetTests.cs | 18 +- .../SaveResults/SerializationServiceTests.cs | 32 +- .../SaveResults/ServiceIntegrationTests.cs | 26 +- .../QueryExecution/SettingsTests.cs | 36 +- .../QueryExecution/SpecialActionTests.cs | 26 +- .../QueryExecution/SubsetTests.cs | 73 +-- .../Azure/AzureAuthenticationManagerTest.cs | 16 +- .../AzureDatabaseDiscoveryProviderTest.cs | 12 +- .../Azure/AzureResourceWrapperTest.cs | 10 +- .../AzureSqlServerDiscoveryProviderTest.cs | 6 +- .../Azure/AzureSubscriptionContextTest.cs | 6 +- .../ResourceProvider/DependencyManagerTest.cs | 34 +- .../ResourceProvider/ExceptionUtilTest.cs | 22 +- .../FirewallErrorParserTest.cs | 17 +- .../FirewallRuleServiceTest.cs | 70 +-- .../ResourceProviderServiceTests.cs | 24 +- .../ResourceProvider/ServiceManagerTest.cs | 16 +- .../SchemaCompare/SchemaCompareTests.cs | 37 +- .../ScriptingExtensionMethodsTests.cs | 4 +- .../Scripting/ScriptingObjectMatcherTests.cs | 96 +-- .../ServiceHost/AsyncLockTests.cs | 16 +- .../ServiceHost/AsyncQueueTests.cs | 14 +- .../ServiceHost/CapabilitiesTests.cs | 4 +- .../JsonRpcMessageSerializerTests.cs | 16 +- .../ServiceHost/LoggerTests.cs | 36 +- .../ServiceHost/ScriptFileTests.cs | 74 +-- .../ServiceHost/ServiceHostTests.cs | 4 +- .../ServiceHost/SrTests.cs | 26 +- .../GenerateScriptOperationTests.cs | 12 +- .../SqlContext/SettingsTests.cs | 10 +- .../TaskServices/SqlTaskTests.cs | 60 +- .../TaskServices/TaskManagerTests.cs | 14 +- .../TaskServices/TaskServiceTests.cs | 10 +- .../Utility/CommandOptionsTests.cs | 38 +- .../Utility/LongListTests.cs | 126 ++-- .../Utility/SrTests.cs | 4 +- .../Utility/TaskExtensionTests.cs | 34 +- .../Utility/TestUtils.cs | 4 +- .../Utility/TextUtilitiesTests.cs | 14 +- .../Utility/ValidateTests.cs | 10 +- .../UtilityTests/FromSqlScriptTests.cs | 117 ++-- .../UtilityTests/ToSqlScriptTests.cs | 152 ++--- .../Workspace/WorkspaceTests.cs | 48 +- 205 files changed, 4146 insertions(+), 4329 deletions(-) diff --git a/Packages.props b/Packages.props index 3c26efa4..dcd131c0 100644 --- a/Packages.props +++ b/Packages.props @@ -23,6 +23,8 @@ + + diff --git a/azure-pipelines/build.yml b/azure-pipelines/build.yml index d4c87d7d..b26a3526 100644 --- a/azure-pipelines/build.yml +++ b/azure-pipelines/build.yml @@ -1,5 +1,5 @@ pool: - name: Hosted VS2017 + vmImage: 'windows-latest' demands: - Cmd - npm diff --git a/src/Microsoft.SqlTools.ManagedBatchParser/BatchParser/ExecutionEngineCode/Batch.cs b/src/Microsoft.SqlTools.ManagedBatchParser/BatchParser/ExecutionEngineCode/Batch.cs index 2321becf..1e1c6c5f 100644 --- a/src/Microsoft.SqlTools.ManagedBatchParser/BatchParser/ExecutionEngineCode/Batch.cs +++ b/src/Microsoft.SqlTools.ManagedBatchParser/BatchParser/ExecutionEngineCode/Batch.cs @@ -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 diff --git a/src/Microsoft.SqlTools.ServiceLayer/Microsoft.SqlTools.ServiceLayer.csproj b/src/Microsoft.SqlTools.ServiceLayer/Microsoft.SqlTools.ServiceLayer.csproj index 2ca2cd79..9007d1d9 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/Microsoft.SqlTools.ServiceLayer.csproj +++ b/src/Microsoft.SqlTools.ServiceLayer/Microsoft.SqlTools.ServiceLayer.csproj @@ -20,7 +20,7 @@ - + @@ -45,4 +45,23 @@ + + + + + + + diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/CommonObjects.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/CommonObjects.cs index 0e030e74..3ba56157 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/CommonObjects.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/CommonObjects.cs @@ -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); diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/Contracts/Utilities/FlagsIntConverterTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/Contracts/Utilities/FlagsIntConverterTests.cs index a67b3630..9e369e5e 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/Contracts/Utilities/FlagsIntConverterTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/Contracts/Utilities/FlagsIntConverterTests.cs @@ -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(); 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(); 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 diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/Contracts/Utilities/FlagsStringConverterTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/Contracts/Utilities/FlagsStringConverterTests.cs index aaa53970..a73f2b10 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/Contracts/Utilities/FlagsStringConverterTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/Contracts/Utilities/FlagsStringConverterTests.cs @@ -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(); 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(); 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 diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/ExtensibilityTests/ServiceProviderTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/ExtensibilityTests/ServiceProviderTests.cs index 93aa311f..f602cbe3 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/ExtensibilityTests/ServiceProviderTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/ExtensibilityTests/ServiceProviderTests.cs @@ -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(() => provider.GetService()); } - [Fact] + [Test] public void GetServicesShouldReturnEmptyIfNoServicesRegistered() { // Given no service regisstered // When I call GetService var services = provider.GetServices(); - // 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(); - 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(); - Assert.Equal(service, returnedServices.Single()); + Assert.AreEqual(service, returnedServices.Single()); } - [Fact] + [Test] public void RegisterServiceProviderShouldThrowIfServiceIsIncompatible() { MyProviderService service = new MyProviderService(); Assert.Throws(() => 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(() => provider.RegisterSingleService(service)); } - [Fact] + [Test] public void RegisterShouldThrowIfServiceAlreadyRegistered() { MyProviderService service = new MyProviderService(); @@ -95,7 +98,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.ExtensibilityTests Assert.Throws(() => provider.Register(() => service.AsSingleItemEnumerable())); } - [Fact] + [Test] public void RegisterShouldThrowIfServicesAlreadyRegistered() { provider.Register(() => new [] { new MyProviderService(), new MyProviderService() }); diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/Microsoft.SqlTools.Hosting.UnitTests.csproj b/test/Microsoft.SqlTools.Hosting.UnitTests/Microsoft.SqlTools.Hosting.UnitTests.csproj index 43412e5a..01a43f55 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/Microsoft.SqlTools.Hosting.UnitTests.csproj +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/Microsoft.SqlTools.Hosting.UnitTests.csproj @@ -7,8 +7,9 @@ - - + + + diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/EventContextTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/EventContextTests.cs index 0f816107..8efd32a4 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/EventContextTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/EventContextTests.cs @@ -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"); } } } \ No newline at end of file diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/JsonRpcHostTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/JsonRpcHostTests.cs index 402d6160..0122d04d 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/JsonRpcHostTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/JsonRpcHostTests.cs @@ -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(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(() => 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(() => 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, 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>>(); @@ -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(() => jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object)); + Assert.That(() => jh.SetAsyncRequestHandler(CommonObjects.RequestType, requestHandler.Object), Throws.InstanceOf(), "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(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(() => 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(() => 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>(); @@ -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>(); @@ -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(() => jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object)); + Assert.That(() => jh.SetAsyncEventHandler(CommonObjects.EventType, eventHandler.Object), Throws.InstanceOf(), "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(() => 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(() => jh.SendRequest(CommonObjects.RequestType, CommonObjects.TestMessageContents.DefaultInstance)); + Assert.ThrowsAsync(() => 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 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(() => jh.DispatchMessage(CommonObjects.RequestMessage)); + Assert.ThrowsAsync(() => 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(() => jh.DispatchMessage(CommonObjects.RequestMessage)); + Assert.ThrowsAsync(() => 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(() => jh.DispatchMessage(CommonObjects.ResponseMessage)); + Assert.ThrowsAsync(() => 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(() => jh.DispatchMessage(CommonObjects.EventMessage)); + Assert.ThrowsAsync(() => 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(() => jh.DispatchMessage(CommonObjects.EventMessage)); + Assert.ThrowsAsync(() => 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(Stream.Null, null); mr.SetupSequence(o => o.ReadMessage()) .ReturnsAsync(CommonObjects.RequestMessage) - .Returns(Task.FromException(new EndOfStreamException())); - - // If: I start the input consumption loop + .Returns(Task.FromException(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("code")); + Assert.That(outgoing.Select(m => (m.MessageType, m.Id, m.Contents.Value("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()), 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(() => 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(() => 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 diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageReaderTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageReaderTests.cs index 1c748dff..86318947 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageReaderTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageReaderTests.cs @@ -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(() => 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(() => mr.ReadMessage()); + Assert.ThrowsAsync(() => 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(() => mr.ReadMessage()); + Assert.ThrowsAsync(() => 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(() => mr.ReadMessage()); + Assert.ThrowsAsync(() => 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(() => mr.ReadMessage()); + Assert.ThrowsAsync(() => mr.ReadMessage()); // If: I read another, valid, message var msg = await mr.ReadMessage(); diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageTests.cs index 3f0366b6..6dbbdea4 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageTests.cs @@ -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 expectedProperties = new List {"jsonrpc"}; - Assert.Equal("2.0", jObject["jsonrpc"]); + Assert.AreEqual("2.0", jObject["jsonrpc"].Value()); // 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()); 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()); 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 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(() => 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(() => 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(() => 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(); // 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(); // 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(() => m.GetTypedContents()); + Assert.Throws(() => m.GetTypedContents()); } #endregion diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageWriterTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageWriterTests.cs index f62d673d..d9f93a96 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageWriterTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/MessageWriterTests.cs @@ -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(() => mw.WriteMessage(null)); + var mw = new MessageWriter(Stream.Null); + Assert.ThrowsAsync(() => mw.WriteMessage(null)); } - [Theory] - [MemberData(nameof(WriteMessageData))] + [TestCaseSource(nameof(WriteMessageData))] public async Task WriteMessage(object contents, Dictionary 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>(outputParts[1]); diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/RequestContextTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/RequestContextTests.cs index afcad885..ceda755d 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/RequestContextTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/ProtocolTests/RequestContextTests.cs @@ -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.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.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.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(); - 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.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(); - 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(); + Assert.AreEqual(e.HResult, contents.Code); + Assert.AreEqual(errorMessage, contents.Message); } diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/ServiceHostTests/ExtensibleServiceHostTest.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/ServiceHostTests/ExtensibleServiceHostTest.cs index 32c8e46f..de5c110f 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/ServiceHostTests/ExtensibleServiceHostTest.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/ServiceHostTests/ExtensibleServiceHostTest.cs @@ -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(() => 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(() => 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(jh.protocolChannel); + Assert.That(jh.protocolChannel, Is.InstanceOf(), "The underlying rpc host should be using the stdio server channel "); Assert.False(jh.protocolChannel.IsConnected); } } diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/ServiceHostTests/ServiceHostTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/ServiceHostTests/ServiceHostTests.cs index ef0253e7..0db35204 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/ServiceHostTests/ServiceHostTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/ServiceHostTests/ServiceHostTests.cs @@ -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(jh.protocolChannel); + Assert.That(jh.protocolChannel, Is.InstanceOf(), "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(() => 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 diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/UtilityTests/AsyncLockTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/UtilityTests/AsyncLockTests.cs index c34c3404..42cbafce 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/UtilityTests/AsyncLockTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/UtilityTests/AsyncLockTests.cs @@ -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 lockOne = asyncLock.LockAsync(); Task 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); } } } diff --git a/test/Microsoft.SqlTools.Hosting.UnitTests/UtilityTests/LoggerTests.cs b/test/Microsoft.SqlTools.Hosting.UnitTests/UtilityTests/LoggerTests.cs index 126d6ac3..4fc6a744 100644 --- a/test/Microsoft.SqlTools.Hosting.UnitTests/UtilityTests/LoggerTests.cs +++ b/test/Microsoft.SqlTools.Hosting.UnitTests/UtilityTests/LoggerTests.cs @@ -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] /// /// Logger test cases /// @@ -20,7 +21,7 @@ namespace Microsoft.SqlTools.Hosting.UnitTests.UtilityTests /// /// Test to verify that the logger initialization is generating a valid file /// - [Fact] + [Test] public void LoggerDefaultFile() { // delete any existing log files from the current directory diff --git a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/AssemblyInfo.cs b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/AssemblyInfo.cs index 8f639b84..4e046a4e 100644 --- a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/AssemblyInfo.cs +++ b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/AssemblyInfo.cs @@ -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)] \ No newline at end of file +[assembly: NUnit.Framework.NonParallelizable] \ No newline at end of file diff --git a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserSqlCmdTests.cs b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserSqlCmdTests.cs index 76073b9d..6c24ce72 100644 --- a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserSqlCmdTests.cs +++ b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserSqlCmdTests.cs @@ -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(); diff --git a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserTests.cs b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserTests.cs index 562701e7..37f26115 100644 --- a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserTests.cs +++ b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserTests.cs @@ -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. /// - [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.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(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(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(result, ScriptExecutionResult.Cancel); + Assert.AreEqual(ScriptExecutionResult.Cancel, result); } // /// /// Verify whether lexer can consume token for SqlCmd variable /// - [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(() => 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(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.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 /// /// Verify whether the batchParser execute SqlCmd successfully /// - [Fact] + [Test] public void VerifyRunSqlCmd() { using (ExecutionEngine executionEngine = new ExecutionEngine()) @@ -365,7 +359,7 @@ GO"; /// /// Verify whether the batchParser parsed :connect command successfully /// - [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"; /// /// Verify whether the batchParser parsed :on error successfully /// - [Fact] + [Test] public void VerifyOnErrorSqlCmd() { using (ExecutionEngine executionEngine = new ExecutionEngine()) @@ -443,7 +444,7 @@ GO"; /// /// Verify whether the batchParser parses Include command i.e. :r successfully /// - [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(); 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(inputText, roundtripTextBuilder.ToString()); + Assert.AreEqual(inputText, roundtripTextBuilder.ToString()); } } } diff --git a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserWrapperTests.cs b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserWrapperTests.cs index 4dccbf96..a658ab11 100644 --- a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserWrapperTests.cs +++ b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/BatchParser/BatchParserWrapperTests.cs @@ -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); } } } diff --git a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.csproj b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.csproj index 155f55da..60cde6cc 100644 --- a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.csproj +++ b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.csproj @@ -19,8 +19,9 @@ - - + + + diff --git a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/TSQLExecutionEngine/ExecutionEngineTest.cs b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/TSQLExecutionEngine/ExecutionEngineTest.cs index 11e3618c..7dc4c41d 100644 --- a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/TSQLExecutionEngine/ExecutionEngineTest.cs +++ b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/TSQLExecutionEngine/ExecutionEngineTest.cs @@ -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] /// ///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 /// - 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 /// ///A test for a simple SQL script /// - [Fact] + [Test] public void ExecutionEngineTest_SimpleTest() { string sqlStatement = "SELECT * FROM sysobjects"; @@ -97,15 +94,15 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn List 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); } /// /// Test with a valid script using default execution condition /// - [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 batchScripts = executor.BatchScripts; ExecuteSqlBatch(batchScripts, connection); - Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult); + Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); } // // Test with multiple valid scripts in multiple batches // - [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 batchScripts = executor.BatchScripts; ExecuteSqlBatch(batchScripts, connection); - Assert.Equal(ScriptExecutionResult.Success, executor.ExecutionResult); + Assert.AreEqual(ScriptExecutionResult.Success, executor.ExecutionResult); Assert.True(CompareTwoIntLists(executor.ResultCountQueue, expResultCounts)); } /// /// Test with SQL comment /// - [Fact] + [Test] public void ExecutionEngineTest_TestComment() { string sqlStatement = "/*test comments*/"; @@ -167,7 +164,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn List 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 /// /// Test with a invalid query using the default execution condition /// - [Fact] + [Test] public void ExecutionEngineTest_DefaultCondition_InvalidScript() { string sqlStatement = "select ** from sysobjects"; @@ -192,17 +189,17 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn List 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); } /// /// Test with an invalid query using a defined execution condition /// - [Fact] + [Test] public void ExecutionEngineTest_InvalidScriptWithCondition() { string sqlStatement = "select * from authors"; @@ -218,7 +215,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn List 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 /// /// Test with multiple invalid scripts in multiple batches /// - [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 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 /// /// Test with invalid scripts within a single batch /// - [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 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 /// /// Test with mixed valid and invalid scripts /// - [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 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 /// /// Test HaltOnError execution condition /// - [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 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 /// /// HaltOnError with a single batch /// - [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 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); } /// /// Test ParseOnly execution condition with valid scripts /// - [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); } /// /// Test HaltOnError execution condition with invalid scripts /// - [Fact] + [Test] public void ExecutionEngineTest_ParseOnly_InvalidScript() { string sqlStatement = "select ** from authors"; @@ -403,7 +402,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn List 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 /// /// Parse script only without transaction wrapper /// - [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); } /// @@ -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); } /// /// Test with invalid connection /// - [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 /// /// Test with multiple conditions true /// - [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 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 /// /// Test with SQL commands /// - [Fact] + [Test] public void ExecutionEngineTest_SQLCmds() { string[] sqlStatements = { @@ -537,7 +536,7 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn /// /// Test synchronous cancel /// - [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); } /// /// Test asynchronous cancel /// - [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); } /// @@ -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); } /// /// Test async cancel when the execution is done /// - [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); } /// /// Test multiple threads of execution engine with cancel operation /// - [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 diff --git a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/TSQLExecutionEngine/TestExecutor.cs b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/TSQLExecutionEngine/TestExecutor.cs index 63f40769..cbaff188 100644 --- a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/TSQLExecutionEngine/TestExecutor.cs +++ b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/TSQLExecutionEngine/TestExecutor.cs @@ -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 resultCounts = new List(); private List sqlMessages = new List(); - private List errorMessage = new List(); + private readonly List errorMessage = new List(); private List batchFinished = new List(); private static ScriptExecutionResult execResult = ScriptExecutionResult.All; private static List batchScripts = new List(); 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; + } } /// @@ -333,11 +338,12 @@ namespace Microsoft.SqlTools.ManagedBatchParser.IntegrationTests.TSQLExecutionEn /// /// /// - 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); } /// @@ -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 diff --git a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/Utility/LiveConnectionHelper.cs b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/Utility/LiveConnectionHelper.cs index a83beea8..574ffbb7 100644 --- a/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/Utility/LiveConnectionHelper.cs +++ b/test/Microsoft.SqlTools.ManagedBatchParser.IntegrationTests/Utility/LiveConnectionHelper.cs @@ -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 { diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Admin/DatabaseAdminTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Admin/DatabaseAdminTests.cs index 0a81a287..7f00b52e 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Admin/DatabaseAdminTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Admin/DatabaseAdminTests.cs @@ -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 /// /// Validate creating a database with valid input /// - // [Fact] - public async void CreateDatabaseWithValidInputTest() + // [Test] + public async Task CreateDatabaseWithValidInputTest() { var result = GetLiveAutoCompleteTestObjects(); var requestContext = new Mock>(); @@ -68,8 +68,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.AdminServices /// /// Get a default database info object /// - // [Fact] - public async void GetDefaultDatebaseInfoTest() + // [Test] + public async Task GetDefaultDatebaseInfoTest() { var result = GetLiveAutoCompleteTestObjects(); var requestContext = new Mock>(); @@ -89,8 +89,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.AdminServices /// Get database info test /// /// 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>(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentAlertTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentAlertTests.cs index 82c586e4..79d8ef57 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentAlertTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentAlertTests.cs @@ -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 /// /// Verify default agent/alerts handlers /// - [Fact] + [Test] public async Task TestHandleAgentAlertsRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -42,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// Verify the default "create agent alert" request handler with valid parameters /// - [Fact] + [Test] public async Task TestHandleCreateAgentAlertsRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -86,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// Verify the default "update agent alert" request handler with valid parameters /// - [Fact] + [Test] public async Task TestHandleUpdateAgentAlertsRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentJobStepTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentJobStepTests.cs index 225ba692..7b24064e 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentJobStepTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentJobStepTests.cs @@ -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 /// /// TestHandleCreateAgentJobStepRequest /// - [Fact] + [Test] public async Task TestHandleCreateAgentJobStepRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleUpdateAgentJobStepRequest /// - [Fact] + [Test] public async Task TestHandleUpdateAgentJobStepRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -71,7 +71,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleDeleteAgentJobRequest /// - [Fact] + [Test] public async Task TestHandleDeleteAgentJobStepRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentJobTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentJobTests.cs index 069a57f2..848910fc 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentJobTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentJobTests.cs @@ -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 /// /// TestHandleCreateAgentJobRequest /// - [Fact] + [Test] public async Task TestHandleCreateAgentJobRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -43,7 +43,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleUpdateAgentJobRequest /// - [Fact] + [Test] public async Task TestHandleUpdateAgentJobRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -66,7 +66,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleDeleteAgentJobRequest /// - [Fact] + [Test] public async Task TestHandleDeleteAgentJobRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -86,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestAgentJobDefaultsRequest /// - [Fact] + [Test] public async Task TestAgentJobDefaultsRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentNotebookTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentNotebookTests.cs index 28f0d717..88257a5d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentNotebookTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentNotebookTests.cs @@ -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 /// /// Test case for fetch notebook jobs Request Handler /// - [Fact] + [Test] public async Task TestHandleAgentNotebooksRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -40,16 +40,16 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// Tests the create job helper function /// - [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 /// /// Tests the create job request handler with an invalid file path /// - [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(p => p.Success == false))); - Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); + Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); } } /// /// creating a job with duplicate name /// - [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 /// /// Tests the create notebook job handler /// - [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(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 /// /// Tests the delete notebook job handler /// - [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>(); deleteNotebookContext.Setup(x => x.SendResult(It.IsAny())).Returns(Task.FromResult(new object())); @@ -161,15 +161,15 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent }, deleteNotebookContext.Object); deleteNotebookContext.Verify(x => x.SendResult(It.Is(p => p.Success == true))); //verifying if the job is deleted - Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); + Assert.AreEqual(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook)); } } /// /// deleting a existing notebook job /// - [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 /// /// updating a non existing notebook job /// - [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 /// /// update notebook handler with garbage path /// - [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>(); updateNotebookContext.Setup(x => x.SendResult(It.IsAny())).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); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentOperatorTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentOperatorTests.cs index 9d052f97..9b03a3fe 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentOperatorTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentOperatorTests.cs @@ -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 /// /// Verify default agent/operators handlers /// - [Fact] + [Test] public async Task TestHandleAgentOperatorsRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -41,7 +41,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// Verify the default "create agent alert" request handler with valid parameters /// - [Fact] + [Test] public async Task TestHandleCreateAgentOperatorRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -63,7 +63,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleUpdateAgentOperatorRequest /// - [Fact] + [Test] public async Task TestHandleUpdateAgentOperatorRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -87,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleDeleteAgentOperatorRequest /// - [Fact] + [Test] public async Task TestHandleDeleteAgentOperatorRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentProxyTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentProxyTests.cs index 291dde38..348cd8d3 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentProxyTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentProxyTests.cs @@ -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 /// /// Verify default agent/proxies handlers /// - [Fact] + [Test] public async Task TestHandleAgentProxiesRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleCreateAgentProxyRequest /// - [Fact] + [Test] public async Task TestHandleCreateAgentProxyRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// Verify the default "update agent alert" request handler with valid parameters /// - [Fact] + [Test] public async Task TestHandleUpdateAgentProxyRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -96,7 +96,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleDeleteAgentProxyRequest /// - [Fact] + [Test] public async Task TestHandleDeleteAgentProxyRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentScheduleTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentScheduleTests.cs index 3fbc6c77..7c7bbb92 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentScheduleTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentScheduleTests.cs @@ -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 /// /// HandleAgentSchedulesRequest /// - [Fact] + [Test] public async Task HandleAgentSchedulesRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleCreateAgentScheduleRequest /// - [Fact] + [Test] public async Task TestHandleCreateAgentScheduleRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleUpdateAgentScheduleRequest /// - [Fact] + [Test] public async Task TestHandleUpdateAgentScheduleRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -95,7 +95,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// TestHandleDeleteAgentScheduleRequest /// - [Fact] + [Test] public async Task TestHandleDeleteAgentScheduleRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentServiceTests.cs index 1e670d35..6094e8a8 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Agent/AgentServiceTests.cs @@ -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 /// /// Verify that a start profiling request starts a profiling session /// - [Fact] + [Test] public async Task TestHandleAgentJobsRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -44,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Agent /// /// Verify that a job history request returns the job history /// - [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()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/AssemblyInfo.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/AssemblyInfo.cs index 70421c18..e87e98ec 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/AssemblyInfo.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/AssemblyInfo.cs @@ -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] diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Cms/CmsServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Cms/CmsServiceTests.cs index 615dc71d..2c8750b5 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Cms/CmsServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Cms/CmsServiceTests.cs @@ -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(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Connection/ConnectionServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Connection/ConnectionServiceTests.cs index 76efb1e8..c9b3e3b4 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Connection/ConnectionServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Connection/ConnectionServiceTests.cs @@ -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 /// 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 /// /// Test HandleGetConnectionStringRequest /// - [Fact] - public async void GetCurrentConnectionStringTest() + [Test] + public async Task GetCurrentConnectionStringTest() { // If we make a connection to a live database ConnectionService service = ConnectionService.Instance; diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Connection/ReliableConnectionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Connection/ReliableConnectionTests.cs index fe52711e..e5a069bf 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Connection/ReliableConnectionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Connection/ReliableConnectionTests.cs @@ -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((s) => { throw new RetryLimitExceededException(); }, token), default(int)); + Assert.AreEqual(default(int), policy.ExecuteAction((s) => { throw new RetryLimitExceededException(); }, token)); // execute an action that throws a retry limit exeception with an inner exception Assert.Throws(() => @@ -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 /// /// Test ReliableConnectionHelper.GetDefaultDatabaseFilePath() /// - [Fact] + [Test] public void TestGetDefaultDatabaseFilePath() { @@ -293,7 +293,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// Test ReliableConnectionHelper.GetServerVersion() /// - [Fact] + [Test] public void TestGetServerVersion() { using (var connection = CreateTestConnection()) @@ -324,7 +324,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// Tests ReliableConnectionHelper.GetCompleteServerName() /// - [Fact] + [Test] public void TestGetCompleteServerName() { string name = ReliableConnectionHelper.GetCompleteServerName(@".\SQL2008"); @@ -337,7 +337,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// Tests ReliableConnectionHelper.IsDatabaseReadonly() /// - [Fact] + [Test] public void TestIsDatabaseReadonly() { var connectionBuilder = CreateTestConnectionStringBuilder(); @@ -350,7 +350,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// /// Tests ReliableConnectionHelper.IsDatabaseReadonly() with null builder parameter /// - [Fact] + [Test] public void TestIsDatabaseReadonlyWithNullBuilder() { Assert.Throws(() => ReliableConnectionHelper.IsDatabaseReadonly(null, null)); @@ -359,7 +359,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// Verify ANSI_NULL and QUOTED_IDENTIFIER settings can be set and retrieved for a session /// - [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 /// /// Test that the retry policy factory constructs all possible types of policies successfully. /// - [Fact] + [Test] public void RetryPolicyFactoryConstructsPoliciesSuccessfully() { RunIfWrapper.RunIfWindows(() => @@ -468,7 +468,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// ReliableConnectionHelper.IsCloud() should be false for a local server /// - [Fact] + [Test] public void TestIsCloudIsFalseForLocalServer() { using (var connection = CreateTestConnection()) @@ -483,7 +483,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// Tests that ReliableConnectionHelper.OpenConnection() opens a connection if it is closed /// - [Fact] + [Test] public void TestOpenConnectionOpensConnection() { using (var connection = CreateTestConnection()) @@ -499,7 +499,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// Tests that ReliableConnectionHelper.ExecuteNonQuery() runs successfully /// - [Fact] + [Test] public void TestExecuteNonQuery() { var result = ReliableConnectionHelper.ExecuteNonQuery( @@ -516,7 +516,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// Test that TryGetServerVersion() gets server information /// - [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); } /// /// Test that TryGetServerVersion() fails with invalid connection string /// - [Fact] + [Test] public void TestTryGetServerVersionInvalidConnectionString() { RunIfWrapper.RunIfWindows(() => @@ -544,7 +543,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// Validate ambient static settings /// - [Fact] + [Test] public void AmbientSettingsStaticPropertiesTest() { var defaultSettings = AmbientSettings.DefaultSettings; @@ -578,7 +577,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection /// /// Validate ambient settings populate /// - [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(() => 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) => { }; diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DacFx/DacFxserviceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DacFx/DacFxserviceTests.cs index 4d609988..cb7e3a8b 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DacFx/DacFxserviceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DacFx/DacFxserviceTests.cs @@ -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 /// /// Verify the export bacpac request /// - [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 /// /// Verify the import bacpac request /// - [Fact] - public async void ImportBacpac() + [Test] + public async Task ImportBacpac() { // first export a bacpac var result = GetLiveAutoCompleteTestObjects(); @@ -150,8 +150,8 @@ RETURN 0 /// /// Verify the extract dacpac request /// - [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 /// /// Verify the extract request to create Sql file /// - [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 /// /// Verify the extract request to create a Flat file structure /// - [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 /// /// Verify the deploy dacpac request /// - [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; } /// /// Verify the export request being cancelled /// - [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 /// /// Verify the generate deploy script request /// - [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 /// /// Verify the generate deploy plan request /// - [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 // /// Verify that SqlCmdVars are set correctly for a deploy request /// - [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 // /// Verify that SqlCmdVars are set correctly for a generate script request /// - [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 /// - [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 // /// Verify that options are set correctly for a generate script request /// - [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 // /// Verify that options can get retrieved from publish profile /// - [Fact] - public async void GetOptionsFromProfile() + [Test] + public async Task GetOptionsFromProfile() { DeploymentOptions expectedResults = new DeploymentOptions() { @@ -729,8 +733,8 @@ RETURN 0 // /// Verify that default options are returned if a profile doesn't specify any options /// - [Fact] - public async void GetOptionsFromProfileWithoutOptions() + [Test] + public async Task GetOptionsFromProfileWithoutOptions() { DeploymentOptions expectedResults = new DeploymentOptions(); expectedResults.ExcludeObjectTypes = null; diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/BackupServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/BackupServiceTests.cs index bc044b62..b15cfb7b 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/BackupServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/BackupServiceTests.cs @@ -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 /// /// 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'; "; /// /// Create simple backup test /// - [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'; "; /// /// Test creating backup with advanced options set. /// - [Fact] + [Test] public void CreateBackupWithAdvancedOptionsTest() { DisasterRecoveryService service = new DisasterRecoveryService(); @@ -190,7 +190,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; /// /// Test creating backup with advanced options set. /// - [Fact] + [Test] public void ScriptBackupWithAdvancedOptionsTest() { DisasterRecoveryService service = new DisasterRecoveryService(); @@ -245,7 +245,7 @@ CREATE CERTIFICATE {1} WITH SUBJECT = 'Backup Encryption Certificate'; "; /// /// Test the correct script generation for different backup action types /// - [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); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/DisasterRecoveryFileValidatorTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/DisasterRecoveryFileValidatorTests.cs index 9790426e..167666fc 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/DisasterRecoveryFileValidatorTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/DisasterRecoveryFileValidatorTests.cs @@ -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 /// 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"); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/RestoreDatabaseServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/RestoreDatabaseServiceTests.cs index 2564bf8e..90df9378 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/RestoreDatabaseServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/RestoreDatabaseServiceTests.cs @@ -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)) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/FileBrowser/FileBrowserServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/FileBrowser/FileBrowserServiceTests.cs index 4193e094..b93639cb 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/FileBrowser/FileBrowserServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/FileBrowser/FileBrowserServiceTests.cs @@ -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(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(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(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); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageExtensibility/ExternalLanguageServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageExtensibility/ExternalLanguageServiceTests.cs index ceb82afc..3631f5e4 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageExtensibility/ExternalLanguageServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageExtensibility/ExternalLanguageServiceTests.cs @@ -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(r => result = r).AddErrorHandling(null); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageServer/LanguageServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageServer/LanguageServiceTests.cs index 7ad16dea..79b3b868 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageServer/LanguageServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageServer/LanguageServiceTests.cs @@ -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 /// /// Test the service initialization code path and verify nothing throws /// - [Fact] + [Test] public void ServiceInitialization() { try @@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer /// /// Test the service initialization code path and verify nothing throws /// - //[Fact] + //[Test] public void PrepopulateCommonMetadata() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -89,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer /// /// This test tests auto completion /// - [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 /// - [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. /// - [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 /// /// Test overwriting the binding queue context /// - [Fact] + [Test] public void OverwriteBindingContext() { var result = LiveConnectionHelper.InitLiveConnectionInfo(); @@ -279,7 +279,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer /// /// Verifies that clearing the Intellisense cache correctly refreshes the cache with new info from the DB. /// - [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 /// - [Fact] + [Test] public async Task HandleRequestToChangeToSqlcmdFile() { diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageServer/PeekDefinitionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageServer/PeekDefinitionTests.cs index c3bd6041..2eec3a64 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageServer/PeekDefinitionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/LanguageServer/PeekDefinitionTests.cs @@ -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"; /// /// Test get definition for a table object with active connection /// - [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"; /// /// Test get definition for a invalid table object with active connection /// - [Fact] + [Test] public void GetTableDefinitionInvalidObjectTest() { // Get live connectionInfo and serverConnection @@ -146,7 +146,7 @@ GO"; /// /// Test get definition for a valid table object with schema and active connection /// - [Fact] + [Test] public void GetTableDefinitionWithSchemaTest() { // Get live connectionInfo and serverConnection @@ -168,7 +168,7 @@ GO"; /// /// Test GetDefinition with an unsupported type(schema - dbo). Expect a error result. /// - [Fact] + [Test] public void GetUnsupportedDefinitionErrorTest() { ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); @@ -187,7 +187,7 @@ GO"; /// /// Get Definition for a object with no definition. Expect a error result /// - [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); } /// /// Test GetDefinition with a forced timeout. Expect a error result. /// - [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); } /// /// Test get definition for a view object with active connection /// - [Fact] + [Test] public void GetValidViewDefinitionTest() { ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(); @@ -293,7 +293,7 @@ GO"; /// /// Test get definition for an invalid view object with no schema name and with active connection /// - [Fact] + [Test] public void GetViewDefinitionInvalidObjectTest() { // Get live connectionInfo and serverConnection @@ -312,7 +312,7 @@ GO"; /// /// Test get definition for a stored procedure object with active connection /// - [Fact] + [Test] public void GetStoredProcedureDefinitionTest() { // Get live connectionInfo and serverConnection @@ -333,7 +333,7 @@ GO"; /// /// Test get definition for a stored procedure object that does not exist with active connection /// - [Fact] + [Test] public void GetStoredProcedureDefinitionFailureTest() { // Get live connectionInfo and serverConnection @@ -352,7 +352,7 @@ GO"; /// /// Test get definition for a stored procedure object with active connection and no schema /// - [Fact] + [Test] public void GetStoredProcedureDefinitionWithoutSchemaTest() { // Get live connectionInfo and serverConnection @@ -372,7 +372,7 @@ GO"; /// /// Test get definition for a scalar valued function object with active connection and explicit schema name. Expect non-null locations /// - [Fact] + [Test] public async Task GetScalarValuedFunctionDefinitionWithSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName); @@ -421,7 +421,7 @@ GO"; /// /// Test get definition for a table valued function object with active connection and explicit schema name. Expect non-null locations /// - [Fact] + [Test] public async Task GetTableValuedFunctionDefinitionWithSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, ScalarValuedFunctionTypeName); @@ -430,7 +430,7 @@ GO"; /// /// Test get definition for a scalar valued function object that doesn't exist with active connection. Expect null locations /// - [Fact] + [Test] public async Task GetScalarValuedFunctionDefinitionWithNonExistentFailureTest() { string objectName = "doesNotExist"; @@ -443,7 +443,7 @@ GO"; /// /// Test get definition for a table valued function object that doesn't exist with active connection. Expect null locations /// - [Fact] + [Test] public async Task GetTableValuedFunctionDefinitionWithNonExistentObjectFailureTest() { string objectName = "doesNotExist"; @@ -455,7 +455,7 @@ GO"; /// /// Test get definition for a scalar valued function object with active connection. Expect non-null locations /// - [Fact] + [Test] public async Task GetScalarValuedFunctionDefinitionWithoutSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(AddTwoFunctionQuery, AddTwoFunctionName, ScalarValuedFunctionTypeName, null); @@ -464,7 +464,7 @@ GO"; /// /// Test get definition for a table valued function object with active connection. Expect non-null locations /// - [Fact] + [Test] public async Task GetTableValuedFunctionDefinitionWithoutSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(ReturnTableTableFunctionQuery, ReturnTableFunctionName, ScalarValuedFunctionTypeName, null); @@ -474,7 +474,7 @@ GO"; /// /// Test get definition for a user defined data type object with active connection and explicit schema name. Expect non-null locations /// - [Fact] + [Test] public async Task GetUserDefinedDataTypeDefinitionWithSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName); @@ -483,7 +483,7 @@ GO"; /// /// Test get definition for a user defined data type object with active connection. Expect non-null locations /// - [Fact] + [Test] public async Task GetUserDefinedDataTypeDefinitionWithoutSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(SsnTypeQuery, SsnTypeName, UserDefinedDataTypeTypeName, null); @@ -492,7 +492,7 @@ GO"; /// /// Test get definition for a user defined data type object that doesn't exist with active connection. Expect null locations /// - [Fact] + [Test] public async Task GetUserDefinedDataTypeDefinitionWithNonExistentFailureTest() { string objectName = "doesNotExist"; @@ -504,7 +504,7 @@ GO"; /// /// Test get definition for a user defined table type object with active connection and explicit schema name. Expect non-null locations /// - [Fact] + [Test] public async Task GetUserDefinedTableTypeDefinitionWithSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName); @@ -513,7 +513,7 @@ GO"; /// /// Test get definition for a user defined table type object with active connection. Expect non-null locations /// - [Fact] + [Test] public async Task GetUserDefinedTableTypeDefinitionWithoutSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(LocationTableTypeQuery, LocationTableTypeName, UserDefinedTableTypeTypeName, null); @@ -522,7 +522,7 @@ GO"; /// /// Test get definition for a user defined table type object that doesn't exist with active connection. Expect null locations /// - [Fact] + [Test] public async Task GetUserDefinedTableTypeDefinitionWithNonExistentFailureTest() { string objectName = "doesNotExist"; @@ -535,7 +535,7 @@ GO"; /// /// Test get definition for a synonym object with active connection and explicit schema name. Expect non-null locations /// - [Fact] + [Test] public async Task GetSynonymDefinitionWithSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName); @@ -545,7 +545,7 @@ GO"; /// /// Test get definition for a Synonym object with active connection. Expect non-null locations /// - [Fact] + [Test] public async Task GetSynonymDefinitionWithoutSchemaNameSuccessTest() { await ExecuteAndValidatePeekTest(TestTableSynonymQuery, TestTableSynonymName, SynonymTypeName, null); @@ -554,7 +554,7 @@ GO"; /// /// Test get definition for a Synonym object that doesn't exist with active connection. Expect null locations /// - [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 /// - [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 /// - [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 /// - [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 /// - [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" /// - [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); } /// @@ -671,7 +671,7 @@ GO"; /// Give that there is a query connection /// Expect database name to be query connection's database name /// - [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 /// - [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"; diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Metadata/MetadataServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Metadata/MetadataServiceTests.cs index 89da35f3..79246398 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Metadata/MetadataServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Metadata/MetadataServiceTests.cs @@ -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 /// /// Verify that the metadata service correctly returns details for user tables /// - [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>(); @@ -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 diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Microsoft.SqlTools.ServiceLayer.IntegrationTests.csproj b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Microsoft.SqlTools.ServiceLayer.IntegrationTests.csproj index a3435d4c..b4d210f7 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Microsoft.SqlTools.ServiceLayer.IntegrationTests.csproj +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Microsoft.SqlTools.ServiceLayer.IntegrationTests.csproj @@ -20,8 +20,9 @@ - - + + + diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/ObjectExplorer/ObjectExplorerServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/ObjectExplorer/ObjectExplorerServiceTests.cs index 99dbbd99..91287dbf 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/ObjectExplorer/ObjectExplorerServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/ObjectExplorer/ObjectExplorerServiceTests.cs @@ -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 /// - [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); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Profiler/ProfilerServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Profiler/ProfilerServiceTests.cs index 7437acba..f54c7686 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Profiler/ProfilerServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Profiler/ProfilerServiceTests.cs @@ -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 /// /// Verify that a start profiling request starts a profiling session /// - //[Fact] + //[Test] public async Task TestHandleStartAndStopProfilingRequests() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -76,7 +76,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Profiler /// /// Verify the profiler service XEvent session factory /// - //[Fact] + //[Test] public void TestCreateXEventSession() { var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/DataStorage/StorageDataReaderTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/DataStorage/StorageDataReaderTests.cs index 95a7157b..f5b35462 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/DataStorage/StorageDataReaderTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/DataStorage/StorageDataReaderTests.cs @@ -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 /// /// Validate GetBytesWithMaxCapacity /// - [Fact] + [Test] public void GetBytesWithMaxCapacityTest() { var storageReader = GetTestStorageDataReader( @@ -47,7 +47,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt /// /// Validate GetCharsWithMaxCapacity /// - [Fact] + [Test] public void GetCharsWithMaxCapacityTest() { var storageReader = GetTestStorageDataReader( @@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt /// /// Validate GetXmlWithMaxCapacity /// - [Fact] + [Test] public void GetXmlWithMaxCapacityTest() { var storageReader = GetTestStorageDataReader( @@ -86,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt /// /// Validate StringWriterWithMaxCapacity Write test /// - [Fact] + [Test] public void StringWriterWithMaxCapacityTest() { var writer = new StorageDataReader.StringWriterWithMaxCapacity(null, 4); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/ExecuteTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/ExecuteTests.cs index 209d7844..69df4248 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/ExecuteTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/ExecuteTests.cs @@ -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) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/SqlCmdExecutionTest.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/SqlCmdExecutionTest.cs index 50ac1da9..f69f29b4 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/SqlCmdExecutionTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/QueryExecution/SqlCmdExecutionTest.cs @@ -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(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceOptionsTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceOptionsTests.cs index 4be874fc..9c289841 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceOptionsTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceOptionsTests.cs @@ -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 /// /// Verify the schema compare request comparing two dacpacs with and without ignore column option /// - [Fact] - public async void SchemaCompareDacpacToDacpacOptions() + [Test] + public async Task SchemaCompareDacpacToDacpacOptions() { await SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions()); } @@ -318,8 +318,8 @@ END /// /// Verify the schema compare request comparing two dacpacs with and excluding table valued functions /// - [Fact] - public async void SchemaCompareDacpacToDacpacObjectTypes() + [Test] + public async Task SchemaCompareDacpacToDacpacObjectTypes() { await SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions()); } @@ -327,8 +327,8 @@ END /// /// Verify the schema compare request comparing two databases with and without ignore column option /// - [Fact] - public async void SchemaCompareDatabaseToDatabaseOptions() + [Test] + public async Task SchemaCompareDatabaseToDatabaseOptions() { await SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions()); } @@ -336,8 +336,8 @@ END /// /// Verify the schema compare request comparing two databases with and excluding table valued functions /// - [Fact] - public async void SchemaCompareDatabaseToDatabaseObjectTypes() + [Test] + public async Task SchemaCompareDatabaseToDatabaseObjectTypes() { await SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions()); } @@ -345,8 +345,8 @@ END /// /// Verify the schema compare script generation comparing dacpac and db with and without ignore column option /// - [Fact] - public async void SchemaCompareGenerateScriptDacpacToDatabaseOptions() + [Test] + public async Task SchemaCompareGenerateScriptDacpacToDatabaseOptions() { await SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabaseWithOptions(Source1, Target1, GetIgnoreColumnOptions(), new DeploymentOptions()); } @@ -354,8 +354,8 @@ END /// /// Verify the schema compare script generation comparing dacpac and db with and excluding table valued function /// - [Fact] - public async void SchemaCompareGenerateScriptDacpacToDatabaseObjectTypes() + [Test] + public async Task SchemaCompareGenerateScriptDacpacToDatabaseObjectTypes() { await SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabaseWithOptions(Source2, Target2, GetExcludeTableValuedFunctionOptions(), new DeploymentOptions()); } @@ -363,7 +363,7 @@ END /// /// Verify the schema compare default creation test /// - [Fact] + [Test] public void ValidateSchemaCompareOptionsDefaultAgainstDacFx() { DeploymentOptions deployOptions = new DeploymentOptions(); @@ -384,8 +384,8 @@ END /// /// Verify the schema compare default creation test /// - [Fact] - public async void ValidateSchemaCompareGetDefaultOptionsCallFromService() + [Test] + public async Task ValidateSchemaCompareGetDefaultOptionsCallFromService() { DeploymentOptions deployOptions = new DeploymentOptions(); var schemaCompareRequestContext = new Mock>(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceTests.cs index 6a0a71a8..f395cee4 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SchemaCompare/SchemaCompareServiceTests.cs @@ -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 /// /// Verify the schema compare request comparing two dacpacs /// - [Fact] - public async void SchemaCompareDacpacToDacpac() + [Test] + public async Task SchemaCompareDacpacToDacpac() { var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); @@ -122,8 +123,8 @@ WITH VALUES /// /// Verify the schema compare request comparing a two databases /// - [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 /// /// Verify the schema compare request comparing a database to a dacpac /// - [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 /// /// Verify the schema compare generate script request comparing a database to a database /// - [Fact] - public async void SchemaCompareGenerateScriptDatabaseToDatabase() + [Test] + public async Task SchemaCompareGenerateScriptDatabaseToDatabase() { var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); var schemaCompareRequestContext = new Mock>(); @@ -249,8 +250,8 @@ WITH VALUES /// /// Verify the schema compare generate script request comparing a dacpac to a database /// - [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 /// /// Verify the schema compare publish changes request comparing a dacpac to a database /// - [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 /// /// Verify the schema compare publish changes request comparing a database to a database /// - [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 /// /// Verify the schema compare Scmp File Save for database endpoints /// - [Fact] - public async void SchemaCompareSaveScmpFileForDatabases() + [Test] + public async Task SchemaCompareSaveScmpFileForDatabases() { var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects(); @@ -465,8 +466,8 @@ WITH VALUES /// /// Verify the schema compare Scmp File Save for dacpac endpoints /// - [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 /// /// Verify the schema compare Scmp File Save for dacpac and db endpoints combination /// - [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 /// /// Verify opening an scmp comparing two databases /// - [Fact] - public async void SchemaCompareOpenScmpDatabaseToDatabaseRequest() + [Test] + public async Task SchemaCompareOpenScmpDatabaseToDatabaseRequest() { await CreateAndOpenScmp(SchemaCompareEndpointType.Database, SchemaCompareEndpointType.Database); } @@ -537,8 +538,8 @@ WITH VALUES /// /// Verify opening an scmp comparing a dacpac and database /// - [Fact] - public async void SchemaCompareOpenScmpDacpacToDatabaseRequest() + [Test] + public async Task SchemaCompareOpenScmpDacpacToDatabaseRequest() { await CreateAndOpenScmp(SchemaCompareEndpointType.Dacpac, SchemaCompareEndpointType.Database); } @@ -546,8 +547,8 @@ WITH VALUES /// /// Verify opening an scmp comparing two dacpacs /// - [Fact] - public async void SchemaCompareOpenScmpDacpacToDacpacRequest() + [Test] + public async Task SchemaCompareOpenScmpDacpacToDacpacRequest() { await CreateAndOpenScmp(SchemaCompareEndpointType.Dacpac, SchemaCompareEndpointType.Dacpac); } @@ -555,7 +556,7 @@ WITH VALUES /// /// Verify the schema compare Service Calls ends to end /// - [Fact] + [Test] public async Task VerifySchemaCompareServiceCalls() { string operationId = Guid.NewGuid().ToString(); @@ -695,8 +696,8 @@ WITH VALUES /// /// Verify the schema compare cancel /// - [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 /// - //[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 /// /// Verify the schema compare request with failing exclude request because of dependencies and that include will include dependencies /// - [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(); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Scripting/ScriptingServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Scripting/ScriptingServiceTests.cs index ace58057..7a781aeb 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Scripting/ScriptingServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Scripting/ScriptingServiceTests.cs @@ -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 /// /// Verify the script object request /// - [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 }, 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; diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Security/CredentialTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Security/CredentialTests.cs index cba15f65..1999c671 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Security/CredentialTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Security/CredentialTests.cs @@ -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 /// /// TestHandleCreateCredentialRequest /// - [Fact] + [Test] public async Task TestHandleCreateCredentialRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -49,7 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security /// /// TestHandleUpdateCredentialRequest /// - [Fact] + [Test] public async Task TestHandleUpdateCredentialRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Security /// /// TestHandleDeleteCredentialRequest /// - [Fact] + [Test] public async Task TestHandleDeleteCredentialRequest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/ServerConfigurations/ServerConfigurationsServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/ServerConfigurations/ServerConfigurationsServiceTests.cs index f532c768..482b775d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/ServerConfigurations/ServerConfigurationsServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/ServerConfigurations/ServerConfigurationsServiceTests.cs @@ -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 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(r => result = r).AddErrorHandling(null); @@ -113,8 +113,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServic requestContext.Verify(x => x.SendError(It.IsAny())); } - [Fact] - public async void VerifyConfigUpdateRequestSendErrorGivenInvalidConnection() + [Test] + public async Task VerifyConfigUpdateRequestSendErrorGivenInvalidConnection() { ServerConfigUpdateResponseParams result = null; var requestContext = RequestContextMocks.Create(r => result = r).AddErrorHandling(null); @@ -130,8 +130,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.MachineLearningServic requestContext.Verify(x => x.SendError(It.IsAny())); } - [Fact] - public async void VerifyConfigListRequestSendErrorGivenInvalidConnection() + [Test] + public async Task VerifyConfigListRequestSendErrorGivenInvalidConnection() { ServerConfigListResponseParams result = null; var requestContext = RequestContextMocks.Create(r => result = r).AddErrorHandling(null); diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SqlAssessment/SqlAssessmentServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SqlAssessment/SqlAssessmentServiceTests.cs index a98ee6b4..e99ecc19 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SqlAssessment/SqlAssessmentServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/SqlAssessment/SqlAssessmentServiceTests.cs @@ -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> CallAssessment( @@ -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); }); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/TaskServices/TaskServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/TaskServices/TaskServiceTests.cs index 13580dec..61b1ba5d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/TaskServices/TaskServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/TaskServices/TaskServiceTests.cs @@ -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 { diff --git a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Utility/LiveConnectionHelper.cs b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Utility/LiveConnectionHelper.cs index 06b0ec18..bf957687 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Utility/LiveConnectionHelper.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/Utility/LiveConnectionHelper.cs @@ -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 { diff --git a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/Baselined/BaselinedTest.cs b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/Baselined/BaselinedTest.cs index 219a464d..9ada67f6 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/Baselined/BaselinedTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/Baselined/BaselinedTest.cs @@ -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 { diff --git a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/Microsoft.SqlTools.ServiceLayer.Test.Common.csproj b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/Microsoft.SqlTools.ServiceLayer.Test.Common.csproj index c8399d1f..0555a696 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/Microsoft.SqlTools.ServiceLayer.Test.Common.csproj +++ b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/Microsoft.SqlTools.ServiceLayer.Test.Common.csproj @@ -10,8 +10,9 @@ - - + + + diff --git a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/RequestContextMocking/EventFlowValidator.cs b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/RequestContextMocking/EventFlowValidator.cs index d9487f0f..8fb4050c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/RequestContextMocking/EventFlowValidator.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/RequestContextMocking/EventFlowValidator.cs @@ -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}"); }); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/SqlTestDb.cs b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/SqlTestDb.cs index c43c993b..9553d3ba 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/SqlTestDb.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/SqlTestDb.cs @@ -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; diff --git a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestConnectionProfileService.cs b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestConnectionProfileService.cs index f1d7fa42..08b89a06 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestConnectionProfileService.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestConnectionProfileService.cs @@ -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 { diff --git a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestLogger.cs b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestLogger.cs index 904ba892..4baa8091 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestLogger.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestLogger.cs @@ -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 { diff --git a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestServiceDriverProvider.cs b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestServiceDriverProvider.cs index fa8889d3..8a5428e5 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestServiceDriverProvider.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestServiceDriverProvider.cs @@ -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 { diff --git a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestServiceProvider.cs b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestServiceProvider.cs index e2a51dff..25fd2179 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestServiceProvider.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.Test.Common/TestServiceProvider.cs @@ -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 { diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/ConnectionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/ConnectionTests.cs index f7b5e369..68a7a8b4 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/ConnectionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/ConnectionTests.cs @@ -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] /// /// Language Service end-to-end integration tests /// @@ -19,16 +20,16 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests /// /// Try to connect with invalid credentials /// - [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 /// /// Validate list databases request /// - [Fact] + [Test] public async Task ListDatabasesTest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/LanguageServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/LanguageServiceTests.cs index f7803176..bb940dd7 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/LanguageServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/LanguageServiceTests.cs @@ -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] /// /// Language Service end-to-end integration tests /// @@ -23,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests /// /// Validate hover tooltip scenarios /// - [Fact] + [Test] public async Task HoverTest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -64,7 +65,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests /// /// Validation autocompletion suggestions scenarios /// - [Fact] + [Test] public async Task CompletionTest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -111,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests /// /// Validate diagnostic scenarios /// - [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 /// /// - [Fact] + [Test] public async Task DefinitionTest() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -260,7 +261,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests /// /// Validate the configuration change event /// - [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); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests.csproj b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests.csproj index 047c1f5c..26318c43 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests.csproj +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests.csproj @@ -21,8 +21,9 @@ - - + + + diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/Program.cs b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/Program.cs index 3ea3a2f5..b79c55ab 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/Program.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/Program.cs @@ -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 diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/QueryExecutionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/QueryExecutionTests.cs index ead95330..e7d0b0f1 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/QueryExecutionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/QueryExecutionTests.cs @@ -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"; diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/SqlScriptPublishModelTests.cs b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/SqlScriptPublishModelTests.cs index 850d1017..7144ef14 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/SqlScriptPublishModelTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/SqlScriptPublishModelTests.cs @@ -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] /// /// Scripting service end-to-end integration tests that use the SqlScriptPublishModel type to generate scripts. /// - public class SqlScriptPublishModelTests : IClassFixture + 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(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(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(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(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 { diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/StressTests.cs b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/StressTests.cs index ee9a19a0..bb7af271 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/StressTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/StressTests.cs @@ -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 { /// /// Simulate typing by a user to stress test the language service /// - //[Fact] + //[Test] public async Task TestLanguageService() { const string textToType = "SELECT * FROM sys.objects GO " + @@ -144,7 +146,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests /// /// Repeatedly execute queries to stress test the query execution service. /// - //[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 /// /// Repeatedly connect and disconnect to stress test the connection service. /// - //[Fact] + //[Test] public async Task TestConnectionService() { string ownerUri = "file:///my/test/file.sql"; diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/WorkspaceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/WorkspaceTests.cs index 667bf955..569f7185 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/WorkspaceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver.Tests/WorkspaceTests.cs @@ -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] /// /// Language Service end-to-end integration tests /// @@ -19,7 +20,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests /// /// Validate workspace lifecycle events /// - [Fact] + [Test] public async Task InitializeRequestTest() { using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Driver/ServiceTestDriver.cs b/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Driver/ServiceTestDriver.cs index b715f668..8d6eea4f 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Driver/ServiceTestDriver.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Driver/ServiceTestDriver.cs @@ -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); diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Microsoft.SqlTools.ServiceLayer.TestDriver.csproj b/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Microsoft.SqlTools.ServiceLayer.TestDriver.csproj index 4be29f85..aa1df865 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Microsoft.SqlTools.ServiceLayer.TestDriver.csproj +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Microsoft.SqlTools.ServiceLayer.TestDriver.csproj @@ -9,8 +9,6 @@ - - diff --git a/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Utility/TestRunner.cs b/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Utility/TestRunner.cs index 9625b531..635692c1 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Utility/TestRunner.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.TestDriver/Utility/TestRunner.cs @@ -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 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); + } } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Admin/AdminServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Admin/AdminServiceTests.cs index f7773f3d..bb5ce564 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Admin/AdminServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Admin/AdminServiceTests.cs @@ -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] /// /// Tests for AdminService Class /// 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); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/AssemblyInfo.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/AssemblyInfo.cs index 70421c18..e87e98ec 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/AssemblyInfo.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/AssemblyInfo.cs @@ -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] diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/AutoParameterization/SqlParameterizerTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/AutoParameterization/SqlParameterizerTests.cs index fab29d78..41edd0d3 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/AutoParameterization/SqlParameterizerTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/AutoParameterization/SqlParameterizerTests.cs @@ -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] /// /// Parameterization for Always Encrypted is a feature that automatically converts Transact-SQL variables /// into query parameters (instances of SqlParameter 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. /// - [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); } /// @@ -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. /// - [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); } /// @@ -90,7 +91,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization /// Batch statements larger than 300000 characters (Approximately 600 Kb) should /// throw ParameterizationScriptTooLargeException. /// - [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 ParameterizationParsingException. /// Better to catch the error here than on the server. /// - [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 ParameterizationFormatException should get thrown. /// - [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 /// - [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 ScriptFileMarker by calling the SqlParameterizer.CodeSense /// method, if a null script is passed in, the reuslt should be an empty collection. /// - [Fact] + [Test] public void CodeSenseShouldReturnEmptyListWhenGivenANullScript() { string sql = null; IList result = SqlParameterizer.CodeSense(sql); Assert.NotNull(result); - Assert.Empty(result); + Assert.That(result, Is.Empty); } /// /// When requesting a collection of ScriptFileMarker by calling the SqlParameterizer.CodeSense /// method, if a script is passed in that contains no valid parameters, the reuslt should be an empty collection. /// - [Fact] + [Test] public void CodeSenseShouldReturnEmptyListWhenGivenAParameterlessScript() { // SQL with no parameters @@ -206,7 +207,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization IList result = SqlParameterizer.CodeSense(sql); Assert.NotNull(result); - Assert.Empty(result); + Assert.That(result, Is.Empty); } /// @@ -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. /// - [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); } /// @@ -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. /// - [Fact] + [Test] public void CodeSenseShouldReturnInformationalCodeSenseItemsForValidParameters() { const string ssn = "795-73-9838"; @@ -263,8 +264,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization IList 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)); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Completion/AutoCompletionResultTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Completion/AutoCompletionResultTest.cs index 87792656..4409f00a 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Completion/AutoCompletionResultTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Completion/AutoCompletionResultTest.cs @@ -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(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Completion/ScriptDocumentInfoTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Completion/ScriptDocumentInfoTest.cs index fe65ed77..bc6d25c2 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Completion/ScriptDocumentInfoTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Completion/ScriptDocumentInfoTest.cs @@ -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); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/CachedServerInfoTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/CachedServerInfoTests.cs index cf100c92..555fe4e1 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/CachedServerInfoTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/CachedServerInfoTests.cs @@ -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] /// /// Tests for Sever Information Caching Class /// @@ -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 _)); } } } \ No newline at end of file diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ConnectionDetailsTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ConnectionDetailsTests.cs index e29de8dd..c66ea43a 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ConnectionDetailsTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ConnectionDetailsTests.cs @@ -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] /// /// Tests for ConnectionDetails Class /// 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); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ConnectionServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ConnectionServiceTests.cs index 680b5433..185de1fe 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ConnectionServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ConnectionServiceTests.cs @@ -3,27 +3,28 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; using Microsoft.Data.SqlClient; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; using Microsoft.SqlTools.Hosting.Protocol; +using Microsoft.SqlTools.ServiceLayer.Admin.Contracts; using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; using Moq.Protected; -using Xunit; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; using System.Linq; -using Microsoft.SqlTools.ServiceLayer.Admin.Contracts; - +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; + namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection { + [TestFixture] /// /// Tests for the ServiceHost Connection Service tests /// @@ -56,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection return connectionMock.Object; } - [Fact] + [Test] public void CanCancelConnectRequest() { const string testFile = "file:///my/test/file.sql"; @@ -117,7 +118,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Assert.True(cancelResult); } - [Fact] + [Test] public async Task CanCancelConnectRequestByConnecting() { const string testFile = "file:///my/test/file.sql"; @@ -182,10 +183,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Assert.Null(connectTask.Result.ConnectionId); // Verify that the second connection succeeded - Assert.NotEmpty(connectResult.ConnectionId); + Assert.That(connectResult.ConnectionId, Is.Not.Empty); } - [Fact] + [Test] public void CanCancelConnectRequestByDisconnecting() { const string testFile = "file:///my/test/file.sql"; @@ -250,10 +251,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// Verify that we can connect to the default database when no database name is /// provided as a parameter. /// - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CanConnectWithEmptyDatabaseName(string databaseName) + [Test] + public async Task CanConnectWithEmptyDatabaseName([Values(null, "")]string databaseName) { // Connect var connectionDetails = TestObjects.GetTestConnectionDetails(); @@ -266,18 +265,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Connection = connectionDetails }); - // check that a connection was created - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Empty, "check that a connection was created"); } /// /// Verify that we can connect to the default database when no database name is /// provided as a parameter. /// - [Theory] - [InlineData("master")] - [InlineData("nonMasterDb")] - public async Task ConnectToDefaultDatabaseRespondsWithActualDbName(string expectedDbName) + [Test] + public async Task ConnectToDefaultDatabaseRespondsWithActualDbName([Values("master", "nonMasterDb")]string expectedDbName) { // Given connecting with empty database name will return the expected DB name var connectionMock = new Mock { CallBase = true }; @@ -301,17 +297,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Connection = connectionDetails }); - // Then I expect connection to succeed and the Summary to include the correct DB name - Assert.NotEmpty(connectionResult.ConnectionId); - Assert.NotNull(connectionResult.ConnectionSummary); - Assert.Equal(expectedDbName, connectionResult.ConnectionSummary.DatabaseName); + Assert.Multiple(() => + { + Assert.That(connectionResult.ConnectionId, Is.Not.Empty, "ConnectionId"); + Assert.NotNull(connectionResult.ConnectionSummary, "ConnectionSummary"); + Assert.AreEqual(expectedDbName, connectionResult.ConnectionSummary.DatabaseName, "I expect connection to succeed and the Summary to include the correct DB name"); + }); } /// /// Verify that when a connection is started for a URI with an already existing /// connection, we disconnect first before connecting. /// - [Fact] + [Test] public async Task ConnectingWhenConnectionExistCausesDisconnectThenConnect() { bool callbackInvoked = false; @@ -357,7 +355,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection }); // Then I expect to be connected to master - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); // And when I then connect to another DB var updatedConnectionDetails = TestObjects.GetTestConnectionDetails(); @@ -375,14 +373,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Assert.True(callbackInvoked); // verify that we connected again - Assert.NotEmpty(connectionResult.ConnectionId); - Assert.Equal(otherDbName, connectionResult.ConnectionSummary.DatabaseName); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); + Assert.AreEqual(otherDbName, connectionResult.ConnectionSummary.DatabaseName); } /// /// Verify that when connecting with invalid credentials, an error is thrown. /// - [Fact] + [Test] public async Task ConnectingWithInvalidCredentialsYieldsErrorMessage() { var testConnectionDetails = TestObjects.GetTestConnectionDetails(); @@ -404,27 +402,28 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Connection = invalidConnectionDetails }); - // check that an error was caught - Assert.NotNull(connectionResult.Messages); - Assert.NotEqual(String.Empty, connectionResult.Messages); + Assert.That(connectionResult.Messages, Is.Not.Null.Or.Empty, "check that an error was caught"); } + static readonly object[] invalidParameters = + { + new object[] { "SqlLogin", null, "my-server", "test", "sa", "123456" }, + new object[] { "SqlLogin", "file://my/sample/file.sql", null, "test", "sa", "123456" }, + new object[] {"SqlLogin", "file://my/sample/file.sql", "my-server", "test", null, "123456"}, + new object[] {"SqlLogin", "file://my/sample/file.sql", "my-server", "test", "sa", null}, + new object[] {"SqlLogin", "", "my-server", "test", "sa", "123456" }, + new object[] {"SqlLogin", "file://my/sample/file.sql", "", "test", "sa", "123456"}, + new object[] {"SqlLogin", "file://my/sample/file.sql", "my-server", "test", "", "123456"}, + new object[] {"SqlLogin", "file://my/sample/file.sql", "my-server", "test", "sa", ""}, + new object[] {"Integrated", null, "my-server", "test", "sa", "123456"}, + new object[] {"Integrated", "file://my/sample/file.sql", null, "test", "sa", "123456"}, + new object[] {"Integrated", "", "my-server", "test", "sa", "123456"}, + new object[] {"Integrated", "file://my/sample/file.sql", "", "test", "sa", "123456"} + }; /// /// Verify that when connecting with invalid parameters, an error is thrown. /// - [Theory] - [InlineData("SqlLogin", null, "my-server", "test", "sa", "123456")] - [InlineData("SqlLogin", "file://my/sample/file.sql", null, "test", "sa", "123456")] - [InlineData("SqlLogin", "file://my/sample/file.sql", "my-server", "test", null, "123456")] - [InlineData("SqlLogin", "file://my/sample/file.sql", "my-server", "test", "sa", null)] - [InlineData("SqlLogin", "", "my-server", "test", "sa", "123456")] - [InlineData("SqlLogin", "file://my/sample/file.sql", "", "test", "sa", "123456")] - [InlineData("SqlLogin", "file://my/sample/file.sql", "my-server", "test", "", "123456")] - [InlineData("SqlLogin", "file://my/sample/file.sql", "my-server", "test", "sa", "")] - [InlineData("Integrated", null, "my-server", "test", "sa", "123456")] - [InlineData("Integrated", "file://my/sample/file.sql", null, "test", "sa", "123456")] - [InlineData("Integrated", "", "my-server", "test", "sa", "123456")] - [InlineData("Integrated", "file://my/sample/file.sql", "", "test", "sa", "123456")] + [Test, TestCaseSource(nameof(invalidParameters))] public async Task ConnectingWithInvalidParametersYieldsErrorMessage(string authType, string ownerUri, string server, string database, string userName, string password) { // Connect with invalid parameters @@ -443,23 +442,24 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection } }); - // check that an error was caught - Assert.NotNull(connectionResult.Messages); - Assert.NotEqual(String.Empty, connectionResult.Messages); + Assert.That(connectionResult.Messages, Is.Not.Null.Or.Empty, "check that an error was caught"); } + static readonly object[] noUserNameOrPassword = + { + new object[] {null, null}, + new object[] {null, ""}, + new object[] {"", null}, + new object[] {"", ""}, + new object[] {"sa", null}, + new object[] {"sa", ""}, + new object[] {null, "12345678"}, + new object[] {"", "12345678"}, + }; /// /// Verify that when using integrated authentication, the username and/or password can be empty. /// - [Theory] - [InlineData(null, null)] - [InlineData(null, "")] - [InlineData("", null)] - [InlineData("", "")] - [InlineData("sa", null)] - [InlineData("sa", "")] - [InlineData(null, "12345678")] - [InlineData("", "12345678")] + [Test, TestCaseSource(nameof(noUserNameOrPassword))] public async Task ConnectingWithNoUsernameOrPasswordWorksForIntegratedAuth(string userName, string password) { // Connect @@ -478,14 +478,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection } }); - // check that the connection was successful - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); } /// /// Verify that when connecting with a null parameters object, an error is thrown. /// - [Fact] + [Test] public async Task ConnectingWithNullParametersObjectYieldsErrorMessage() { // Connect with null parameters @@ -493,54 +492,57 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection TestObjects.GetTestConnectionService() .Connect(null); - // check that an error was caught - Assert.NotNull(connectionResult.Messages); - Assert.NotEqual(String.Empty, connectionResult.Messages); + Assert.That(connectionResult.Messages, Is.Not.Null.Or.Empty, "check that an error was caught"); } + + private static readonly object[] optionalParameters = + { + new object[] {"AuthenticationType", "Integrated", "Integrated Security" }, + new object[] {"AuthenticationType", "SqlLogin", ""}, + new object[] {"Encrypt", true, "Encrypt"}, + new object[] {"Encrypt", false, "Encrypt"}, + new object[] {"ColumnEncryptionSetting", "Enabled", "Column Encryption Setting=Enabled"}, + new object[] {"ColumnEncryptionSetting", "Disabled", "Column Encryption Setting=Disabled"}, + new object[] {"ColumnEncryptionSetting", "enabled", "Column Encryption Setting=Enabled"}, + new object[] {"ColumnEncryptionSetting", "disabled", "Column Encryption Setting=Disabled"}, + new object[] {"ColumnEncryptionSetting", "ENABLED", "Column Encryption Setting=Enabled"}, + new object[] {"ColumnEncryptionSetting", "DISABLED", "Column Encryption Setting=Disabled"}, + new object[] {"ColumnEncryptionSetting", "eNaBlEd", "Column Encryption Setting=Enabled"}, + new object[] {"ColumnEncryptionSetting", "DiSaBlEd", "Column Encryption Setting=Disabled"}, + new object[] {"TrustServerCertificate", true, "Trust Server Certificate"}, + new object[] {"TrustServerCertificate", false, "Trust Server Certificate"}, + new object[] {"PersistSecurityInfo", true, "Persist Security Info"}, + new object[] {"PersistSecurityInfo", false, "Persist Security Info"}, + new object[] {"ConnectTimeout", 15, "Connect Timeout"}, + new object[] {"ConnectRetryCount", 1, "Connect Retry Count"}, + new object[] {"ConnectRetryInterval", 10, "Connect Retry Interval"}, + new object[] {"ApplicationName", "vscode-mssql", "Application Name"}, + new object[] {"WorkstationId", "mycomputer", "Workstation ID"}, + new object[] {"ApplicationIntent", "ReadWrite", "Application Intent"}, + new object[] {"ApplicationIntent", "ReadOnly", "Application Intent"}, + new object[] {"CurrentLanguage", "test", "Current Language"}, + new object[] {"Pooling", false, "Pooling"}, + new object[] {"Pooling", true, "Pooling"}, + new object[] {"MaxPoolSize", 100, "Max Pool Size"}, + new object[] {"MinPoolSize", 0, "Min Pool Size"}, + new object[] {"LoadBalanceTimeout", 0, "Load Balance Timeout"}, + new object[] {"Replication", true, "Replication"}, + new object[] {"Replication", false, "Replication"}, + new object[] {"AttachDbFilename", "myfile", "AttachDbFilename"}, + new object[] {"FailoverPartner", "partner", "Failover Partner"}, + new object[] {"MultiSubnetFailover", true, "Multi Subnet Failover"}, + new object[] {"MultiSubnetFailover", false, "Multi Subnet Failover"}, + new object[] {"MultipleActiveResultSets", false, "Multiple Active Result Sets"}, + new object[] {"MultipleActiveResultSets", true, "Multiple Active Result Sets"}, + new object[] {"PacketSize", 8192, "Packet Size"}, + new object[] {"TypeSystemVersion", "Latest", "Type System Version"}, + }; + /// /// Verify that optional parameters can be built into a connection string for connecting. /// - [Theory] - [InlineData("AuthenticationType", "Integrated", "Integrated Security")] - [InlineData("AuthenticationType", "SqlLogin", "")] - [InlineData("Encrypt", true, "Encrypt")] - [InlineData("Encrypt", false, "Encrypt")] - [InlineData("ColumnEncryptionSetting", "Enabled", "Column Encryption Setting=Enabled")] - [InlineData("ColumnEncryptionSetting", "Disabled", "Column Encryption Setting=Disabled")] - [InlineData("ColumnEncryptionSetting", "enabled", "Column Encryption Setting=Enabled")] - [InlineData("ColumnEncryptionSetting", "disabled", "Column Encryption Setting=Disabled")] - [InlineData("ColumnEncryptionSetting", "ENABLED", "Column Encryption Setting=Enabled")] - [InlineData("ColumnEncryptionSetting", "DISABLED", "Column Encryption Setting=Disabled")] - [InlineData("ColumnEncryptionSetting", "eNaBlEd", "Column Encryption Setting=Enabled")] - [InlineData("ColumnEncryptionSetting", "DiSaBlEd", "Column Encryption Setting=Disabled")] - [InlineData("TrustServerCertificate", true, "Trust Server Certificate")] - [InlineData("TrustServerCertificate", false, "Trust Server Certificate")] - [InlineData("PersistSecurityInfo", true, "Persist Security Info")] - [InlineData("PersistSecurityInfo", false, "Persist Security Info")] - [InlineData("ConnectTimeout", 15, "Connect Timeout")] - [InlineData("ConnectRetryCount", 1, "Connect Retry Count")] - [InlineData("ConnectRetryInterval", 10, "Connect Retry Interval")] - [InlineData("ApplicationName", "vscode-mssql", "Application Name")] - [InlineData("WorkstationId", "mycomputer", "Workstation ID")] - [InlineData("ApplicationIntent", "ReadWrite", "Application Intent")] - [InlineData("ApplicationIntent", "ReadOnly", "Application Intent")] - [InlineData("CurrentLanguage", "test", "Current Language")] - [InlineData("Pooling", false, "Pooling")] - [InlineData("Pooling", true, "Pooling")] - [InlineData("MaxPoolSize", 100, "Max Pool Size")] - [InlineData("MinPoolSize", 0, "Min Pool Size")] - [InlineData("LoadBalanceTimeout", 0, "Load Balance Timeout")] - [InlineData("Replication", true, "Replication")] - [InlineData("Replication", false, "Replication")] - [InlineData("AttachDbFilename", "myfile", "AttachDbFilename")] - [InlineData("FailoverPartner", "partner", "Failover Partner")] - [InlineData("MultiSubnetFailover", true, "Multi Subnet Failover")] - [InlineData("MultiSubnetFailover", false, "Multi Subnet Failover")] - [InlineData("MultipleActiveResultSets", false, "Multiple Active Result Sets")] - [InlineData("MultipleActiveResultSets", true, "Multiple Active Result Sets")] - [InlineData("PacketSize", 8192, "Packet Size")] - [InlineData("TypeSystemVersion", "Latest", "Type System Version")] + [Test, TestCaseSource(nameof(optionalParameters))] public void ConnectingWithOptionalParametersBuildsConnectionString(string propertyName, object propertyValue, string connectionStringMarker) { // Create a test connection details object and set the property to a specific value @@ -550,52 +552,50 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection // Test that a connection string can be created without exceptions string connectionString = ConnectionService.BuildConnectionString(details); - Assert.NotNull(connectionString); - Assert.NotEmpty(connectionString); - // Verify that the parameter is in the connection string - Assert.True(connectionString.Contains(connectionStringMarker)); + Assert.That(connectionString, Contains.Substring(connectionStringMarker), "Verify that the parameter is in the connection string"); } + private static readonly object[] optionalEnclaveParameters = + { + new object[] {"EnclaveAttestationProtocol", "AAS", "Attestation Protocol=AAS"}, + new object[] {"EnclaveAttestationProtocol", "HGS", "Attestation Protocol=HGS"}, + new object[] {"EnclaveAttestationProtocol", "aas", "Attestation Protocol=AAS"}, + new object[] {"EnclaveAttestationProtocol", "hgs", "Attestation Protocol=HGS"}, + new object[] {"EnclaveAttestationProtocol", "AaS", "Attestation Protocol=AAS"}, + new object[] {"EnclaveAttestationProtocol", "hGs", "Attestation Protocol=HGS"}, + new object[] {"EnclaveAttestationUrl", "https://attestation.us.attest.azure.net/attest/SgxEnclave", "Enclave Attestation Url=https://attestation.us.attest.azure.net/attest/SgxEnclave" }, + }; + /// /// Verify that optional parameters which require ColumnEncryptionSetting to be enabled /// can be built into a connection string for connecting. /// - [Theory] - [InlineData("EnclaveAttestationProtocol", "AAS", "Attestation Protocol=AAS")] - [InlineData("EnclaveAttestationProtocol", "HGS", "Attestation Protocol=HGS")] - [InlineData("EnclaveAttestationProtocol", "aas", "Attestation Protocol=AAS")] - [InlineData("EnclaveAttestationProtocol", "hgs", "Attestation Protocol=HGS")] - [InlineData("EnclaveAttestationProtocol", "AaS", "Attestation Protocol=AAS")] - [InlineData("EnclaveAttestationProtocol", "hGs", "Attestation Protocol=HGS")] - [InlineData("EnclaveAttestationUrl", "https://attestation.us.attest.azure.net/attest/SgxEnclave", "Enclave Attestation Url=https://attestation.us.attest.azure.net/attest/SgxEnclave")] + [Test, TestCaseSource(nameof(optionalEnclaveParameters))] public void ConnectingWithOptionalEnclaveParametersBuildsConnectionString(string propertyName, object propertyValue, string connectionStringMarker) { // Create a test connection details object and set the property to a specific value ConnectionDetails details = TestObjects.GetTestConnectionDetails(); - details.GetType() - .GetProperty("ColumnEncryptionSetting") - .SetValue(details, "Enabled"); + details.ColumnEncryptionSetting = "Enabled"; details.GetType() .GetProperty(propertyName) .SetValue(details, propertyValue); // Test that a connection string can be created without exceptions - string connectionString = ConnectionService.BuildConnectionString(details); - Assert.NotNull(connectionString); - Assert.NotEmpty(connectionString); - - // Verify that the parameter is in the connection string - Assert.True(connectionString.Contains(connectionStringMarker)); + string connectionString = ConnectionService.BuildConnectionString(details); + Assert.That(connectionString, Contains.Substring(connectionStringMarker), "Verify that the parameter is in the connection string"); } + private static readonly object[] invalidOptions = + { + new object[] {"AuthenticationType", "NotAValidAuthType" }, + new object[] {"ColumnEncryptionSetting", "NotAValidColumnEncryptionSetting" }, + new object[] {"EnclaveAttestationProtocol", "NotAValidEnclaveAttestationProtocol" }, + }; /// /// Build connection string with an invalid property type /// - [Theory] - [InlineData("AuthenticationType", "NotAValidAuthType")] - [InlineData("ColumnEncryptionSetting", "NotAValidColumnEncryptionSetting")] - [InlineData("EnclaveAttestationProtocol", "NotAValidEnclaveAttestationProtocol")] + [Test, TestCaseSource(nameof(invalidOptions))] public void BuildConnectionStringWithInvalidOptions(string propertyName, object propertyValue) { ConnectionDetails details = TestObjects.GetTestConnectionDetails(); @@ -604,63 +604,50 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Assert.Throws(() => ConnectionService.BuildConnectionString(details)); } - /// - /// Parameters used for test: BuildConnectionStringWithInvalidOptionCombinations - /// - public static readonly object[][] ConnectionStringWithInvalidOptionCombinations = - { - new object[] - { - typeof(ArgumentException), - new [] + private static readonly Tuple[][] optionCombos = + { + new [] { Tuple.Create("ColumnEncryptionSetting", null), Tuple.Create("EnclaveAttestationProtocol", "AAS"), Tuple.Create("EnclaveAttestationUrl", "https://attestation.us.attest.azure.net/attest/SgxEnclave") - } - }, - new object[] - { - typeof(ArgumentException), - new [] + }, + new [] { Tuple.Create("ColumnEncryptionSetting", "Disabled"), Tuple.Create("EnclaveAttestationProtocol", "AAS"), Tuple.Create("EnclaveAttestationUrl", "https://attestation.us.attest.azure.net/attest/SgxEnclave") - } - }, - new object[] - { - typeof(ArgumentException), - new [] + }, + new [] { Tuple.Create("ColumnEncryptionSetting", ""), Tuple.Create("EnclaveAttestationProtocol", "AAS"), Tuple.Create("EnclaveAttestationUrl", "https://attestation.us.attest.azure.net/attest/SgxEnclave") - } - } + } }; /// /// Build connection string with an invalid property combinations /// - [Theory] - [MemberData(nameof(ConnectionStringWithInvalidOptionCombinations))] - public void BuildConnectionStringWithInvalidOptionCombinations(Type exceptionType, Tuple[] propertyNameValuePairs) + [Test] + public void ConnStrWithInvalidOptions() { ConnectionDetails details = TestObjects.GetTestConnectionDetails(); - propertyNameValuePairs.ToList().ForEach(tuple => - { - PropertyInfo info = details.GetType().GetProperty(tuple.Item1); - info.SetValue(details, tuple.Item2); - }); - Assert.Throws(exceptionType, () => ConnectionService.BuildConnectionString(details)); + foreach (var options in optionCombos) + { + options.ToList().ForEach(tuple => + { + PropertyInfo info = details.GetType().GetProperty(tuple.Item1); + info.SetValue(details, tuple.Item2); + }); + Assert.Throws(() => ConnectionService.BuildConnectionString(details)); + } } /// /// Verify that a connection changed event is fired when the database context changes. /// - [Fact] + [Test] public async Task ConnectionChangedEventIsFiredWhenDatabaseContextChanges() { var serviceHostMock = new Mock(); @@ -678,8 +665,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Connection = TestObjects.GetTestConnectionDetails() }); - // verify that a valid connection id was returned - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Empty, "verify that a valid connection id was returned"); ConnectionInfo info; Assert.True(connectionService.TryFindConnection(ownerUri, out info)); @@ -694,7 +680,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Verify that the SQL parser correctly detects errors in text /// - [Fact] + [Test] public async Task ConnectToDatabaseTest() { // connect to a database instance @@ -707,14 +693,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Connection = TestObjects.GetTestConnectionDetails() }); - // verify that a valid connection id was returned - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); } /// /// Verify that we can disconnect from an active connection successfully /// - [Fact] + [Test] public async Task DisconnectFromDatabaseTest() { // first connect @@ -728,8 +713,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Connection = TestObjects.GetTestConnectionDetails() }); - // verify that we are connected - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); // send disconnect request var disconnectResult = @@ -744,7 +728,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Test that when a disconnect is performed, the callback event is fired /// - [Fact] + [Test] public async Task DisconnectFiresCallbackEvent() { bool callbackInvoked = false; @@ -760,8 +744,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Connection = TestObjects.GetTestConnectionDetails() }); - // verify that we are connected - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); // register disconnect callback connectionService.RegisterOnDisconnectTask( @@ -789,7 +772,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Test that disconnecting an active connection removes the Owner URI -> ConnectionInfo mapping /// - [Fact] + [Test] public async Task DisconnectRemovesOwnerMapping() { // first connect @@ -804,7 +787,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection }); // verify that we are connected - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); // check that the owner mapping exists ConnectionInfo info; @@ -826,11 +809,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Test that disconnecting validates parameters and doesn't succeed when they are invalid /// - [Theory] - [InlineData(null)] - [InlineData("")] - - public async Task DisconnectValidatesParameters(string disconnectUri) + [Test] + public async Task DisconnectValidatesParameters([Values("", null)] string disconnectUri) { // first connect string ownerUri = "file://my/sample/file.sql"; @@ -844,7 +824,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection }); // verify that we are connected - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); // send disconnect request var disconnectResult = @@ -877,7 +857,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection }); // verify that a valid connection id was returned - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); // list databases for the connection ListDatabasesParams parameters = new ListDatabasesParams @@ -891,7 +871,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Verifies the the list databases operation lists database names for the server used by a connection. /// - [Fact] + [Test] public async Task ListDatabasesOnServerForCurrentConnectionReturnsDatabaseNames() { // Result set for the query of database names @@ -909,18 +889,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection string[] databaseNames = response.DatabaseNames; - Assert.Equal(databaseNames.Length, 5); - Assert.Equal(databaseNames[0], "master"); - Assert.Equal(databaseNames[1], "model"); - Assert.Equal(databaseNames[2], "msdb"); - Assert.Equal(databaseNames[3], "tempdb"); - Assert.Equal(databaseNames[4], "mydatabase"); + Assert.AreEqual(5, databaseNames.Length); + Assert.AreEqual("master", databaseNames[0]); + Assert.AreEqual("model", databaseNames[1]); + Assert.AreEqual("msdb", databaseNames[2]); + Assert.AreEqual("tempdb", databaseNames[3]); + Assert.AreEqual("mydatabase", databaseNames[4]); } /// /// Verifies the the list databases operation lists database names for the server used by a connection. /// - [Fact] + [Test] public async Task ListDatabasesOnServerForCurrentConnectionReturnsDatabaseDetails() { // Result set for the query of database names @@ -941,7 +921,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection TestResultSet data = new TestResultSet(cols, rows); var response = await RunListDatabasesRequestHandler(testdata: data, includeDetails: true); - Assert.Equal(response.Databases.Length, 5); + Assert.AreEqual(5, response.Databases.Length); VerifyDatabaseDetail(rows[0], response.Databases[4]); VerifyDatabaseDetail(rows[1], response.Databases[0]); VerifyDatabaseDetail(rows[2], response.Databases[1]); @@ -951,49 +931,49 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection private void VerifyDatabaseDetail(object[] expected, DatabaseInfo actual) { - Assert.Equal(expected[0], actual.Options[ListDatabasesRequestDatabaseProperties.Name]); - Assert.Equal(expected[1], actual.Options[ListDatabasesRequestDatabaseProperties.State]); - Assert.Equal(expected[2], actual.Options[ListDatabasesRequestDatabaseProperties.SizeInMB]); - Assert.Equal(expected[3], actual.Options[ListDatabasesRequestDatabaseProperties.LastBackup]); + Assert.AreEqual(expected[0], actual.Options[ListDatabasesRequestDatabaseProperties.Name]); + Assert.AreEqual(expected[1], actual.Options[ListDatabasesRequestDatabaseProperties.State]); + Assert.AreEqual(expected[2], actual.Options[ListDatabasesRequestDatabaseProperties.SizeInMB]); + Assert.AreEqual(expected[3], actual.Options[ListDatabasesRequestDatabaseProperties.LastBackup]); } /// /// Verify that the factory is returning DatabaseNamesHandler /// - [Fact] + [Test] public void ListDatabaseRequestFactoryReturnsDatabaseNamesHandler() { var handler = ListDatabaseRequestHandlerFactory.getHandler(includeDetails: false, isSqlDB: true); - Assert.IsType(typeof(DatabaseNamesHandler), handler); + Assert.That(handler, Is.InstanceOf()); handler = ListDatabaseRequestHandlerFactory.getHandler(includeDetails: false, isSqlDB: false); - Assert.IsType(typeof(DatabaseNamesHandler), handler); + Assert.That(handler, Is.InstanceOf()); } /// /// Verify that the factory is returning SqlDBDatabaseDetailHandler /// - [Fact] + [Test] public void ListDatabaseRequestFactoryReturnsSqlDBHandler() { var handler = ListDatabaseRequestHandlerFactory.getHandler(includeDetails: true, isSqlDB: true); - Assert.IsType(typeof(SqlDBDatabaseDetailHandler), handler); + Assert.That(handler, Is.InstanceOf()); } /// /// Verify that the factory is returning SqlServerDatabaseDetailHandler /// - [Fact] + [Test] public void ListDatabaseRequestFactoryReturnsSqlServerHandler() { var handler = ListDatabaseRequestHandlerFactory.getHandler(includeDetails: true, isSqlDB: false); - Assert.IsType(typeof(SqlServerDatabaseDetailHandler), handler); + Assert.That(handler, Is.InstanceOf()); } /// /// Verify that the SQL parser correctly detects errors in text /// - [Fact] + [Test] public async Task OnConnectionCallbackHandlerTest() { bool callbackInvoked = false; @@ -1018,7 +998,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Test ConnectionSummaryComparer /// - [Fact] + [Test] public void TestConnectionSummaryComparer() { var summary1 = new ConnectionSummary() @@ -1048,7 +1028,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Verify when a connection is created that the URI -> Connection mapping is created in the connection service. /// - [Fact] + [Test] public async Task TestConnectRequestRegistersOwner() { // Given a request to connect to a database @@ -1060,7 +1040,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection // verify that a valid connection id was returned Assert.NotNull(connectionResult.ConnectionId); - Assert.NotEqual(string.Empty, connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.EqualTo(string.Empty)); Assert.NotNull(new Guid(connectionResult.ConnectionId)); // verify that the (URI -> connection) mapping was created @@ -1075,7 +1055,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// the case, look at RetryPolicyUtils.cs in IsRetryableNetworkConnectivityError(), /// and remove the code block specific to Linux/OSX. /// - [Fact] + [Test] public void TestThatLinuxAndOsxSqlExceptionHasNoErrorCode() { RunIfWrapper.RunIfLinuxOrOSX(() => @@ -1095,7 +1075,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection catch (SqlException ex) { // Error code should be 0 due to bug - Assert.Equal(ex.Number, 0); + Assert.AreEqual(0, ex.Number); } }); } @@ -1103,7 +1083,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Test that cancel connection with a null connection parameter /// - [Fact] + [Test] public void TestCancelConnectionNullParam() { var service = TestObjects.GetTestConnectionService(); @@ -1113,7 +1093,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Test that cancel connection with a null connection parameter /// - [Fact] + [Test] public void TestListDatabasesInvalidParams() { var service = TestObjects.GetTestConnectionService(); @@ -1126,7 +1106,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Test that the connection complete notification type can be created. /// - [Fact] + [Test] public void TestConnectionCompleteNotificationIsCreated() { Assert.NotNull(ConnectionCompleteNotification.Type); @@ -1135,17 +1115,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection /// /// Test that the connection summary comparer creates a hash code correctly /// - [Theory] - [InlineData(true, null, null, null)] - [InlineData(false, null, null, null)] - [InlineData(false, null, null, "sa")] - [InlineData(false, null, "test", null)] - [InlineData(false, null, "test", "sa")] - [InlineData(false, "server", null, null)] - [InlineData(false, "server", null, "sa")] - [InlineData(false, "server", "test", null)] - [InlineData(false, "server", "test", "sa")] - public void TestConnectionSummaryComparerHashCode(bool objectNull, string serverName, string databaseName, string userName) + [Test] + public void TestConnectionSummaryComparerHashCode([Values]bool objectNull, + [Values(null, "server")]string serverName, + [Values(null, "test")]string databaseName, + [Values(null, "sa")]string userName) { // Given a connection summary and comparer object ConnectionSummary summary = null; @@ -1164,17 +1138,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection int hashCode = comparer.GetHashCode(summary); if (summary == null || (serverName == null && databaseName == null && userName == null)) { - // Then I expect it to be 31 for a null summary - Assert.Equal(31, hashCode); + Assert.AreEqual(31, hashCode, "I expect it to be 31 for a null summary"); } else { - // And not 31 otherwise - Assert.NotEqual(31, hashCode); + Assert.That(hashCode, Is.Not.EqualTo(31), "And not 31 otherwise"); } } - [Fact] + [Test] public void ConnectParamsAreInvalidIfConnectionIsNull() { // Given connection parameters where the connection property is null @@ -1189,13 +1161,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection // If I check if the parameters are valid Assert.False(parameters.IsValid(out errorMessage)); - // Then I expect an error message - Assert.NotNull(errorMessage); - Assert.NotEmpty(errorMessage); + Assert.That(errorMessage, Is.Not.Null.Or.Empty, "Then I expect an error message"); } - [Fact] - public async void ConnectingTwiceWithTheSameUriDoesNotCreateAnotherDbConnection() + [Test] + public async Task ConnectingTwiceWithTheSameUriDoesNotCreateAnotherDbConnection() { // Setup the connect and disconnect params var connectParamsSame1 = new ConnectParams() @@ -1225,31 +1195,31 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection // Given a request to connect to a database, there should be no initial connections in the map var service = TestObjects.GetTestConnectionService(); Dictionary ownerToConnectionMap = service.OwnerToConnectionMap; - Assert.Equal(0, ownerToConnectionMap.Count); + Assert.AreEqual(0, ownerToConnectionMap.Count); // If we connect to the service, there should be 1 connection await service.Connect(connectParamsSame1); - Assert.Equal(1, ownerToConnectionMap.Count); + Assert.AreEqual(1, ownerToConnectionMap.Count); // If we connect again with the same URI, there should still be 1 connection await service.Connect(connectParamsSame2); - Assert.Equal(1, ownerToConnectionMap.Count); + Assert.AreEqual(1, ownerToConnectionMap.Count); // If we connect with a different URI, there should be 2 connections await service.Connect(connectParamsDifferent); - Assert.Equal(2, ownerToConnectionMap.Count); + Assert.AreEqual(2, ownerToConnectionMap.Count); // If we disconnect with the unique URI, there should be 1 connection service.Disconnect(disconnectParamsDifferent); - Assert.Equal(1, ownerToConnectionMap.Count); + Assert.AreEqual(1, ownerToConnectionMap.Count); // If we disconnect with the duplicate URI, there should be 0 connections service.Disconnect(disconnectParamsSame); - Assert.Equal(0, ownerToConnectionMap.Count); + Assert.AreEqual(0, ownerToConnectionMap.Count); } - [Fact] - public async void DbConnectionDoesntLeakUponDisconnect() + [Test] + public async Task DbConnectionDoesntLeakUponDisconnect() { // If we connect with a single URI and 2 connection types var connectParamsDefault = new ConnectParams() @@ -1274,8 +1244,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection // We should have one ConnectionInfo and 2 DbConnections ConnectionInfo connectionInfo = service.OwnerToConnectionMap[connectParamsDefault.OwnerUri]; - Assert.Equal(2, connectionInfo.CountConnections); - Assert.Equal(1, service.OwnerToConnectionMap.Count); + Assert.AreEqual(2, connectionInfo.CountConnections); + Assert.AreEqual(1, service.OwnerToConnectionMap.Count); // If we record when the Default connecton calls Close() bool defaultDisconnectCalled = false; @@ -1305,12 +1275,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Assert.True(queryDisconnectCalled); // And the maps that hold connection data should be empty - Assert.Equal(0, connectionInfo.CountConnections); - Assert.Equal(0, service.OwnerToConnectionMap.Count); + Assert.AreEqual(0, connectionInfo.CountConnections); + Assert.AreEqual(0, service.OwnerToConnectionMap.Count); } - [Fact] - public async void ClosingQueryConnectionShouldLeaveDefaultConnectionOpen() + [Test] + public async Task ClosingQueryConnectionShouldLeaveDefaultConnectionOpen() { // Setup the connect and disconnect params var connectParamsDefault = new ConnectParams() @@ -1338,52 +1308,48 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection ConnectionInfo connectionInfo = service.OwnerToConnectionMap[connectParamsDefault.OwnerUri]; // There should be 2 connections in the map - Assert.Equal(2, connectionInfo.CountConnections); + Assert.AreEqual(2, connectionInfo.CountConnections); // If I Disconnect only the Query connection, there should be 1 connection in the map service.Disconnect(disconnectParamsQuery); - Assert.Equal(1, connectionInfo.CountConnections); + Assert.AreEqual(1, connectionInfo.CountConnections); // If I reconnect, there should be 2 again await service.Connect(connectParamsQuery); - Assert.Equal(2, connectionInfo.CountConnections); + Assert.AreEqual(2, connectionInfo.CountConnections); } - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetOrOpenNullOwnerUri(string ownerUri) + [Test] + public async Task GetOrOpenNullOwnerUri([Values(null, "")]string ownerUri) { // If: I have a connection service and I ask for a connection with an invalid ownerUri // Then: An exception should be thrown var service = TestObjects.GetTestConnectionService(); - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => service.GetOrOpenConnection(ownerUri, ConnectionType.Default)); } - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetOrOpenNullConnectionType(string connType) + [Test] + public async Task GetOrOpenNullConnectionType([Values(null, "")] string connType) { // If: I have a connection service and I ask for a connection with an invalid connectionType // Then: An exception should be thrown var service = TestObjects.GetTestConnectionService(); - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => service.GetOrOpenConnection(TestObjects.ScriptUri, connType)); } - [Fact] + [Test] public async Task GetOrOpenNoConnection() { // If: I have a connection service and I ask for a connection for an unconnected uri // Then: An exception should be thrown var service = TestObjects.GetTestConnectionService(); - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => service.GetOrOpenConnection(TestObjects.ScriptUri, ConnectionType.Query)); } - [Fact] + [Test] public async Task GetOrOpenNoDefaultConnection() { // Setup: Create a connection service with an empty connection info obj @@ -1393,11 +1359,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection // If: I ask for a connection on a connection that doesn't have a default connection // Then: An exception should be thrown - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => service.GetOrOpenConnection(TestObjects.ScriptUri, ConnectionType.Query)); } - [Fact] + [Test] public async Task GetOrOpenAdminDefaultConnection() { // Setup: Create a connection service with an empty connection info obj @@ -1407,11 +1373,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection // If: I ask for a connection on a connection that doesn't have a default connection // Then: An exception should be thrown - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => service.GetOrOpenConnection(TestObjects.ScriptUri, ConnectionType.Query)); } - [Fact] + [Test] public async Task ConnectionWithAdminConnectionEnsuresOnlyOneConnectionCreated() { // If I try to connect using a connection string, it overrides the server name and username for the connection @@ -1429,33 +1395,33 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection DbConnection defaultConn = await service.GetOrOpenConnection(connectionParameters.OwnerUri, ConnectionType.Default); ConnectionInfo connInfo = service.OwnerToConnectionMap[connectionParameters.OwnerUri]; Assert.NotNull(defaultConn); - Assert.Equal(connInfo.AllConnections.Count, 1); + Assert.AreEqual(1, connInfo.AllConnections.Count); // Verify that for the Query, no new connection is created DbConnection queryConn = await service.GetOrOpenConnection(connectionParameters.OwnerUri, ConnectionType.Query); connInfo = service.OwnerToConnectionMap[connectionParameters.OwnerUri]; Assert.NotNull(defaultConn); - Assert.Equal(connInfo.AllConnections.Count, 1); + Assert.AreEqual(1, connInfo.AllConnections.Count); // Verify that if the query connection was closed, it will be reopened on requesting the connection again - Assert.Equal(ConnectionState.Open, queryConn.State); + Assert.AreEqual(ConnectionState.Open, queryConn.State); queryConn.Close(); - Assert.Equal(ConnectionState.Closed, queryConn.State); + Assert.AreEqual(ConnectionState.Closed, queryConn.State); queryConn = await service.GetOrOpenConnection(connectionParameters.OwnerUri, ConnectionType.Query); - Assert.Equal(ConnectionState.Open, queryConn.State); + Assert.AreEqual(ConnectionState.Open, queryConn.State); } - [Fact] + [Test] public async Task ConnectionWithConnectionStringSucceeds() { // If I connect using a connection string instead of the normal parameters, the connection succeeds var connectionParameters = TestObjects.GetTestConnectionParams(true); var connectionResult = await TestObjects.GetTestConnectionService().Connect(connectionParameters); - Assert.NotEmpty(connectionResult.ConnectionId); + Assert.That(connectionResult.ConnectionId, Is.Not.Null.Or.Empty, "check that the connection was successful"); } - [Fact] + [Test] public async Task ConnectionWithBadConnectionStringFails() { // If I try to connect using an invalid connection string, the connection fails @@ -1463,10 +1429,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection connectionParameters.Connection.ConnectionString = "thisisnotavalidconnectionstring"; var connectionResult = await TestObjects.GetTestConnectionService().Connect(connectionParameters); - Assert.NotEmpty(connectionResult.ErrorMessage); + Assert.That(connectionResult.ErrorMessage, Is.Not.Empty); } - [Fact] + [Test] public async Task ConnectionWithConnectionStringOverridesServerInfo() { // If I try to connect using a connection string, it overrides the server name and username for the connection @@ -1480,11 +1446,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection // Connect and verify that the connectionParameters object's server name and username have been overridden var connectionResult = await TestObjects.GetTestConnectionService().Connect(connectionParameters); - Assert.NotEqual(serverName, connectionResult.ConnectionSummary.ServerName); - Assert.NotEqual(userName, connectionResult.ConnectionSummary.UserName); + Assert.That(connectionResult.ConnectionSummary.ServerName, Is.Not.EqualTo(serverName)); + Assert.That(connectionResult.ConnectionSummary.UserName, Is.Not.EqualTo(userName)); } - [Fact] + [Test] public async Task OtherParametersOverrideConnectionString() { // If I try to connect using a connection string, and set parameters other than the server name, username, or password, @@ -1497,10 +1463,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection // Connect and verify that the connection string's database name has been overridden var connectionResult = await TestObjects.GetTestConnectionService().Connect(connectionParameters); - Assert.Equal(databaseName, connectionResult.ConnectionSummary.DatabaseName); + Assert.AreEqual(databaseName, connectionResult.ConnectionSummary.DatabaseName); } - [Fact] + [Test] public async Task CanChangeDatabase() { string ownerUri = "file://my/sample/file.sql"; @@ -1537,10 +1503,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection connectionService.ChangeConnectionDatabaseContext(ownerUri, otherDbName); - Assert.Equal(otherDbName, connection.Database); + Assert.AreEqual(otherDbName, connection.Database); } - [Fact] + [Test] public async Task CanChangeDatabaseAzure() { @@ -1591,10 +1557,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection connectionService.ChangeConnectionDatabaseContext(ownerUri, otherDbName, true); - Assert.Equal(otherDbName, dbName); + Assert.AreEqual(otherDbName, dbName); } - [Fact] + [Test] public async Task ReturnsFalseIfNotForced() { string ownerUri = "file://my/sample/file.sql"; @@ -1644,13 +1610,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection Assert.False(connectionService.ChangeConnectionDatabaseContext(ownerUri, otherDbName)); - Assert.Equal(defaultDbName, dbName); + Assert.AreEqual(defaultDbName, dbName); } /// /// Test ParseConnectionString /// - [Fact] + [Test] public void ParseConnectionStringTest() { // If we make a connection to a live database @@ -1660,19 +1626,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection var details = service.ParseConnectionString(connectionString); - Assert.Equal("tcp:{servername},1433", details.ServerName); - Assert.Equal("{databasename}", details.DatabaseName); - Assert.Equal("{your_username}", details.UserName); - Assert.Equal("{your_password}", details.Password); - Assert.Equal(false, details.PersistSecurityInfo); - Assert.Equal(false, details.MultipleActiveResultSets); - Assert.Equal(true, details.Encrypt); - Assert.Equal(false, details.TrustServerCertificate); - Assert.Equal(30, details.ConnectTimeout); + Assert.AreEqual("tcp:{servername},1433", details.ServerName); + Assert.AreEqual("{databasename}", details.DatabaseName); + Assert.AreEqual("{your_username}", details.UserName); + Assert.AreEqual("{your_password}", details.Password); + Assert.AreEqual(false, details.PersistSecurityInfo); + Assert.AreEqual(false, details.MultipleActiveResultSets); + Assert.AreEqual(true, details.Encrypt); + Assert.AreEqual(false, details.TrustServerCertificate); + Assert.AreEqual(30, details.ConnectTimeout); } - [Fact] - public async void ConnectingWithAzureAccountUsesToken() + [Test] + public async Task ConnectingWithAzureAccountUsesToken() { // Set up mock connection factory var mockFactory = new Mock(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/DatabaseLocksManagerTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/DatabaseLocksManagerTests.cs index 75ef5cdc..ca096074 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/DatabaseLocksManagerTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/DatabaseLocksManagerTests.cs @@ -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(); @@ -30,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection } } - [Fact] + [Test] public void ReleaseAccessShouldConnectTheConnections() { var connectionLock = new Mock(); @@ -45,7 +46,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection } } - //[Fact] + //[Test] public void SecondProcessToGainAccessShouldWaitForTheFirstProcess() { var connectionLock = new Mock(); @@ -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); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ReliableConnectionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ReliableConnectionTests.cs index b4262bbe..4513cf82 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ReliableConnectionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Connection/ReliableConnectionTests.cs @@ -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] /// /// Tests for ReliableConnection code /// 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); } } } \ No newline at end of file diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/CredentialServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/CredentialServiceTests.cs index faed726a..1182abcf 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/CredentialServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/CredentialServiceTests.cs @@ -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] /// /// 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 /// - 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; - /// - /// Constructor called once for every test - /// - 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( @@ -103,7 +104,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials verify: Assert.True); } - [Fact] + [Test] public async Task SaveCredentialWorksForEmptyPassword() { await TestUtils.RunAndVerify( @@ -111,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials verify: Assert.True); } - [Fact] + [Test] public async Task SaveCredentialSupportsSavingCredentialMultipleTimes() { await TestUtils.RunAndVerify( @@ -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( 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 diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Linux/LinuxInteropTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Linux/LinuxInteropTests.cs index 0d43bb84..5076fc36 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Linux/LinuxInteropTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Linux/LinuxInteropTests.cs @@ -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 } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Win32/CredentialSetTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Win32/CredentialSetTests.cs index 09781c4d..dd1a6c3c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Win32/CredentialSetTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Win32/CredentialSetTests.cs @@ -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(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(); }); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Win32/Win32CredentialTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Win32/Win32CredentialTests.cs index ee42f4ea..5a66b847 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Win32/Win32CredentialTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Credentials/Win32/Win32CredentialTests.cs @@ -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(() => diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DacFx/DacFxTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DacFx/DacFxTests.cs index 816f19e0..e9409733 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DacFx/DacFxTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DacFx/DacFxTests.cs @@ -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"; diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/BackupTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/BackupTests.cs index e0040aee..d9be6167 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/BackupTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/BackupTests.cs @@ -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 /// /// - [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 /// /// - [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 /// /// - [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 /// /// - [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 /// /// - [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 /// /// - [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); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/DatabaseFileInfoTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/DatabaseFileInfoTests.cs index cbdf9ca6..6f012457 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/DatabaseFileInfoTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/DatabaseFileInfoTests.cs @@ -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(() => 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")); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/DisasterRecoveryFileValidatorUnitTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/DisasterRecoveryFileValidatorUnitTests.cs index 6581a410..4fdcd427 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/DisasterRecoveryFileValidatorUnitTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/DisasterRecoveryFileValidatorUnitTests.cs @@ -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 /// 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"; diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/LocalizedPropertyInfoTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/LocalizedPropertyInfoTests.cs index 3f8f2143..e3fb07b7 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/LocalizedPropertyInfoTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/LocalizedPropertyInfoTests.cs @@ -5,29 +5,29 @@ using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery { public class LocalizedPropertyInfoTests { - [Fact] + [Test] public void PropertyDisplayNameShouldReturnNameWhenNotSet() { LocalizedPropertyInfo propertyInfo = new LocalizedPropertyInfo(); propertyInfo.PropertyName = "name"; - Assert.Equal(propertyInfo.PropertyDisplayName, propertyInfo.PropertyName); + Assert.AreEqual(propertyInfo.PropertyDisplayName, propertyInfo.PropertyName); } - [Fact] + [Test] public void PropertyValudDisplayNameShouldReturnValudWhenNotSet() { LocalizedPropertyInfo propertyInfo = new LocalizedPropertyInfo(); propertyInfo.PropertyName = "name"; propertyInfo.PropertyValue = "value"; - Assert.Equal(propertyInfo.PropertyValueDisplayName, propertyInfo.PropertyValue); + Assert.AreEqual(propertyInfo.PropertyValueDisplayName, propertyInfo.PropertyValue); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/RestoreOptionsHelperTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/RestoreOptionsHelperTests.cs index 3c987844..8e228d84 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/RestoreOptionsHelperTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/DisasterRecovery/RestoreOptionsHelperTests.cs @@ -10,13 +10,13 @@ using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.Contracts; using Microsoft.SqlTools.ServiceLayer.DisasterRecovery.RestoreOperation; using Microsoft.SqlTools.ServiceLayer.Utility; using Microsoft.SqlTools.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery { public class RestoreOptionsHelperTests { - [Fact] + [Test] public void VerifyOptionsCreatedSuccessfullyIsResponse() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -27,7 +27,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery VerifyOptions(result, optionValues); } - [Fact] + [Test] public void RelocateAllFilesShouldBeReadOnlyGivenNoDbFiles() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -40,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.True(result[RestoreOptionsHelper.RelocateDbFiles].IsReadOnly); } - [Fact] + [Test] public void DataFileFolderShouldBeReadOnlyGivenRelocateAllFilesSetToFalse() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -54,7 +54,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.True(result[RestoreOptionsHelper.LogFileFolder].IsReadOnly); } - [Fact] + [Test] public void DataFileFolderShouldBeCurrentValueGivenRelocateAllFilesSetToTrue() { string dataFile = "data files"; @@ -70,12 +70,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.NotNull(result); Assert.False(result[RestoreOptionsHelper.DataFileFolder].IsReadOnly); Assert.False(result[RestoreOptionsHelper.LogFileFolder].IsReadOnly); - Assert.Equal(result[RestoreOptionsHelper.DataFileFolder].CurrentValue, dataFile); - Assert.Equal(result[RestoreOptionsHelper.LogFileFolder].CurrentValue, logFile); + Assert.AreEqual(result[RestoreOptionsHelper.DataFileFolder].CurrentValue, dataFile); + Assert.AreEqual(result[RestoreOptionsHelper.LogFileFolder].CurrentValue, logFile); } - [Fact] + [Test] public void KeepReplicationShouldBeReadOnlyGivenRecoveryStateWithNoRecovery() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -87,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.True(result[RestoreOptionsHelper.KeepReplication].IsReadOnly); } - [Fact] + [Test] public void StandbyFileShouldBeReadOnlyGivenRecoveryStateNotWithStandBy() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -99,7 +99,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.True(result[RestoreOptionsHelper.StandbyFile].IsReadOnly); } - [Fact] + [Test] public void BackupTailLogShouldBeReadOnlyTailLogBackupNotPossible() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -112,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.True(result[RestoreOptionsHelper.TailLogBackupFile].IsReadOnly); } - [Fact] + [Test] public void TailLogWithNoRecoveryShouldBeReadOnlyTailLogBackupWithNoRecoveryNotPossible() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -124,7 +124,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.True(result[RestoreOptionsHelper.TailLogWithNoRecovery].IsReadOnly); } - [Fact] + [Test] public void StandbyFileShouldNotBeReadOnlyGivenRecoveryStateWithStandBy() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -136,7 +136,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.False(result[RestoreOptionsHelper.StandbyFile].IsReadOnly); } - [Fact] + [Test] public void CloseExistingConnectionsShouldNotBeReadOnlyGivenCanDropExistingConnectionsSetToTrue() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -148,7 +148,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.False(result[RestoreOptionsHelper.CloseExistingConnections].IsReadOnly); } - [Fact] + [Test] public void CloseExistingConnectionsShouldBeReadOnlyGivenCanDropExistingConnectionsSetToFalse() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -160,7 +160,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.True(result[RestoreOptionsHelper.CloseExistingConnections].IsReadOnly); } - [Fact] + [Test] public void KeepReplicationShouldNotBeReadOnlyGivenRecoveryStateWithNoRecovery() { GeneralRequestDetails optionValues = CreateOptionsTestData(); @@ -172,7 +172,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery Assert.True(result[RestoreOptionsHelper.KeepReplication].IsReadOnly); } - [Fact] + [Test] public void KeepReplicationShouldSetToDefaultValueGivenRecoveryStateWithNoRecovery() { RestoreParams restoreParams = CreateOptionsTestData(); @@ -187,10 +187,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery bool actual = restoreDatabaseTaskDataObject.RestoreOptions.KeepReplication; bool expected = (bool)options[RestoreOptionsHelper.KeepReplication].DefaultValue; - Assert.Equal(actual, expected); + Assert.AreEqual(actual, expected); } - [Fact] + [Test] public void KeepReplicationShouldSetToValueInRequestGivenRecoveryStateWithRecovery() { RestoreParams restoreParams = CreateOptionsTestData(); @@ -204,11 +204,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery bool actual = restoreDatabaseTaskDataObject.RestoreOptions.KeepReplication; bool expected = true; - Assert.Equal(actual, expected); + Assert.AreEqual(actual, expected); } - [Fact] + [Test] public void SourceDatabaseNameShouldSetToDefaultIfNotValid() { RestoreParams restoreParams = CreateOptionsTestData(); @@ -224,10 +224,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery string actual = restoreDatabaseTaskDataObject.SourceDatabaseName; string expected = defaultDbName; - Assert.Equal(actual, expected); + Assert.AreEqual(actual, expected); } - [Fact] + [Test] public void SourceDatabaseNameShouldStayTheSameIfValid() { RestoreParams restoreParams = CreateOptionsTestData(); @@ -243,10 +243,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery string actual = restoreDatabaseTaskDataObject.SourceDatabaseName; string expected = currentDbName; - Assert.Equal(actual, expected); + Assert.AreEqual(actual, expected); } - [Fact] + [Test] public void TargetDatabaseNameShouldBeWhatIsRequested() { RestoreParams restoreParams = CreateOptionsTestData(); @@ -262,10 +262,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery string actual = restoreDatabaseTaskDataObject.TargetDatabaseName; string expected = currentDbName; - Assert.Equal(actual, expected); + Assert.AreEqual(actual, expected); } - [Fact] + [Test] public void TargetDatabaseNameShouldBeWhatIsRequested2() { RestoreParams restoreParams = CreateOptionsTestData(); @@ -281,7 +281,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery string actual = restoreDatabaseTaskDataObject.TargetDatabaseName; string expected = currentDbName; - Assert.Equal(actual, expected); + Assert.AreEqual(actual, expected); } @@ -360,90 +360,90 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery private void VerifyOptions(Dictionary optionInResponse, GeneralRequestDetails optionValues) { RestorePlanDetailInfo planDetailInfo = optionInResponse[RestoreOptionsHelper.DataFileFolder]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.DataFileFolder); - Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue(RestoreOptionsHelper.RelocateDbFiles)); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.DataFileFolder)); - Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue("DefaultDataFileFolder")); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.DataFileFolder); + Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue(RestoreOptionsHelper.RelocateDbFiles)); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.DataFileFolder)); + Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue("DefaultDataFileFolder")); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.LogFileFolder]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.LogFileFolder); - Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue(RestoreOptionsHelper.RelocateDbFiles)); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.LogFileFolder)); - Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue("DefaultLogFileFolder")); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.LogFileFolder); + Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue(RestoreOptionsHelper.RelocateDbFiles)); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.LogFileFolder)); + Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue("DefaultLogFileFolder")); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.RelocateDbFiles]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.RelocateDbFiles); - Assert.Equal(planDetailInfo.IsReadOnly, (optionValues.GetOptionValue>("DbFiles").Count == 0)); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.RelocateDbFiles)); - Assert.Equal(planDetailInfo.DefaultValue, false); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.RelocateDbFiles); + Assert.AreEqual(planDetailInfo.IsReadOnly, (optionValues.GetOptionValue>("DbFiles").Count == 0)); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.RelocateDbFiles)); + Assert.AreEqual(false, planDetailInfo.DefaultValue); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.ReplaceDatabase]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.ReplaceDatabase); - Assert.Equal(planDetailInfo.IsReadOnly, false); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.ReplaceDatabase)); - Assert.Equal(planDetailInfo.DefaultValue, false); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.ReplaceDatabase); + Assert.AreEqual(false, planDetailInfo.IsReadOnly); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.ReplaceDatabase)); + Assert.AreEqual(false, planDetailInfo.DefaultValue); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.KeepReplication]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.KeepReplication); - Assert.Equal(planDetailInfo.IsReadOnly, optionValues.GetOptionValue(RestoreOptionsHelper.RecoveryState) == DatabaseRecoveryState.WithNoRecovery); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.KeepReplication)); - Assert.Equal(planDetailInfo.DefaultValue, false); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.KeepReplication); + Assert.AreEqual(planDetailInfo.IsReadOnly, optionValues.GetOptionValue(RestoreOptionsHelper.RecoveryState) == DatabaseRecoveryState.WithNoRecovery); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.KeepReplication)); + Assert.AreEqual(false, planDetailInfo.DefaultValue); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.SetRestrictedUser]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.SetRestrictedUser); - Assert.Equal(planDetailInfo.IsReadOnly, false); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.SetRestrictedUser)); - Assert.Equal(planDetailInfo.DefaultValue, false); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.SetRestrictedUser); + Assert.AreEqual(false, planDetailInfo.IsReadOnly); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.SetRestrictedUser)); + Assert.AreEqual(false, planDetailInfo.DefaultValue); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.RecoveryState]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.RecoveryState); - Assert.Equal(planDetailInfo.IsReadOnly, false); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.RecoveryState).ToString()); - Assert.Equal(planDetailInfo.DefaultValue, DatabaseRecoveryState.WithRecovery.ToString()); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.RecoveryState); + Assert.AreEqual(false, planDetailInfo.IsReadOnly); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.RecoveryState).ToString()); + Assert.AreEqual(planDetailInfo.DefaultValue, DatabaseRecoveryState.WithRecovery.ToString()); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.StandbyFile]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.StandbyFile); - Assert.Equal(planDetailInfo.IsReadOnly, optionValues.GetOptionValue(RestoreOptionsHelper.RecoveryState) != DatabaseRecoveryState.WithStandBy); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.StandbyFile)); - Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue("GetDefaultStandbyFile")); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.StandbyFile); + Assert.AreEqual(planDetailInfo.IsReadOnly, optionValues.GetOptionValue(RestoreOptionsHelper.RecoveryState) != DatabaseRecoveryState.WithStandBy); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.StandbyFile)); + Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue("GetDefaultStandbyFile")); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.BackupTailLog]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.BackupTailLog); - Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue("IsTailLogBackupPossible")); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.BackupTailLog)); - Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue("IsTailLogBackupPossible")); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.BackupTailLog); + Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue("IsTailLogBackupPossible")); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.BackupTailLog)); + Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue("IsTailLogBackupPossible")); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.TailLogBackupFile]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.TailLogBackupFile); - Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue("IsTailLogBackupPossible") + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.TailLogBackupFile); + Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue("IsTailLogBackupPossible") | !optionValues.GetOptionValue(RestoreOptionsHelper.BackupTailLog)); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue("TailLogBackupFile")); - Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue("GetDefaultTailLogbackupFile")); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue("TailLogBackupFile")); + Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue("GetDefaultTailLogbackupFile")); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.TailLogWithNoRecovery]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.TailLogWithNoRecovery); - Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue("IsTailLogBackupWithNoRecoveryPossible") + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.TailLogWithNoRecovery); + Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue("IsTailLogBackupWithNoRecoveryPossible") | !optionValues.GetOptionValue(RestoreOptionsHelper.BackupTailLog)); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue("TailLogWithNoRecovery")); - Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue("IsTailLogBackupWithNoRecoveryPossible")); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue("TailLogWithNoRecovery")); + Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue("IsTailLogBackupWithNoRecoveryPossible")); + Assert.AreEqual(true, planDetailInfo.IsVisiable); planDetailInfo = optionInResponse[RestoreOptionsHelper.CloseExistingConnections]; - Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.CloseExistingConnections); - Assert.Equal(planDetailInfo.IsReadOnly, false); - Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.CloseExistingConnections)); - Assert.Equal(planDetailInfo.DefaultValue, false); - Assert.Equal(planDetailInfo.IsVisiable, true); + Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.CloseExistingConnections); + Assert.AreEqual(false, planDetailInfo.IsReadOnly); + Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue(RestoreOptionsHelper.CloseExistingConnections)); + Assert.AreEqual(false, planDetailInfo.DefaultValue); + Assert.AreEqual(true, planDetailInfo.IsVisiable); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/CellUpdateTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/CellUpdateTests.cs index 242801ec..6ae12f1f 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/CellUpdateTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/CellUpdateTests.cs @@ -9,13 +9,13 @@ using System.Data.Common; using Microsoft.SqlTools.ServiceLayer.EditData.Contracts; using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { public class CellUpdateTests { - [Fact] + [Test] public void NullColumnTest() { // If: I attempt to create a CellUpdate with a null column @@ -23,7 +23,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new CellUpdate(null, string.Empty)); } - [Fact] + [Test] public void NullStringValueTest() { // If: I attempt to create a CellUpdate with a null string value @@ -31,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new CellUpdate(GetWrapper("ntext"), null)); } - [Fact] + [Test] public void NullStringAllowedTest() { // If: I attempt to create a CellUpdate to set it to NULL @@ -41,13 +41,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: The value should be a DBNull and the string value should be the same as what // was given - Assert.IsType(cu.Value); - Assert.Equal(DBNull.Value, cu.Value); - Assert.Equal(nullString, cu.ValueAsString); - Assert.Equal(col, cu.Column); + Assert.That(cu.Value, Is.InstanceOf()); + Assert.AreEqual(DBNull.Value, cu.Value); + Assert.AreEqual(nullString, cu.ValueAsString); + Assert.AreEqual(col, cu.Column); } - [Fact] + [Test] public void NullStringNotAllowedTest() { // If: I attempt to create a cell update to set to null when its not allowed @@ -55,7 +55,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new CellUpdate(GetWrapper("ntext", false), "NULL")); } - [Fact] + [Test] public void NullTextStringTest() { // If: I attempt to create a CellUpdate with the text 'NULL' (with mixed case) @@ -63,16 +63,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData CellUpdate cu = new CellUpdate(col, "'NULL'"); // Then: The value should be NULL - Assert.IsType(cu.Value); - Assert.Equal("NULL", cu.Value); - Assert.Equal("'NULL'", cu.ValueAsString); - Assert.Equal(col, cu.Column); + Assert.That(cu.Value, Is.InstanceOf()); + Assert.AreEqual("NULL", cu.Value); + Assert.AreEqual("'NULL'", cu.ValueAsString); + Assert.AreEqual(col, cu.Column); } - [Theory] - [InlineData("This is way too long")] - [InlineData("TooLong")] - public void StringTooLongTest(string value) + [Test] + public void StringTooLongTest([Values("This is way too long", "TooLong")]string value) { // If: I attempt to create a CellUpdate to set it to a large string // Then: I should get an exception thrown @@ -80,8 +78,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new CellUpdate(col, value)); } - [Theory] - [MemberData(nameof(ByteArrayTestParams))] + [Test] + [TestCaseSource(nameof(ByteArrayTestParams))] public void ByteArrayTest(string strValue, byte[] expectedValue, string expectedString) { // If: I attempt to create a CellUpdate for a binary column @@ -89,10 +87,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData CellUpdate cu = new CellUpdate(col, strValue); // Then: The value should be a binary and should match the expected data - Assert.IsType(cu.Value); - Assert.Equal(expectedValue, cu.Value); - Assert.Equal(expectedString, cu.ValueAsString); - Assert.Equal(col, cu.Column); + Assert.That(cu.Value, Is.InstanceOf()); + Assert.AreEqual(expectedValue, cu.Value); + Assert.AreEqual(expectedString, cu.ValueAsString); + Assert.AreEqual(col, cu.Column); } public static IEnumerable ByteArrayTestParams @@ -134,7 +132,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } } - [Fact] + [Test] public void ByteArrayInvalidFormatTest() { // If: I attempt to create a CellUpdate for a binary column @@ -143,8 +141,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new CellUpdate(col, "this is totally invalid")); } - [Theory] - [MemberData(nameof(BoolTestParams))] + [Test] + [TestCaseSource(nameof(BoolTestParams))] public void BoolTest(string input, bool output, string outputString) { // If: I attempt to create a CellUpdate for a boolean column @@ -152,13 +150,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData CellUpdate cu = new CellUpdate(col, input); // Then: The value should match what was expected - Assert.IsType(cu.Value); - Assert.Equal(output, cu.Value); - Assert.Equal(outputString, cu.ValueAsString); - Assert.Equal(col, cu.Column); + Assert.That(cu.Value, Is.InstanceOf()); + Assert.AreEqual(output, cu.Value); + Assert.AreEqual(outputString, cu.ValueAsString); + Assert.AreEqual(col, cu.Column); } - public static IEnumerable BoolTestParams + private static IEnumerable BoolTestParams { get { @@ -169,7 +167,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } } - [Fact] + [Test] public void BoolInvalidFormatTest() { // If: I create a CellUpdate for a bool column and provide an invalid numeric value @@ -178,10 +176,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new CellUpdate(col, "12345")); } - [Theory] - [InlineData("24:00:00")] - [InlineData("105:00:00")] - public void TimeSpanTooLargeTest(string value) + [Test] + public void TimeSpanTooLargeTest([Values("24:00:00", "105:00:00")] string value) { // If: I create a cell update for a timespan column and provide a value that is over 24hrs // Then: It should throw an exception @@ -189,21 +185,33 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new CellUpdate(col, value)); } - [Theory] - [MemberData(nameof(RoundTripTestParams))] - public void RoundTripTest(DbColumnWrapper col, object obj) + /// + /// Not using TestCaseSource because nUnit's test name generator + /// doesn't like DbColumnWrapper objects as a source, due + /// to that class lacking a ToString override. + /// + /// + /// + [Test] + public void RoundTripTest() { - // Setup: Figure out the test string - string testString = obj.ToString(); - - // If: I attempt to create a CellUpdate - CellUpdate cu = new CellUpdate(col, testString); - - // Then: The value and type should match what we put in - Assert.IsType(col.DataType, cu.Value); - Assert.Equal(obj, cu.Value); - Assert.Equal(testString, cu.ValueAsString); - Assert.Equal(col, cu.Column); + foreach (var inputs in RoundTripTestParams) + { + + var col = (DbColumnWrapper)inputs[0]; + var obj = inputs[1]; + // Setup: Figure out the test string + string testString = obj.ToString(); + + // If: I attempt to create a CellUpdate + CellUpdate cu = new CellUpdate(col, testString); + + // Then: The value and type should match what we put in + Assert.That(cu.Value, Is.InstanceOf(col.DataType)); + Assert.AreEqual(obj, cu.Value); + Assert.AreEqual(testString, cu.ValueAsString); + Assert.AreEqual(col, cu.Column); + } } public static IEnumerable RoundTripTestParams @@ -228,10 +236,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } } - [Theory] - [InlineData(true)] - [InlineData(false)] - public void AsDbCellValue(bool isNull) + [Test] + public void AsDbCellValue([Values]bool isNull) { // Setup: Create a cell update var value = isNull ? "NULL" : "foo"; @@ -246,19 +252,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.NotNull(dbc); // ... The display value should be the same as the value we supplied - Assert.Equal(value, dbc.DisplayValue); + Assert.AreEqual(value, dbc.DisplayValue); // ... The null-ness of the value should be the same as what we supplied - Assert.Equal(isNull, dbc.IsNull); + Assert.AreEqual(isNull, dbc.IsNull); // ... We don't care *too* much about the raw value, but we'll check it anyhow - Assert.Equal(isNull ? (object)DBNull.Value : value, dbc.RawObject); + Assert.AreEqual(isNull ? (object)DBNull.Value : value, dbc.RawObject); } - [Theory] - [InlineData(true)] - [InlineData(false)] - public void AsEditCellValue(bool isNull) + [Test] + public void AsEditCellValue([Values]bool isNull) { // Setup: Create a cell update var value = isNull ? "NULL" : "foo"; @@ -273,13 +277,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.NotNull(ec); // ... The display value should be the same as the value we supplied - Assert.Equal(value, ec.DisplayValue); + Assert.AreEqual(value, ec.DisplayValue); // ... The null-ness of the value should be the same as what we supplied - Assert.Equal(isNull, ec.IsNull); + Assert.AreEqual(isNull, ec.IsNull); // ... We don't care *too* much about the raw value, but we'll check it anyhow - Assert.Equal(isNull ? (object)DBNull.Value : value, ec.RawObject); + Assert.AreEqual(isNull ? (object)DBNull.Value : value, ec.RawObject); // ... The edit cell should be dirty Assert.True(ec.IsDirty); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/EditCellTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/EditCellTests.cs index 85fcb452..568afbdb 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/EditCellTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/EditCellTests.cs @@ -6,13 +6,13 @@ using System; using Microsoft.SqlTools.ServiceLayer.EditData.Contracts; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { public class EditCellTests { - [Fact] + [Test] public void ConstructNullDbCell() { // If: I construct an EditCell with a null DbCellValue @@ -20,7 +20,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new EditCell(null, true)); } - [Fact] + [Test] public void ConstructValid() { // Setup: Create a DbCellValue to copy the values from @@ -36,9 +36,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... The values I provided in the DbCellValue should be present - Assert.Equal(source.DisplayValue, ec.DisplayValue); - Assert.Equal(source.IsNull, ec.IsNull); - Assert.Equal(source.RawObject, ec.RawObject); + Assert.AreEqual(source.DisplayValue, ec.DisplayValue); + Assert.AreEqual(source.IsNull, ec.IsNull); + Assert.AreEqual(source.RawObject, ec.RawObject); // ... The is dirty value I set should be present Assert.True(ec.IsDirty); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/FilterMetadataTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/FilterMetadataTest.cs index 4d1610fd..56608ff1 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/FilterMetadataTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/FilterMetadataTest.cs @@ -6,7 +6,7 @@ using Microsoft.SqlTools.ServiceLayer.EditData; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { @@ -19,7 +19,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData /// public class FilterMetadataTest { - [Fact] + [Test] public void BasicFilterTest() { EditColumnMetadata[] metas = CreateMetadataColumns(new string[] { "[col1]", "[col2]", "[col3]" }); @@ -29,7 +29,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData ValidateFilteredData(filteredData, cols); } - [Fact] + [Test] public void ReorderedResultsTest() { EditColumnMetadata[] metas = CreateMetadataColumns(new string[] { "[col1]", "[col2]", "[col3]" }); @@ -39,7 +39,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData ValidateFilteredData(filteredData, cols); } - [Fact] + [Test] public void LessResultColumnsTest() { EditColumnMetadata[] metas = CreateMetadataColumns(new string[] { "[col1]", "[col2]", "[col3]", "[fillerCol1]", "[fillerCol2]" }); @@ -49,7 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData ValidateFilteredData(filteredData, cols); } - [Fact] + [Test] public void EmptyDataTest() { EditColumnMetadata[] metas = new EditColumnMetadata[0]; @@ -81,13 +81,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData private void ValidateFilteredData(EditColumnMetadata[] filteredData, DbColumnWrapper[] cols) { - Assert.Equal(cols.Length, filteredData.Length); + Assert.AreEqual(cols.Length, filteredData.Length); for (int i = 0; i < cols.Length; i++) { - Assert.Equal(cols[i].ColumnName, filteredData[i].EscapedName); + Assert.AreEqual(cols[i].ColumnName, filteredData[i].EscapedName); if (cols[i].ColumnOrdinal.HasValue) { - Assert.Equal(cols[i].ColumnOrdinal, filteredData[i].Ordinal); + Assert.AreEqual(cols[i].ColumnOrdinal, filteredData[i].Ordinal); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowCreateTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowCreateTests.cs index a9185a3c..56e94414 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowCreateTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowCreateTests.cs @@ -15,13 +15,13 @@ using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement; using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { public class RowCreateTests { - [Fact] + [Test] public async Task RowCreateConstruction() { // Setup: Create the values to store @@ -33,9 +33,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData RowCreate rc = new RowCreate(rowId, rs, data.TableMetadata); // Then: The values I provided should be available - Assert.Equal(rowId, rc.RowId); - Assert.Equal(rs, rc.AssociatedResultSet); - Assert.Equal(data.TableMetadata, rc.AssociatedObjectMetadata); + Assert.AreEqual(rowId, rc.RowId); + Assert.AreEqual(rs, rc.AssociatedResultSet); + Assert.AreEqual(data.TableMetadata, rc.AssociatedObjectMetadata); } #region GetScript Tests @@ -58,8 +58,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } } - [Theory] - [MemberData(nameof(GetScriptMissingCellsData))] + [Test] + [TestCaseSource(nameof(GetScriptMissingCellsData))] public async Task GetScriptMissingCell(bool includeIdentity, int defaultCols, int nullableCols, int valuesToSkipSetting) { // Setup: Generate the parameters for the row create @@ -108,8 +108,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } } - [Theory] - [MemberData(nameof(GetScriptData))] + [Test] + [TestCaseSource(nameof(GetScriptData))] public async Task GetScript(bool includeIdentity, int colsWithDefaultConstraints, int colsThatAllowNull, int valuesToSkipSetting, RegexExpectedOutput expectedOutput) { // Setup: @@ -142,7 +142,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(m.Success); // Table name matches - Assert.Equal(Common.TableName, m.Groups[1].Value); + Assert.AreEqual(Common.TableName, m.Groups[1].Value); } else { @@ -152,24 +152,22 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(m.Success); // Table name matches - Assert.Equal(Common.TableName, m.Groups[1].Value); + Assert.AreEqual(Common.TableName, m.Groups[1].Value); // In columns match string cols = m.Groups[2].Value; - Assert.Equal(expectedOutput.ExpectedInColumns, cols.Split(',').Length); + Assert.AreEqual(expectedOutput.ExpectedInColumns, cols.Split(',').Length); // In values match string vals = m.Groups[3].Value; - Assert.Equal(expectedOutput.ExpectedInValues, vals.Split(',').Length); + Assert.AreEqual(expectedOutput.ExpectedInValues, vals.Split(',').Length); } } #endregion - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task ApplyChanges(bool includeIdentity) + [Test] + public async Task ApplyChanges([Values]bool includeIdentity) { // Setup: // ... Generate the parameters for the row create @@ -185,12 +183,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData await rc.ApplyChanges(newRowReader); // Then: The result set should have an additional row in it - Assert.Equal(2, rs.RowCount); + Assert.AreEqual(2, rs.RowCount); } #region GetCommand Tests - [Fact] + [Test] public async Task GetCommandNullConnection() { // Setup: Create a row create @@ -219,8 +217,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } } - [Theory] - [MemberData(nameof(GetCommandMissingCellsData))] + [Test] + [TestCaseSource(nameof(GetCommandMissingCellsData))] public async Task GetCommandMissingCellNoDefault(bool includeIdentity, int defaultCols, int nullableCols, int valuesToSkip) { @@ -274,8 +272,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } } - [Theory] - [MemberData(nameof(GetCommandData))] + [Test] + [TestCaseSource(nameof(GetCommandData))] public async Task GetCommand(bool includeIdentity, int defaultCols, int nullableCols, int valuesToSkip, RegexExpectedOutput expectedOutput) { // Setup: @@ -298,7 +296,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.NotNull(cmd); // ... There should be parameters in it - Assert.Equal(expectedOutput.ExpectedInValues, cmd.Parameters.Count); + Assert.AreEqual(expectedOutput.ExpectedInValues, cmd.Parameters.Count); // ... The script should match the expected regex output ValidateCommandAgainstRegex(cmd.CommandText, expectedOutput); @@ -308,7 +306,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { // Break the query into parts string[] splitSql = sql.Split(Environment.NewLine); - Assert.Equal(3, splitSql.Length); + Assert.AreEqual(3, splitSql.Length); // Check the declare statement first Regex declareRegex = new Regex(@"^DECLARE @(.+) TABLE \((.+)\)$"); @@ -321,7 +319,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Correct number of columns in declared table string[] declareCols = declareMatch.Groups[2].Value.Split(", "); - Assert.Equal(expectedOutput.ExpectedOutColumns, declareCols.Length); + Assert.AreEqual(expectedOutput.ExpectedOutColumns, declareCols.Length); // Check the insert statement in the middle if (expectedOutput.ExpectedInColumns == 0 || expectedOutput.ExpectedInValues == 0) @@ -332,16 +330,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(insertMatch.Success); // Table name matches - Assert.Equal(Common.TableName, insertMatch.Groups[1].Value); + Assert.AreEqual(Common.TableName, insertMatch.Groups[1].Value); - // Output columns match string[] outCols = insertMatch.Groups[2].Value.Split(", "); - Assert.Equal(expectedOutput.ExpectedOutColumns, outCols.Length); - Assert.All(outCols, col => Assert.StartsWith("inserted.", col)); - - // Output table name matches - Assert.StartsWith("Insert", insertMatch.Groups[3].Value); - Assert.EndsWith("Output", insertMatch.Groups[3].Value); + Assert.AreEqual(expectedOutput.ExpectedOutColumns, outCols.Length); + Assert.That(outCols, Has.All.StartsWith("inserted."), "Output columns match"); + + Assert.Multiple(() => + { + Assert.That(insertMatch.Groups[3].Value, Does.StartWith("Insert"), "Output table name matches"); + Assert.That(insertMatch.Groups[3].Value, Does.EndWith("Output")); + }); } else { @@ -351,25 +350,31 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(insertMatch.Success); // Table name matches - Assert.Equal(Common.TableName, insertMatch.Groups[1].Value); + Assert.AreEqual(Common.TableName, insertMatch.Groups[1].Value); - // Output columns match + // string[] outCols = insertMatch.Groups[3].Value.Split(", "); - Assert.Equal(expectedOutput.ExpectedOutColumns, outCols.Length); - Assert.All(outCols, col => Assert.StartsWith("inserted.", col)); + Assert.Multiple(() => + { + Assert.AreEqual(expectedOutput.ExpectedOutColumns, outCols.Length); + Assert.That(outCols, Has.All.StartsWith("inserted."), "Output columns match"); + }); // In columns match string[] inCols = insertMatch.Groups[2].Value.Split(", "); - Assert.Equal(expectedOutput.ExpectedInColumns, inCols.Length); - - // Output table name matches - Assert.StartsWith("Insert", insertMatch.Groups[4].Value); - Assert.EndsWith("Output", insertMatch.Groups[4].Value); - + Assert.AreEqual(expectedOutput.ExpectedInColumns, inCols.Length); + + // Output table name matches + Assert.Multiple(() => + { + Assert.That(insertMatch.Groups[4].Value, Does.StartWith("Insert")); + Assert.That(insertMatch.Groups[4].Value, Does.EndWith("Output")); + }); + // In values match string[] inVals = insertMatch.Groups[5].Value.Split(", "); - Assert.Equal(expectedOutput.ExpectedInValues, inVals.Length); - Assert.All(inVals, val => Assert.Matches(@"@.+\d+_\d+", val)); + Assert.AreEqual(expectedOutput.ExpectedInValues, inVals.Length); + Assert.That(inVals, Has.All.Match(@"@.+\d+_\d+")); } // Check the select statement last @@ -379,7 +384,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Correct number of columns in declared table string[] selectCols = selectMatch.Groups[1].Value.Split(", "); - Assert.Equal(expectedOutput.ExpectedOutColumns, selectCols.Length); + Assert.AreEqual(expectedOutput.ExpectedOutColumns, selectCols.Length); // Declared table name matches Assert.True(selectMatch.Groups[2].Value.StartsWith("Insert")); @@ -390,7 +395,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region GetEditRow Tests - [Fact] + [Test] public async Task GetEditRowNoAdditions() { // Setup: Generate a standard row create @@ -405,19 +410,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... The row should not be clean Assert.True(er.IsDirty); - Assert.Equal(EditRow.EditRowState.DirtyInsert, er.State); + Assert.AreEqual(EditRow.EditRowState.DirtyInsert, er.State); // ... The row should have a bunch of empty cells (equal to number of columns) and all are dirty - Assert.Equal(rc.newCells.Length, er.Cells.Length); - Assert.All(er.Cells, ec => - { - Assert.Equal(string.Empty, ec.DisplayValue); - Assert.False(ec.IsNull); - Assert.True(ec.IsDirty); - }); + Assert.AreEqual(rc.newCells.Length, er.Cells.Length); + Assert.That(er.Cells.Select(c => c.DisplayValue), Has.All.Empty); + Assert.That(er.Cells.Select(ec => ec.IsDirty), Has.All.True); } - [Fact] + [Test] public async Task GetEditRowWithDefaultValue() { // Setup: Generate a row create with default values @@ -435,19 +436,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... The row should not be clean Assert.True(er.IsDirty); - Assert.Equal(EditRow.EditRowState.DirtyInsert, er.State); + Assert.AreEqual(EditRow.EditRowState.DirtyInsert, er.State); // ... The row sould have a bunch of default values (equal to number of columns) and all are dirty - Assert.Equal(rc.newCells.Length, er.Cells.Length); - Assert.All(er.Cells, ec => - { - Assert.Equal(Common.DefaultValue, ec.DisplayValue); - Assert.False(ec.IsNull); // TODO: Update when we support null default values better - Assert.True(ec.IsDirty); - }); + Assert.AreEqual(rc.newCells.Length, er.Cells.Length); + Assert.That(er.Cells.Select(ec => ec.DisplayValue), Has.All.EqualTo(Common.DefaultValue)); + Assert.That(er.Cells.Select(ec => ec.IsDirty), Has.All.True); } - [Fact] + [Test] public async Task GetEditRowWithCalculatedValue() { // Setup: Generate a row create with an identity column @@ -462,28 +459,23 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... The row should not be null Assert.NotNull(er); - Assert.Equal(er.Id, rowId); + Assert.AreEqual(er.Id, rowId); // ... The row should not be clean Assert.True(er.IsDirty); - Assert.Equal(EditRow.EditRowState.DirtyInsert, er.State); + Assert.AreEqual(EditRow.EditRowState.DirtyInsert, er.State); // ... The row should have a TBD for the identity column - Assert.Equal(rc.newCells.Length, er.Cells.Length); - Assert.Equal(SR.EditDataComputedColumnPlaceholder, er.Cells[0].DisplayValue); + Assert.AreEqual(rc.newCells.Length, er.Cells.Length); + Assert.AreEqual(SR.EditDataComputedColumnPlaceholder, er.Cells[0].DisplayValue); Assert.False(er.Cells[0].IsNull); - Assert.True(er.Cells[0].IsDirty); - - // ... The rest of the cells should have empty display values - Assert.All(er.Cells.Skip(1), ec => - { - Assert.Equal(string.Empty, ec.DisplayValue); - Assert.False(ec.IsNull); - Assert.True(ec.IsDirty); - }); + Assert.True(er.Cells[0].IsDirty); + + // ... The rest of the cells should have empty display values + Assert.That(er.Cells.Skip(1).Select(ec => new { ec.DisplayValue, ec.IsNull, ec.IsDirty }), Has.All.EqualTo(new { DisplayValue = string.Empty, IsNull = false, IsDirty = true })); } - [Fact] + [Test] public async Task GetEditRowWithAdditions() { // Setp: Generate a row create with a cell added to it @@ -497,14 +489,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... The row should not be null and contain the same number of cells as columns Assert.NotNull(er); - Assert.Equal(EditRow.EditRowState.DirtyInsert, er.State); + Assert.AreEqual(EditRow.EditRowState.DirtyInsert, er.State); // ... The row should not be clean Assert.True(er.IsDirty); - Assert.Equal(EditRow.EditRowState.DirtyInsert, er.State); + Assert.AreEqual(EditRow.EditRowState.DirtyInsert, er.State); // ... The row should have a single non-empty cell at the beginning that is dirty - Assert.Equal(setValue, er.Cells[0].DisplayValue); + Assert.AreEqual(setValue, er.Cells[0].DisplayValue); Assert.False(er.Cells[0].IsNull); Assert.True(er.Cells[0].IsDirty); @@ -512,7 +504,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData for (int i = 1; i < er.Cells.Length; i++) { EditCell ec = er.Cells[i]; - Assert.Equal(string.Empty, ec.DisplayValue); + Assert.AreEqual(string.Empty, ec.DisplayValue); Assert.False(ec.IsNull); Assert.True(ec.IsDirty); } @@ -522,11 +514,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region SetCell Tests - [Theory] - [InlineData(-1)] // Negative - [InlineData(3)] // At edge of acceptable values - [InlineData(100)] // Way too large value - public async Task SetCellOutOfRange(int columnId) + [Test] + public async Task SetCellOutOfRange([Values(-1, 3, 100)]int columnId) { // Setup: Generate a row create RowCreate rc = await GetStandardRowCreate(); @@ -535,7 +524,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => rc.SetCell(columnId, string.Empty)); } - [Fact] + [Test] public async Task SetCellNoChange() { // Setup: Generate a row create @@ -549,7 +538,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... The returned value should be equal to what we provided Assert.NotNull(eucr); Assert.NotNull(eucr.Cell); - Assert.Equal(updateValue, eucr.Cell.DisplayValue); + Assert.AreEqual(updateValue, eucr.Cell.DisplayValue); Assert.False(eucr.Cell.IsNull); // ... The returned value should be dirty @@ -562,7 +551,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.NotNull(rc.newCells[0]); } - [Fact] + [Test] public async Task SetCellHasCorrections() { // Setup: @@ -591,7 +580,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... The returned value should be equal to what we provided Assert.NotNull(eucr); Assert.NotNull(eucr.Cell); - Assert.NotEqual("1000", eucr.Cell.DisplayValue); + Assert.That(eucr.Cell.DisplayValue, Is.Not.EqualTo("1000")); Assert.False(eucr.Cell.IsNull); // ... The returned value should be dirty @@ -604,7 +593,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.NotNull(rc.newCells[0]); } - [Fact] + [Test] public async Task SetCellNull() { // Setup: Generate a row create @@ -620,7 +609,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... The returned value should be equal to what we provided Assert.NotNull(eucr); Assert.NotNull(eucr.Cell); - Assert.Equal(nullValue, eucr.Cell.DisplayValue); + Assert.AreEqual(nullValue, eucr.Cell.DisplayValue); Assert.True(eucr.Cell.IsNull); // ... The returned value should be dirty @@ -637,11 +626,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region RevertCell Tests - [Theory] - [InlineData(-1)] // Negative - [InlineData(3)] // At edge of acceptable values - [InlineData(100)] // Way too large value - public async Task RevertCellOutOfRange(int columnId) + [Test] + public async Task RevertCellOutOfRange([Values(-1,3,100)]int columnId) { // Setup: Generate the row create RowCreate rc = await GetStandardRowCreate(); @@ -651,10 +637,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => rc.RevertCell(columnId)); } - [Theory] - [InlineData(1)] - [InlineData(0)] - public async Task RevertCellNotSet(int defaultCols) + [Test] + public async Task RevertCellNotSet([Values(0,1)]int defaultCols) { // Setup: // ... Generate the parameters for the row create @@ -672,7 +656,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... We should get back an edit cell with a value based on the default value string expectedDisplayValue = defaultCols > 0 ? Common.DefaultValue : string.Empty; Assert.NotNull(result.Cell); - Assert.Equal(expectedDisplayValue, result.Cell.DisplayValue); + Assert.AreEqual(expectedDisplayValue, result.Cell.DisplayValue); Assert.False(result.Cell.IsNull); // TODO: Modify to support null defaults // ... The row should be dirty @@ -682,10 +666,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Null(rc.newCells[0]); } - [Theory] - [InlineData(1)] - [InlineData(0)] - public async Task RevertCellThatWasSet(int defaultCols) + [Test] + public async Task RevertCellThatWasSet([Values(0, 1)] int defaultCols) { // Setup: // ... Generate the parameters for the row create @@ -704,7 +686,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... We should get back an edit cell with a value based on the default value string expectedDisplayValue = defaultCols > 0 ? Common.DefaultValue : string.Empty; Assert.NotNull(result.Cell); - Assert.Equal(expectedDisplayValue, result.Cell.DisplayValue); + Assert.AreEqual(expectedDisplayValue, result.Cell.DisplayValue); Assert.False(result.Cell.IsNull); // TODO: Modify to support null defaults // ... The row should be dirty diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowDeleteTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowDeleteTests.cs index a775072e..8784e9e4 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowDeleteTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowDeleteTests.cs @@ -13,13 +13,13 @@ using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement; using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { public class RowDeleteTests { - [Fact] + [Test] public async Task RowDeleteConstruction() { // Setup: Create the values to store @@ -30,15 +30,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData RowDelete rc = new RowDelete(100, rs, data.TableMetadata); // Then: The values I provided should be available - Assert.Equal(100, rc.RowId); - Assert.Equal(rs, rc.AssociatedResultSet); - Assert.Equal(data.TableMetadata, rc.AssociatedObjectMetadata); + Assert.AreEqual(100, rc.RowId); + Assert.AreEqual(rs, rc.AssociatedResultSet); + Assert.AreEqual(data.TableMetadata, rc.AssociatedObjectMetadata); } - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task GetScriptTest(bool isMemoryOptimized) + [Test] + public async Task GetScriptTest([Values]bool isMemoryOptimized) { Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(isMemoryOptimized, true, 0, 0); ResultSet rs = await Common.GetResultSet(data.DbColumns, true); @@ -51,16 +49,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... The script should not be null Assert.NotNull(script); - // ... It should be formatted as a delete script + // ... string scriptStart = $"DELETE FROM {data.TableMetadata.EscapedMultipartName}"; if (isMemoryOptimized) { scriptStart += " WITH(SNAPSHOT)"; } - Assert.StartsWith(scriptStart, script); + Assert.That(script, Does.StartWith(scriptStart), "It should be formatted as a delete script"); } - [Fact] + [Test] public async Task ApplyChanges() { // Setup: Generate the parameters for the row delete object @@ -72,15 +70,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData await rd.ApplyChanges(null); // Reader not used, can be null // Then : The result set should have one less row in it - Assert.Equal(0, rs.RowCount); + Assert.AreEqual(0, rs.RowCount); } - [Theory] - [InlineData(true, true)] - [InlineData(false, true)] - [InlineData(true, false)] - [InlineData(false, false)] - public async Task GetCommand(bool includeIdentity, bool isMemoryOptimized) + [Test] + public async Task GetCommand([Values]bool includeIdentity, [Values]bool isMemoryOptimized) { // Setup: // ... Create a row delete @@ -100,7 +94,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... Only the keys should be used for parameters int expectedKeys = includeIdentity ? 1 : 3; - Assert.Equal(expectedKeys, cmd.Parameters.Count); + Assert.AreEqual(expectedKeys, cmd.Parameters.Count); // ... It should be formatted into an delete script string regexTest = isMemoryOptimized @@ -112,17 +106,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... There should be a table string tbl = m.Groups[1].Value; - Assert.Equal(data.TableMetadata.EscapedMultipartName, tbl); + Assert.AreEqual(data.TableMetadata.EscapedMultipartName, tbl); // ... There should be as many where components as there are keys string[] whereComponents = m.Groups[2].Value.Split(new[] {"AND"}, StringSplitOptions.None); - Assert.Equal(expectedKeys, whereComponents.Length); + Assert.AreEqual(expectedKeys, whereComponents.Length); - // ... Each component should have be equal to a parameter - Assert.All(whereComponents, c => Assert.True(Regex.IsMatch(c.Trim(), @"\(.+ = @.+\)"))); + Assert.That(whereComponents.Select(c => c.Trim()), Has.All.Match(@"\(.+ = @.+\)"), "Each component should be equal to a parameter"); } - [Fact] + [Test] public async Task GetCommandNullConnection() { // Setup: Create a row delete @@ -133,7 +126,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => rd.GetCommand(null)); } - [Fact] + [Test] public async Task GetEditRow() { // Setup: Create a row delete @@ -148,26 +141,26 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... The state should be dirty Assert.True(er.IsDirty); - Assert.Equal(EditRow.EditRowState.DirtyDelete, er.State); + Assert.AreEqual(EditRow.EditRowState.DirtyDelete, er.State); // ... The ID should be the same as the one provided - Assert.Equal(0, er.Id); + Assert.AreEqual(0, er.Id); // ... The row should match the cells that were given and should be dirty - Assert.Equal(cells.Length, er.Cells.Length); + Assert.AreEqual(cells.Length, er.Cells.Length); for (int i = 0; i < cells.Length; i++) { DbCellValue originalCell = cells[i]; EditCell outputCell = er.Cells[i]; - Assert.Equal(originalCell.DisplayValue, outputCell.DisplayValue); - Assert.Equal(originalCell.IsNull, outputCell.IsNull); + Assert.AreEqual(originalCell.DisplayValue, outputCell.DisplayValue); + Assert.AreEqual(originalCell.IsNull, outputCell.IsNull); Assert.True(outputCell.IsDirty); // Note: No real need to check the RawObject property } } - [Fact] + [Test] public async Task GetEditNullRow() { // Setup: Create a row delete @@ -178,7 +171,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => rd.GetEditRow(null)); } - [Fact] + [Test] public async Task SetCell() { // Setup: Create a row delete @@ -189,7 +182,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => rd.SetCell(0, null)); } - [Fact] + [Test] public async Task RevertCell() { // Setup: Create a row delete diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowEditBaseTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowEditBaseTests.cs index 2cafdee1..c9217b3c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowEditBaseTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowEditBaseTests.cs @@ -17,13 +17,13 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { public class RowEditBaseTests { - [Fact] + [Test] public void ConstructWithoutExtendedMetadata() { // Setup: Create a table metadata that has not been extended @@ -34,11 +34,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new RowEditTester(null, etm)); } - [Theory] - [InlineData(-1)] // Negative index - [InlineData(2)] // Equal to count of columns - [InlineData(100)] // Index larger than number of columns - public async Task ValidateUpdatableColumnOutOfRange(int columnId) + [Test] + public async Task ValidateUpdatableColumnOutOfRange([Values(-1,2,100)]int columnId) { // Setup: Create a result set var rs = await GetResultSet( @@ -55,7 +52,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => tester.ValidateColumn(columnId)); } - [Fact] + [Test] public async Task ValidateUpdatableColumnNotUpdatable() { // Setup: Create a result set with an identity column @@ -73,8 +70,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => tester.ValidateColumn(0)); } - [Theory] - [MemberData(nameof(GetWhereClauseIsNotNullData))] + [Test] + [TestCaseSource(nameof(GetWhereClauseIsNotNullData))] public async Task GetWhereClauseSimple(DbColumn col, object val, string nullClause) { // Setup: Create a result set and metadata provider with a single column @@ -124,7 +121,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } } - [Fact] + [Test] public async Task GetWhereClauseMultipleKeyColumns() { // Setup: Create a result set and metadata provider with multiple key columns @@ -136,7 +133,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData rt.ValidateWhereClauseMultipleKeys(); } - [Fact] + [Test] public async Task GetWhereClauseNoKeyColumns() { // Setup: Create a result set and metadata provider with no key columns @@ -148,7 +145,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData rt.ValidateWhereClauseNoKeys(); } - [Fact] + [Test] public async Task SortingByTypeTest() { // Setup: Create a result set and metadata we can reuse @@ -164,12 +161,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData }; rowEdits.Sort(); - // Then: Delete should be the last operation to execute + // Then: // (we don't care about the order of the other two) - Assert.IsType(rowEdits.Last()); + Assert.That(rowEdits.Last(), Is.InstanceOf(), "Delete should be the last operation to execute"); } - [Fact] + [Test] public async Task SortingUpdatesByRowIdTest() { // Setup: Create a result set and metadata we can reuse @@ -186,12 +183,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData rowEdits.Sort(); // Then: They should be in order by row ID ASCENDING - Assert.Equal(1, rowEdits[0].RowId); - Assert.Equal(2, rowEdits[1].RowId); - Assert.Equal(3, rowEdits[2].RowId); + Assert.AreEqual(1, rowEdits[0].RowId); + Assert.AreEqual(2, rowEdits[1].RowId); + Assert.AreEqual(3, rowEdits[2].RowId); } - [Fact] + [Test] public async Task SortingCreatesByRowIdTest() { // Setup: Create a result set and metadata we can reuse @@ -208,12 +205,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData rowEdits.Sort(); // Then: They should be in order by row ID ASCENDING - Assert.Equal(1, rowEdits[0].RowId); - Assert.Equal(2, rowEdits[1].RowId); - Assert.Equal(3, rowEdits[2].RowId); + Assert.AreEqual(1, rowEdits[0].RowId); + Assert.AreEqual(2, rowEdits[1].RowId); + Assert.AreEqual(3, rowEdits[2].RowId); } - [Fact] + [Test] public async Task SortingDeletesByRowIdTest() { // Setup: Create a result set and metadata we can reuse @@ -230,9 +227,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData rowEdits.Sort(); // Then: They should be in order by row ID DESCENDING - Assert.Equal(3, rowEdits[0].RowId); - Assert.Equal(2, rowEdits[1].RowId); - Assert.Equal(1, rowEdits[2].RowId); + Assert.AreEqual(3, rowEdits[0].RowId); + Assert.AreEqual(2, rowEdits[1].RowId); + Assert.AreEqual(1, rowEdits[2].RowId); } private static async Task GetResultSet(DbColumn[] columns, object[] row) @@ -262,18 +259,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... There should only be one component - Assert.Equal(1, wc.ClauseComponents.Count); + Assert.AreEqual(1, wc.ClauseComponents.Count); - // ... Parameterization should be empty - Assert.Empty(wc.Parameters); + Assert.That(wc.Parameters, Is.Empty, "Parameterization should be empty"); // ... The component should contain the name of the column and be null - Assert.Equal( + Assert.AreEqual( $"({AssociatedObjectMetadata.Columns.First().EscapedName} {nullValue})", wc.ClauseComponents[0]); // ... The complete clause should contain a single WHERE - Assert.Equal($"WHERE {wc.ClauseComponents[0]}", wc.CommandText); + Assert.AreEqual($"WHERE {wc.ClauseComponents[0]}", wc.CommandText); } public void ValidateWhereClauseMultipleKeys() @@ -284,14 +280,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... There should two components var keys = AssociatedObjectMetadata.KeyColumns.ToArray(); - Assert.Equal(keys.Length, wc.ClauseComponents.Count); + Assert.AreEqual(keys.Length, wc.ClauseComponents.Count); - // ... Parameterization should be empty - Assert.Empty(wc.Parameters); + Assert.That(wc.Parameters, Is.Empty, "Parameterization should be empty"); - // ... The components should contain the name of the column and the value - Regex r = new Regex(@"\([0-9a-z]+ = .+\)"); - Assert.All(wc.ClauseComponents, s => Assert.True(r.IsMatch(s))); + Assert.That(wc.ClauseComponents, Has.All.Match(@"\([0-9a-z]+ = .+\)"), "The components should contain the name of the column and the value"); // ... The complete clause should contain multiple cause components joined // with and diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowUpdateTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowUpdateTests.cs index 09a6a8fc..530f9242 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowUpdateTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/RowUpdateTests.cs @@ -15,13 +15,13 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { public class RowUpdateTests { - [Fact] + [Test] public async Task RowUpdateConstruction() { // Setup: Create the values to store @@ -33,18 +33,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData RowUpdate rc = new RowUpdate(rowId, rs, data.TableMetadata); // Then: The values I provided should be available - Assert.Equal(rowId, rc.RowId); - Assert.Equal(rs, rc.AssociatedResultSet); - Assert.Equal(data.TableMetadata, rc.AssociatedObjectMetadata); + Assert.AreEqual(rowId, rc.RowId); + Assert.AreEqual(rs, rc.AssociatedResultSet); + Assert.AreEqual(data.TableMetadata, rc.AssociatedObjectMetadata); } #region SetCell Tests - [Theory] - [InlineData(-1)] // Negative - [InlineData(3)] // At edge of acceptable values - [InlineData(100)] // Way too large value - public async Task SetCellOutOfRange(int columnId) + [Test] + public async Task SetCellOutOfRange([Values(-1,3,100)]int columnId) { // Setup: Generate a row create RowUpdate ru = await GetStandardRowUpdate(); @@ -53,7 +50,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => ru.SetCell(columnId, string.Empty)); } - [Fact] + [Test] public async Task SetCellImplicitRevertTest() { // Setup: Create a fake table to update @@ -74,7 +71,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.NotNull(eucr.Cell); // ... The new value we provided should be returned - Assert.Equal(rs.GetRow(0)[1].DisplayValue, eucr.Cell.DisplayValue); + Assert.AreEqual(rs.GetRow(0)[1].DisplayValue, eucr.Cell.DisplayValue); Assert.False(eucr.Cell.IsNull); // ... The cell should be clean @@ -90,11 +87,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... It should have 2 updates string updates = m.Groups[1].Value; string[] updateSplit = updates.Split(','); - Assert.Equal(2, updateSplit.Length); - Assert.All(updateSplit, s => Assert.Equal(2, s.Split('=').Length)); + Assert.AreEqual(2, updateSplit.Length); + Assert.That(updateSplit.Select(s => s.Split('=').Length), Has.All.EqualTo(2)); } - [Fact] + [Test] public async Task SetCellImplicitRowRevertTests() { // Setup: Create a fake column to update @@ -115,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.NotNull(eucr.Cell); // ... The old value should be returned - Assert.Equal(rs.GetRow(0)[1].DisplayValue, eucr.Cell.DisplayValue); + Assert.AreEqual(rs.GetRow(0)[1].DisplayValue, eucr.Cell.DisplayValue); Assert.False(eucr.Cell.IsNull); // ... The cell should be clean @@ -127,7 +124,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // TODO: Make sure that the script and command things will return null } - [Fact] + [Test] public void SetCellHasCorrections() { // Setup: @@ -161,8 +158,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.NotNull(eucr.Cell); // ... The value we used won't be returned - Assert.NotEmpty(eucr.Cell.DisplayValue); - Assert.NotEqual("1000", eucr.Cell.DisplayValue); + Assert.That(eucr.Cell.DisplayValue, Is.Not.Empty); + Assert.That(eucr.Cell.DisplayValue, Is.Not.EqualTo("1000")); Assert.False(eucr.Cell.IsNull); // ... The cell should be dirty @@ -172,11 +169,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(eucr.IsRowDirty); // ... There should be a cell update in the cell list - Assert.Contains(0, ru.cellUpdates.Keys); + Assert.That(ru.cellUpdates.Keys, Has.Member(0)); Assert.NotNull(ru.cellUpdates[0]); } - [Fact] + [Test] public async Task SetCell() { // Setup: Create a row update @@ -191,7 +188,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.NotNull(eucr.Cell); // ... The new value we provided should be returned - Assert.Equal("col1", eucr.Cell.DisplayValue); + Assert.AreEqual("col1", eucr.Cell.DisplayValue); Assert.False(eucr.Cell.IsNull); // ... The row is still dirty @@ -201,16 +198,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(eucr.Cell.IsDirty); // ... There should be a cell update in the cell list - Assert.Contains(0, ru.cellUpdates.Keys); + Assert.That(ru.cellUpdates.Keys, Has.Member(0)); Assert.NotNull(ru.cellUpdates[0]); } #endregion - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task GetScriptTest(bool isMemoryOptimized) + [Test] + public async Task GetScriptTest([Values]bool isMemoryOptimized) { // Setup: Create a fake table to update var data = new Common.TestDbColumnsWithTableMetadata(isMemoryOptimized, true, 0, 0); @@ -237,19 +232,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData string tbl = m.Groups[1].Value; string updates = m.Groups[2].Value; string[] updateSplit = updates.Split(','); - Assert.Equal(data.TableMetadata.EscapedMultipartName, tbl); - Assert.Equal(3, updateSplit.Length); - Assert.All(updateSplit, s => Assert.Equal(2, s.Split('=').Length)); + Assert.AreEqual(data.TableMetadata.EscapedMultipartName, tbl); + Assert.AreEqual(3, updateSplit.Length); + Assert.That(updateSplit.Select(s => s.Split('=').Length), Has.All.EqualTo(2)); } #region GetCommand Tests - [Theory] - [InlineData(true, true)] - [InlineData(true, false)] - [InlineData(false, true)] - [InlineData(false, false)] - public async Task GetCommand(bool includeIdentity, bool isMemoryOptimized) + [Test] + public async Task GetCommand([Values] bool includeIdentity, [Values] bool isMemoryOptimized) { // Setup: // ... Create a row update with cell updates @@ -284,7 +275,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Correct number of columns in declared table string[] declareCols = declareMatch.Groups[2].Value.Split(", "); - Assert.Equal(rs.Columns.Length, declareCols.Length); + Assert.AreEqual(rs.Columns.Length, declareCols.Length); // Check the update statement in the middle string regex = isMemoryOptimized @@ -295,21 +286,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(updateMatch.Success); // Table name matches - Assert.Equal(Common.TableName, updateMatch.Groups[1].Value); + Assert.AreEqual(Common.TableName, updateMatch.Groups[1].Value); // Output columns match string[] outCols = updateMatch.Groups[3].Value.Split(", "); - Assert.Equal(rs.Columns.Length, outCols.Length); - Assert.All(outCols, col => Assert.StartsWith("inserted.", col)); + Assert.AreEqual(rs.Columns.Length, outCols.Length); + Assert.That(outCols, Has.All.StartsWith("inserted.")); - // Set columns match string[] setCols = updateMatch.Groups[2].Value.Split(", "); - Assert.Equal(3, setCols.Length); - Assert.All(setCols, s => Assert.Matches(@".+ = @Value\d+_\d+", s)); - - // Output table name matches - Assert.StartsWith("Update", updateMatch.Groups[4].Value); - Assert.EndsWith("Output", updateMatch.Groups[4].Value); + Assert.AreEqual(3, setCols.Length); + Assert.That(setCols, Has.All.Match(@".+ = @Value\d+_\d+"), "Set columns match"); + + // Output table name matches + Assert.That(updateMatch.Groups[4].Value, Does.StartWith("Update")); + Assert.That(updateMatch.Groups[4].Value, Does.EndWith("Output")); // Check the select statement last Regex selectRegex = new Regex(@"^SELECT (.+) FROM @(.+)$"); @@ -318,19 +308,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Correct number of columns in select statement string[] selectCols = selectMatch.Groups[1].Value.Split(", "); - Assert.Equal(rs.Columns.Length, selectCols.Length); + Assert.AreEqual(rs.Columns.Length, selectCols.Length); // Select table name matches - Assert.StartsWith("Update", selectMatch.Groups[2].Value); - Assert.EndsWith("Output", selectMatch.Groups[2].Value); + Assert.That(selectMatch.Groups[2].Value, Does.StartWith("Update")); + Assert.That(selectMatch.Groups[2].Value, Does.EndWith("Output")); // ... There should be an appropriate number of parameters in it // (1 or 3 keys, 3 value parameters) int expectedKeys = includeIdentity ? 1 : 3; - Assert.Equal(expectedKeys + 3, cmd.Parameters.Count); + Assert.AreEqual(expectedKeys + 3, cmd.Parameters.Count); } - [Fact] + [Test] public async Task GetCommandNullConnection() { // Setup: Create a row update @@ -345,7 +335,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region GetEditRow Tests - [Fact] + [Test] public async Task GetEditRow() { // Setup: Create a row update with a cell set @@ -361,31 +351,31 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... The state should be dirty Assert.True(er.IsDirty); - Assert.Equal(EditRow.EditRowState.DirtyUpdate, er.State); + Assert.AreEqual(EditRow.EditRowState.DirtyUpdate, er.State); // ... The ID should be the same as the one provided - Assert.Equal(0, er.Id); + Assert.AreEqual(0, er.Id); // ... The row should match the cells that were given, except for the updated cell - Assert.Equal(cells.Length, er.Cells.Length); + Assert.AreEqual(cells.Length, er.Cells.Length); for (int i = 1; i < cells.Length; i++) { DbCellValue originalCell = cells[i]; DbCellValue outputCell = er.Cells[i]; - Assert.Equal(originalCell.DisplayValue, outputCell.DisplayValue); - Assert.Equal(originalCell.IsNull, outputCell.IsNull); + Assert.AreEqual(originalCell.DisplayValue, outputCell.DisplayValue); + Assert.AreEqual(originalCell.IsNull, outputCell.IsNull); // Note: No real need to check the RawObject property } // ... The updated cell should match what it was set to and be dirty EditCell newCell = er.Cells[0]; - Assert.Equal("foo", newCell.DisplayValue); + Assert.AreEqual("foo", newCell.DisplayValue); Assert.False(newCell.IsNull); Assert.True(newCell.IsDirty); } - [Fact] + [Test] public async Task GetEditNullRow() { // Setup: Create a row update @@ -400,10 +390,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region ApplyChanges Tests - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task ApplyChanges(bool includeIdentity) + [Test] + public async Task ApplyChanges([Values] bool includeIdentity) { // Setup: // ... Create a row update (no cell updates needed) @@ -420,11 +408,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... The result set should have the same number of rows as before - Assert.Equal(1, rs.RowCount); + Assert.AreEqual(1, rs.RowCount); Assert.True(oldBytesWritten < rs.totalBytesWritten); } - [Fact] + [Test] public async Task ApplyChangesNullReader() { // Setup: @@ -435,18 +423,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // If: I ask for the changes to be applied with a null db reader // Then: I should get an exception - await Assert.ThrowsAsync(() => ru.ApplyChanges(null)); + Assert.ThrowsAsync(() => ru.ApplyChanges(null)); } #endregion #region RevertCell Tests - [Theory] - [InlineData(-1)] // Negative - [InlineData(3)] // At edge of acceptable values - [InlineData(100)] // Way too large value - public async Task RevertCellOutOfRange(int columnId) + [Test] + public async Task RevertCellOutOfRange([Values(-1, 3, 100)] int columnId) { // Setup: // ... Create a row update (no cell updates needed) @@ -459,7 +444,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => ru.RevertCell(columnId)); } - [Fact] + [Test] public async Task RevertCellNotSet() { // Setup: @@ -478,16 +463,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... We should get the original value back // @TODO: Check for a default value when we support it Assert.NotNull(result.Cell); - Assert.Equal(rs.GetRow(0)[0].DisplayValue, result.Cell.DisplayValue); + Assert.AreEqual(rs.GetRow(0)[0].DisplayValue, result.Cell.DisplayValue); // ... The row should be clean Assert.False(result.IsRowDirty); - // ... The cell should no longer be set - Assert.DoesNotContain(0, ru.cellUpdates.Keys); + Assert.That(ru.cellUpdates.Keys, Has.None.Zero, "The cell should no longer be set"); } - [Fact] + [Test] public async Task RevertCellThatWasSet() { // Setup: @@ -508,16 +492,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... We should get the original value back // @TODO: Check for a default value when we support it Assert.NotNull(result.Cell); - Assert.Equal(rs.GetRow(0)[0].DisplayValue, result.Cell.DisplayValue); + Assert.AreEqual(rs.GetRow(0)[0].DisplayValue, result.Cell.DisplayValue); // ... The row should be dirty still Assert.True(result.IsRowDirty); - // ... The cell should no longer be set - Assert.DoesNotContain(0, ru.cellUpdates.Keys); + Assert.That(ru.cellUpdates.Keys, Has.None.Zero, "The cell should no longer be set"); } - [Fact] + [Test] public async Task RevertCellRevertsRow() { // Setup: @@ -537,13 +520,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... We should get the original value back // @TODO: Check for a default value when we support it Assert.NotNull(result.Cell); - Assert.Equal(rs.GetRow(0)[0].DisplayValue, result.Cell.DisplayValue); + Assert.AreEqual(rs.GetRow(0)[0].DisplayValue, result.Cell.DisplayValue); // ... The row should now be reverted Assert.False(result.IsRowDirty); - // ... The cell should no longer be set - Assert.DoesNotContain(0, ru.cellUpdates.Keys); + Assert.That(ru.cellUpdates.Keys, Has.None.Zero, "The cell should no longer be set"); } #endregion diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/ServiceIntegrationTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/ServiceIntegrationTests.cs index f3472671..79423a58 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/ServiceIntegrationTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/ServiceIntegrationTests.cs @@ -7,6 +7,7 @@ using System; using System.Data.Common; using System.Linq; using System.Threading.Tasks; +using Microsoft.SqlServer.Dac.Model; using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.EditData; using Microsoft.SqlTools.ServiceLayer.EditData.Contracts; @@ -17,7 +18,7 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { @@ -25,12 +26,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { #region EditSession Operation Helper Tests - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" \t\n\r")] - [InlineData("Does not exist")] - public async Task NullOrMissingSessionId(string sessionId) + [Test] + public async Task NullOrMissingSessionId([Values(null, "", " \t\n\r", "Does not exist")] string sessionId) { // Setup: // ... Create a edit data service @@ -48,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData efv.Validate(); } - [Fact] + [Test] public async Task OperationThrows() { // Setup: @@ -74,12 +71,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region Dispose Tests - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" \t\n\r")] - [InlineData("Does not exist")] - public async Task DisposeNullOrMissingSessionId(string sessionId) + [Test] + public async Task DisposeNullOrMissingSessionId([Values(null, "", " \t\n\r", "Does not exist")] string sessionId) { // Setup: Create a edit data service var eds = new EditDataService(null, null, null); @@ -93,7 +86,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData efv.Validate(); } - [Fact] + [Test] public async Task DisposeSuccess() { // Setup: Create an edit data service with a session @@ -110,13 +103,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... It should have completed successfully efv.Validate(); - // ... And the session should have been removed from the active session list - Assert.Empty(eds.ActiveSessions); + Assert.That(eds.ActiveSessions, Is.Empty, "And the session should have been removed from the active session list"); } #endregion - [Fact] + [Test] public async Task DeleteSuccess() { // Setup: Create an edit data service with a session @@ -138,7 +130,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(s.EditCache.Any(e => e.Value is RowDelete)); } - [Fact] + [Test] public async Task CreateSucceeds() { // Setup: Create an edit data service with a session @@ -160,7 +152,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(s.EditCache.Any(e => e.Value is RowCreate)); } - [Fact] + [Test] public async Task RevertCellSucceeds() { // Setup: @@ -193,10 +185,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... The edit cache should be empty again EditSession s = eds.ActiveSessions[Constants.OwnerUri]; - Assert.Empty(s.EditCache); + Assert.That(s.EditCache, Is.Empty); } - [Fact] + [Test] public async Task RevertRowSucceeds() { // Setup: Create an edit data service with a session that has an pending edit @@ -217,10 +209,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... The edit cache should be empty again EditSession s = eds.ActiveSessions[Constants.OwnerUri]; - Assert.Empty(s.EditCache); + Assert.That(s.EditCache, Is.Empty); } - [Fact] + [Test] public async Task UpdateSuccess() { // Setup: Create an edit data service with a session @@ -254,7 +246,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData edit.Verify(e => e.SetCell(It.IsAny(), It.IsAny()), Times.Once); } - [Fact] + [Test] public async Task GetRowsSuccess() { // Setup: Create an edit data service with a session @@ -268,8 +260,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData .AddResultValidation(esr => { Assert.NotNull(esr); - Assert.NotEmpty(esr.Subset); - Assert.NotEqual(0, esr.RowCount); + Assert.That(esr.Subset, Is.Not.Empty); + Assert.That(esr.RowCount, Is.Not.EqualTo(0)); }) .Complete(); await eds.HandleSubsetRequest(new EditSubsetParams @@ -285,11 +277,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } #region Initialize Tests - [Theory] - [InlineData(null, "table", "table")] // Null owner URI - [InlineData(Common.OwnerUri, null, "table")] // Null object name - [InlineData(Common.OwnerUri, "table", null)] // Null object type - public async Task InitializeNullParams(string ownerUri, string objName, string objType) + [Test] + [Sequential] + public async Task InitializeNullParams([Values(null, Common.OwnerUri, Common.OwnerUri)] string ownerUri, + [Values("table", null, "table")] string objName, + [Values("table", "table", null)] string objType) { // Setup: Create an edit data service without a session var eds = new EditDataService(null, null, null); @@ -314,10 +306,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData efv.Validate(); // ... There should not be a session - Assert.Empty(eds.ActiveSessions); + Assert.That(eds.ActiveSessions, Is.Empty); } - [Fact] + [Test] public async Task InitializeSessionExists() { // Setup: Create an edit data service with a session already defined @@ -343,12 +335,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData efv.Validate(); // ... The original session should still be there - Assert.Equal(1, eds.ActiveSessions.Count); - Assert.Equal(session, eds.ActiveSessions[Constants.OwnerUri]); + Assert.AreEqual(1, eds.ActiveSessions.Count); + Assert.AreEqual(session, eds.ActiveSessions[Constants.OwnerUri]); } // Disable flaky test for investigation (karlb - 3/13/2018) - //[Fact] + //[Test] public async Task InitializeSessionSuccess() { // Setup: @@ -391,7 +383,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData .AddEventValidation(EditSessionReadyEvent.Type, esrp => { Assert.NotNull(esrp); - Assert.Equal(Constants.OwnerUri, esrp.OwnerUri); + Assert.AreEqual(Constants.OwnerUri, esrp.OwnerUri); Assert.True(esrp.Success); Assert.Null(esrp.Message); }) @@ -404,17 +396,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData efv.Validate(); // ... The session should have been created - Assert.Equal(1, eds.ActiveSessions.Count); + Assert.AreEqual(1, eds.ActiveSessions.Count); Assert.True(eds.ActiveSessions.Keys.Contains(Constants.OwnerUri)); - } - + } + #endregion - - [Theory] - [InlineData("table", "myschema", new [] { "myschema", "table" })] // Use schema - [InlineData("table", null, new [] { "table" })] // skip schema - [InlineData("schema.table", "myschema", new [] { "myschema", "schema.table"})] // Use schema - [InlineData("schema.table", null, new [] { "schema", "table"})] // Split object name into schema + private static readonly object[] schemaNameParameters = + { + new object[] {"table", "myschema", new[] { "myschema", "table" } }, // Use schema + new object[] {"table", null, new[] { "table" } }, // skip schema + new object[] {"schema.table", "myschema", new[] { "myschema", "schema.table" } }, // Use schema + new object[] {"schema.table", null, new[] { "schema", "table" } }, // Split object name into schema + }; + + [Test, TestCaseSource(nameof(schemaNameParameters))] public void ShouldUseSchemaNameIfDefined(string objName, string schemaName, string[] expectedNameParts) { // Setup: Create an edit data service without a session @@ -434,7 +429,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData string[] nameParts = EditSession.GetEditTargetName(initParams); // Then: - Assert.Equal(expectedNameParts, nameParts); + Assert.AreEqual(expectedNameParts, nameParts); } private static async Task GetDefaultSession() diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/SessionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/SessionTests.cs index d4a84a7a..be56714e 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/SessionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/EditData/SessionTests.cs @@ -20,7 +20,7 @@ using Microsoft.SqlTools.ServiceLayer.SqlContext; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { @@ -28,7 +28,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData { #region Construction Tests - [Fact] + [Test] public void SessionConstructionNullMetadataFactory() { // If: I create a session object with a null metadata factory @@ -36,7 +36,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => new EditSession(null)); } - [Fact] + [Test] public void SessionConstructionValid() { // If: I create a session object with a proper arguments @@ -53,14 +53,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Null(s.CommitTask); // ... The next row ID should be the default long - Assert.Equal(default(long), s.NextRowId); + Assert.AreEqual(default(long), s.NextRowId); } #endregion #region Validate Tests - [Fact] + [Test] public void SessionValidateUnfinishedQuery() { // If: I create a session object with a query that hasn't finished execution @@ -70,7 +70,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => EditSession.ValidateQueryForSession(q)); } - [Fact] + [Test] public void SessionValidateIncorrectResultSet() { // Setup: Create a query that yields >1 result sets @@ -94,7 +94,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => EditSession.ValidateQueryForSession(query)); } - [Fact] + [Test] public void SessionValidateValidResultSet() { // If: I validate a query for a session with a valid query @@ -109,7 +109,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region Create Row Tests - [Fact] + [Test] public void CreateRowNotInitialized() { // Setup: @@ -122,7 +122,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.CreateRow()); } - [Fact] + [Test] public async Task CreateRowAddFailure() { // NOTE: This scenario should theoretically never occur, but is tested for completeness @@ -143,13 +143,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.CreateRow()); // ... The mock edit should still exist - Assert.Equal(mockEdit, s.EditCache[rs.RowCount]); + Assert.AreEqual(mockEdit, s.EditCache[rs.RowCount]); // ... The next row ID should not have changes - Assert.Equal(rs.RowCount, s.NextRowId); + Assert.AreEqual(rs.RowCount, s.NextRowId); } - [Fact] + [Test] public async Task CreateRowSuccess() { // Setup: Create a session with a proper query and metadata @@ -163,20 +163,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... The new ID should be equal to the row count - Assert.Equal(rs.RowCount, result.NewRowId); + Assert.AreEqual(rs.RowCount, result.NewRowId); // ... The next row ID should have been incremented - Assert.Equal(rs.RowCount + 1, s.NextRowId); + Assert.AreEqual(rs.RowCount + 1, s.NextRowId); // ... There should be a new row create object in the cache - Assert.Contains(result.NewRowId, s.EditCache.Keys); - Assert.IsType(s.EditCache[result.NewRowId]); + Assert.That(s.EditCache.Keys, Has.Member(result.NewRowId)); + Assert.That(s.EditCache[result.NewRowId], Is.InstanceOf()); // ... The default values should be returned (we will test this in depth below) - Assert.NotEmpty(result.DefaultValues); + Assert.That(result.DefaultValues, Is.Not.Empty); } - [Fact] + [Test] public async Task CreateRowDefaultTest() { // Setup: @@ -229,18 +229,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(result.NewRowId > 0); // ... There should be 3 default values (3 columns) - Assert.NotEmpty(result.DefaultValues); - Assert.Equal(3, result.DefaultValues.Length); + Assert.That(result.DefaultValues, Is.Not.Empty); + Assert.AreEqual(3, result.DefaultValues.Length); // ... There should be specific values for each kind of default Assert.Null(result.DefaultValues[0]); - Assert.Equal("default", result.DefaultValues[1]); + Assert.AreEqual("default", result.DefaultValues[1]); } #endregion - [Theory] - [MemberData(nameof(RowIdOutOfRangeData))] + [Test] + [TestCaseSource(nameof(RowIdOutOfRangeData))] public async Task RowIdOutOfRange(long rowId, Action testAction) { // Setup: Create a session with a proper query and metadata @@ -285,7 +285,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region Initialize Tests - [Fact] + [Test] public void InitializeAlreadyInitialized() { // Setup: @@ -298,7 +298,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.Initialize(null, null, null, null, null)); } - [Fact] + [Test] public void InitializeAlreadyInitializing() { // Setup: @@ -311,8 +311,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.Initialize(null, null, null, null, null)); } - [Theory] - [MemberData(nameof(InitializeNullParamsData))] + [Test] + [TestCaseSource(nameof(InitializeNullParamsData))] public void InitializeNullParams(EditInitializeParams initParams, EditSession.Connector c, EditSession.QueryRunner qr, Func sh, Func fh) { @@ -321,9 +321,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Mock emf = new Mock(); EditSession s = new EditSession(emf.Object); - // If: I initialize it with a missing parameter - // Then: It should throw an exception - Assert.ThrowsAny(() => s.Initialize(initParams, c, qr, sh, fh)); + Assert.That(() => s.Initialize(initParams, c, qr, sh, fh), Throws.InstanceOf(), "I initialize it with a missing parameter. It should throw an exception"); } public static IEnumerable InitializeNullParamsData @@ -376,7 +374,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData } } - [Fact] + [Test] public async Task InitializeMetadataFails() { // Setup: @@ -407,7 +405,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData successHandler.Verify(f => f(), Times.Never); } - [Fact] + [Test] public async Task InitializeQueryFailException() { // Setup: @@ -444,10 +442,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData successHandler.Verify(f => f(), Times.Never); } - [Theory] - [InlineData(null)] - [InlineData("It fail.")] - public async Task InitializeQueryFailReturnNull(string message) + [Test] + public async Task InitializeQueryFailReturnNull([Values(null, "It fail.")] string message) { // Setup: // ... Create a metadata factory that will return some generic column information @@ -484,7 +480,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData successHandler.Verify(f => f(), Times.Never); } - [Fact] + [Test] public async Task InitializeSuccess() { // Setup: @@ -521,16 +517,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // ... The session should have been initialized Assert.True(s.IsInitialized); - Assert.Equal(rs.RowCount, s.NextRowId); + Assert.AreEqual(rs.RowCount, s.NextRowId); Assert.NotNull(s.EditCache); - Assert.Empty(s.EditCache); + Assert.That(s.EditCache, Is.Empty); } #endregion #region Delete Row Tests - [Fact] + [Test] public void DeleteRowNotInitialized() { // Setup: @@ -543,7 +539,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.DeleteRow(0)); } - [Fact] + [Test] public async Task DeleteRowAddFailure() { // Setup: @@ -560,10 +556,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.DeleteRow(0)); // ... The mock edit should still exist - Assert.Equal(mockEdit, s.EditCache[0]); + Assert.AreEqual(mockEdit, s.EditCache[0]); } - [Fact] + [Test] public async Task DeleteRowSuccess() { // Setup: Create a session with a proper query and metadata @@ -572,16 +568,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // If: I add a row to the session s.DeleteRow(0); - // Then: There should be a new row delete object in the cache - Assert.Contains(0, s.EditCache.Keys); - Assert.IsType(s.EditCache[0]); + Assert.That(s.EditCache.Keys, Has.Member(0)); + Assert.That(s.EditCache[0], Is.InstanceOf(), "There should be a new row delete object in the cache"); } #endregion #region Revert Row Tests - [Fact] + [Test] public void RevertRowNotInitialized() { // Setup: @@ -594,7 +589,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.RevertRow(0)); } - [Fact] + [Test] public async Task RevertRowSuccess() { // Setup: @@ -608,16 +603,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // If: I revert the row that has a pending update s.RevertRow(0); - // Then: - // ... The edit cache should not contain a pending edit for the row - Assert.DoesNotContain(0, s.EditCache.Keys); + Assert.That(s.EditCache.Keys, Has.No.Zero, "The edit cache should not contain a pending edit for the row"); } #endregion #region Revert Cell Tests - [Fact] + [Test] public void RevertCellNotInitialized() { // Setup: @@ -630,7 +623,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.RevertCell(0, 0)); } - [Fact] + [Test] public async Task RevertCellRowRevert() { // Setup: @@ -651,14 +644,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData mockEdit.Verify(e => e.RevertCell(0), Times.Once); // ... The mock update should no longer be in the edit cache - Assert.Empty(s.EditCache); + Assert.That(s.EditCache, Is.Empty); } #endregion #region Update Cell Tests - [Fact] + [Test] public void UpdateCellNotInitialized() { // Setup: @@ -671,7 +664,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.UpdateCell(0, 0, "")); } - [Fact] + [Test] public async Task UpdateCellExisting() { // Setup: @@ -690,10 +683,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... The mock update should still be in the cache // ... And it should have had set cell called on it - Assert.Contains(mockEdit.Object, s.EditCache.Values); + Assert.That(s.EditCache.Values, Has.Member(mockEdit.Object)); } - [Fact] + [Test] public async Task UpdateCellNew() { // Setup: @@ -704,12 +697,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData s.UpdateCell(0, 0, ""); // Then: - // ... A new update row edit should have been added to the cache - Assert.Contains(0, s.EditCache.Keys); - Assert.IsType(s.EditCache[0]); + Assert.Multiple(() => + { + Assert.That(s.EditCache.Keys, Has.Member(0)); + Assert.That(s.EditCache[0], Is.InstanceOf(), "A new update row edit should have been added to the cache"); + }); } - [Fact] + [Test] public async Task UpdateCellRowRevert() { // Setup: @@ -730,7 +725,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData mockEdit.Verify(e => e.SetCell(0, null), Times.Once); // ... The mock update should no longer be in the edit cache - Assert.Empty(s.EditCache); + Assert.That(s.EditCache, Is.Empty); } @@ -739,7 +734,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region SubSet Tests - [Fact] + [Test] public async Task SubsetNotInitialized() { // Setup: @@ -749,10 +744,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // If: I ask to update a cell without initializing // Then: I should get an exception - await Assert.ThrowsAsync(() => s.GetRows(0, 100)); + Assert.ThrowsAsync(() => s.GetRows(0, 100)); } - [Fact] + [Test] public async Task GetRowsNoEdits() { // Setup: Create a session with a proper query and metadata @@ -766,7 +761,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... I should get back 3 rows - Assert.Equal(3, rows.Length); + Assert.AreEqual(3, rows.Length); // ... Each row should... for (int i = 0; i < rows.Length; i++) @@ -774,25 +769,25 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData EditRow er = rows[i]; // ... Have properly set IDs - Assert.Equal(i + 1, er.Id); + Assert.AreEqual(i + 1, er.Id); // ... Have cells equal to the cells in the result set DbCellValue[] cachedRow = rs.GetRow(i + 1).ToArray(); - Assert.Equal(cachedRow.Length, er.Cells.Length); + Assert.AreEqual(cachedRow.Length, er.Cells.Length); for (int j = 0; j < cachedRow.Length; j++) { - Assert.Equal(cachedRow[j].DisplayValue, er.Cells[j].DisplayValue); - Assert.Equal(cachedRow[j].IsNull, er.Cells[j].IsNull); + Assert.AreEqual(cachedRow[j].DisplayValue, er.Cells[j].DisplayValue); + Assert.AreEqual(cachedRow[j].IsNull, er.Cells[j].IsNull); Assert.False(er.Cells[j].IsDirty); } // ... Be clean, since we didn't apply any updates - Assert.Equal(EditRow.EditRowState.Clean, er.State); + Assert.AreEqual(EditRow.EditRowState.Clean, er.State); Assert.False(er.IsDirty); } } - [Fact] + [Test] public async Task GetRowsPendingUpdate() { // Setup: @@ -807,22 +802,22 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... I should get back 3 rows - Assert.Equal(3, rows.Length); + Assert.AreEqual(3, rows.Length); // ... The first row should reflect that there is an update pending // (More in depth testing is done in the RowUpdate class tests) var updatedRow = rows[0]; - Assert.Equal(EditRow.EditRowState.DirtyUpdate, updatedRow.State); - Assert.Equal("foo", updatedRow.Cells[0].DisplayValue); + Assert.AreEqual(EditRow.EditRowState.DirtyUpdate, updatedRow.State); + Assert.AreEqual("foo", updatedRow.Cells[0].DisplayValue); // ... The other rows should be clean for (int i = 1; i < rows.Length; i++) { - Assert.Equal(EditRow.EditRowState.Clean, rows[i].State); + Assert.AreEqual(EditRow.EditRowState.Clean, rows[i].State); } } - [Fact] + [Test] public async Task GetRowsPendingDeletion() { // Setup: @@ -837,22 +832,22 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... I should get back 3 rows - Assert.Equal(3, rows.Length); + Assert.AreEqual(3, rows.Length); // ... The first row should reflect that there is an update pending // (More in depth testing is done in the RowUpdate class tests) var updatedRow = rows[0]; - Assert.Equal(EditRow.EditRowState.DirtyDelete, updatedRow.State); - Assert.NotEmpty(updatedRow.Cells[0].DisplayValue); + Assert.AreEqual(EditRow.EditRowState.DirtyDelete, updatedRow.State); + Assert.That(updatedRow.Cells[0].DisplayValue, Is.Not.Empty); // ... The other rows should be clean for (int i = 1; i < rows.Length; i++) { - Assert.Equal(EditRow.EditRowState.Clean, rows[i].State); + Assert.AreEqual(EditRow.EditRowState.Clean, rows[i].State); } } - [Fact] + [Test] public async Task GetRowsPendingInsertion() { // Setup: @@ -867,20 +862,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... I should get back 6 rows - Assert.Equal(6, rows.Length); + Assert.AreEqual(6, rows.Length); // ... The last row should reflect that there's a new row var updatedRow = rows[5]; - Assert.Equal(EditRow.EditRowState.DirtyInsert, updatedRow.State); + Assert.AreEqual(EditRow.EditRowState.DirtyInsert, updatedRow.State); // ... The other rows should be clean for (int i = 0; i < rows.Length - 1; i++) { - Assert.Equal(EditRow.EditRowState.Clean, rows[i].State); + Assert.AreEqual(EditRow.EditRowState.Clean, rows[i].State); } } - [Fact] + [Test] public async Task GetRowsAllNew() { // Setup: @@ -897,17 +892,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... I should get back 3 rows back - Assert.Equal(3, rows.Length); + Assert.AreEqual(3, rows.Length); - // ... All the rows should be new - Assert.All(rows, r => Assert.Equal(EditRow.EditRowState.DirtyInsert, r.State)); + Assert.That(rows.Select(r => r.State), Has.All.EqualTo(EditRow.EditRowState.DirtyInsert), "All the rows should be new"); } #endregion #region Script Edits Tests - [Fact] + [Test] public void ScriptEditsNotInitialized() { // Setup: @@ -920,11 +914,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.ScriptEdits(string.Empty)); } - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" \t\r\n")] - public async Task ScriptNullOrEmptyOutput(string outputPath) + [Test] + public async Task ScriptNullOrEmptyOutput([Values(null, "", " \t\r\n")] string outputPath) { // Setup: Create a session with a proper query and metadata EditSession s = await GetBasicSession(); @@ -934,7 +925,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.ScriptEdits(outputPath)); } - [Fact] + [Test] public async Task ScriptProvidedOutputPath() { // Setup: @@ -954,10 +945,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData // Then: // ... The output path used should be the same as the one we provided - Assert.Equal(file.FilePath, outputPath); + Assert.AreEqual(file.FilePath, outputPath); // ... The written file should have two lines, one for each edit - Assert.Equal(2, File.ReadAllLines(outputPath).Length); + Assert.AreEqual(2, File.ReadAllLines(outputPath).Length); } } @@ -965,7 +956,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData #region Commit Tests - [Fact] + [Test] public void CommitEditsNotInitialized() { // Setup: @@ -978,7 +969,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.CommitEdits(null, null, null)); } - [Fact] + [Test] public async Task CommitNullConnection() { // Setup: Create a basic session @@ -990,7 +981,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData () => s.CommitEdits(null, () => Task.CompletedTask, e => Task.CompletedTask)); } - [Fact] + [Test] public async Task CommitNullSuccessHandler() { // Setup: @@ -1005,7 +996,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.CommitEdits(conn, null, e => Task.CompletedTask)); } - [Fact] + [Test] public async Task CommitNullFailureHandler() { // Setup: @@ -1020,7 +1011,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => s.CommitEdits(conn, () => Task.CompletedTask, null)); } - [Fact] + [Test] public async Task CommitInProgress() { // Setup: @@ -1038,7 +1029,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData () => s.CommitEdits(conn, () => Task.CompletedTask, e => Task.CompletedTask)); } - [Fact] + [Test] public async Task CommitSuccess() { // Setup: @@ -1079,10 +1070,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData edit.Verify(e => e.ApplyChanges(It.IsAny()), Times.Once); // ... The edit cache should be empty - Assert.Empty(s.EditCache); + Assert.That(s.EditCache, Is.Empty); } - [Fact] + [Test] public async Task CommitFailure() { // Setup: @@ -1121,14 +1112,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData edit.Verify(e => e.GetCommand(conn), Times.Once); // ... The edit cache should not be empty - Assert.NotEmpty(s.EditCache); + Assert.That(s.EditCache, Is.Not.Empty); } #endregion #region Construct Initialize Query Tests - [Fact] + [Test] public void ConstructQueryWithoutLimit() { // Setup: Create a metadata provider for some basic columns @@ -1148,16 +1139,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(match.Success); // ... There should be columns in it - Assert.Equal(data.DbColumns.Length, match.Groups[1].Value.Split(',').Length); + Assert.AreEqual(data.DbColumns.Length, match.Groups[1].Value.Split(',').Length); // ... The table name should be in it - Assert.Equal(data.TableMetadata.EscapedMultipartName, match.Groups[2].Value); + Assert.AreEqual(data.TableMetadata.EscapedMultipartName, match.Groups[2].Value); - // ... It should NOT have a TOP clause in it - Assert.DoesNotContain("TOP", query); + Assert.That(query, Does.Not.Contain("TOP"), "It should NOT have a TOP clause in it"); } - [Fact] + [Test] public void ConstructQueryNegativeLimit() { // Setup: Create a metadata provider for some basic columns @@ -1172,11 +1162,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.Throws(() => EditSession.ConstructInitializeQuery(data.TableMetadata, eif)); } - [Theory] - [InlineData(0)] // Yes, zero is valid - [InlineData(10)] - [InlineData(1000)] - public void ConstructQueryWithLimit(int limit) + [Test] + public void ConstructQueryWithLimit([Values(0,10,1000)]int limit) { // Setup: Create a metadata provider for some basic columns var data = new Common.TestDbColumnsWithTableMetadata(false, false, 0, 0); @@ -1195,15 +1182,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData Assert.True(match.Success); // ... There should be columns in it - Assert.Equal(data.DbColumns.Length, match.Groups[2].Value.Split(',').Length); + Assert.AreEqual(data.DbColumns.Length, match.Groups[2].Value.Split(',').Length); // ... The table name should be in it - Assert.Equal(data.TableMetadata.EscapedMultipartName, match.Groups[3].Value); + Assert.AreEqual(data.TableMetadata.EscapedMultipartName, match.Groups[3].Value); // ... The top count should be equal to what we provided int limitFromQuery; Assert.True(int.TryParse(match.Groups[1].Value, out limitFromQuery)); - Assert.Equal(limit, limitFromQuery); + Assert.AreEqual(limit, limitFromQuery); } #endregion diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Extensibility/ExtensionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Extensibility/ExtensionTests.cs index 203ebcef..4bfbcfec 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Extensibility/ExtensionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Extensibility/ExtensionTests.cs @@ -9,51 +9,51 @@ using System.Linq; using System.Reflection; using Microsoft.SqlTools.Extensibility; using Microsoft.SqlTools.ServiceLayer.Formatter; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility { public class ExtensionTests { - [Fact] + [Test] public void CreateAssemblyStoreShouldFindTypesInAssembly() { // Given a store for MyExportType ExtensionStore store = ExtensionStore.CreateAssemblyStore(GetType().GetTypeInfo().Assembly); // Then should get any export for this type and subtypes - Assert.Equal(2, store.GetExports().Count()); + Assert.AreEqual(2, store.GetExports().Count()); // But for a different type, expect throw as the store only contains MyExportType Assert.Throws(() => store.GetExports().Count()); } - [Fact] + [Test] public void CreateDefaultLoaderShouldFindTypesOnlyInMainAssembly() { // Given a store created using CreateDefaultLoader // Then not should find exports from a different assembly ExtensionStore store = ExtensionStore.CreateDefaultLoader(); - Assert.Equal(0, store.GetExports().Count()); + Assert.AreEqual(0, store.GetExports().Count()); // And should not find exports that are defined in the ServiceLayer assembly store = ExtensionStore.CreateDefaultLoader(); - Assert.Empty(store.GetExports()); + Assert.That(store.GetExports(), Is.Empty); } - [Fact] + [Test] public void CreateDefaultServiceProviderShouldFindTypesInAllKnownAssemblies() { // Given a default ExtensionServiceProvider // Then we should not find exports from a test assembly ExtensionServiceProvider serviceProvider = ExtensionServiceProvider.CreateDefaultServiceProvider(); - Assert.Empty(serviceProvider.GetServices()); + Assert.That(serviceProvider.GetServices(), Is.Empty); // But should find exports that are defined in the main assembly - Assert.NotEmpty(serviceProvider.GetServices()); + Assert.That(serviceProvider.GetServices(), Is.Not.Empty); } - // [Fact] + // [Test] public void CreateStoreForCurrentDirectoryShouldFindExportsInDirectory() { // Given stores created for types in different assemblies @@ -62,8 +62,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility // When I query exports // Then exports for all assemblies should be found - Assert.Equal(2, myStore.GetExports().Count()); - Assert.NotEmpty(querierStore.GetExports()); + Assert.AreEqual(2, myStore.GetExports().Count()); + Assert.That(querierStore.GetExports(), Is.Not.Empty); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Extensibility/ServiceProviderTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Extensibility/ServiceProviderTests.cs index f55aff15..038d04c0 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Extensibility/ServiceProviderTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Extensibility/ServiceProviderTests.cs @@ -6,19 +6,21 @@ using System; using System.Linq; using Microsoft.SqlTools.Extensibility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility { public class ServiceProviderTests { private RegisteredServiceProvider provider; - public ServiceProviderTests() + + [SetUp] + public void InitServiceProviderTests() { provider = new RegisteredServiceProvider(); } - [Fact] + [Test] public void GetServiceShouldReturnNullIfNoServicesRegistered() { // Given no service registered @@ -29,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility } - [Fact] + [Test] public void GetSingleServiceThrowsMultipleServicesRegistered() { // Given 2 services registered @@ -39,7 +41,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility Assert.Throws(() => provider.GetService()); } - [Fact] + [Test] public void GetServicesShouldReturnEmptyIfNoServicesRegistered() { // Given no service regisstered @@ -47,36 +49,36 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility var services = provider.GetServices(); // Then I expect empty enumerable to be returned Assert.NotNull(services); - Assert.Equal(0, services.Count()); + Assert.AreEqual(0, services.Count()); } - [Fact] + [Test] public void GetServiceShouldReturnRegisteredService() { MyProviderService service = new MyProviderService(); provider.RegisterSingleService(service); var returnedService = provider.GetService(); - Assert.Equal(service, returnedService); + Assert.AreEqual(service, returnedService); } - [Fact] + [Test] public void GetServicesShouldReturnRegisteredServiceWhenMultipleServicesRegistered() { MyProviderService service = new MyProviderService(); provider.RegisterSingleService(service); var returnedServices = provider.GetServices(); - Assert.Equal(service, returnedServices.Single()); + Assert.AreEqual(service, returnedServices.Single()); } - [Fact] + [Test] public void RegisterServiceProviderShouldThrowIfServiceIsIncompatible() { MyProviderService service = new MyProviderService(); Assert.Throws(() => provider.RegisterSingleService(typeof(OtherService), service)); } - [Fact] + [Test] public void RegisterServiceProviderShouldThrowIfServiceAlreadyRegistered() { MyProviderService service = new MyProviderService(); @@ -85,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility Assert.Throws(() => provider.RegisterSingleService(service)); } - [Fact] + [Test] public void RegisterShouldThrowIfServiceAlreadyRegistered() { MyProviderService service = new MyProviderService(); @@ -94,7 +96,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility Assert.Throws(() => provider.Register(() => service.SingleItemAsEnumerable())); } - [Fact] + [Test] public void RegisterShouldThrowIfServicesAlreadyRegistered() { provider.Register(() => new [] { new MyProviderService(), new MyProviderService() }); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/FileBrowser/FileBrowserTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/FileBrowser/FileBrowserTests.cs index 5e1fd8c9..fdefa686 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/FileBrowser/FileBrowserTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/FileBrowser/FileBrowserTests.cs @@ -6,7 +6,7 @@ using System; using Microsoft.SqlTools.ServiceLayer.FileBrowser; using Microsoft.SqlTools.ServiceLayer.FileBrowser.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.FileBrowser { @@ -15,7 +15,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.FileBrowser /// public class FileBrowserTests { - [Fact] + [Test] public void CreateFileBrowserOperationTest() { FileBrowserOperation operation = new FileBrowserOperation(null, "", null); @@ -25,7 +25,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.FileBrowser Assert.True(operation.FileFilters.Length == 1); } - [Fact] + [Test] public void FilterFilesTest() { FileBrowserOperation operation = new FileBrowserOperation(null, "", null); @@ -44,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.FileBrowser } } - [Fact] + [Test] public void ExpandNodeShouldThrowExceptionForInvalidPath() { FileBrowserOperation operation = new FileBrowserOperation(null, "", null); @@ -64,7 +64,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.FileBrowser Assert.Null(operation.FileTree.SelectedNode); } - [Fact] + [Test] public void CreateFileTreeTest() { FileTree tree = new FileTree(); @@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.FileBrowser Assert.Null(tree.SelectedNode); } - [Fact] + [Test] public void AddFileTreeNodeChildTest() { FileTreeNode node1 = new FileTreeNode(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/BinaryQueryExpressionFormatterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/BinaryQueryExpressionFormatterTests.cs index 51b31ee9..306756c4 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/BinaryQueryExpressionFormatterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/BinaryQueryExpressionFormatterTests.cs @@ -4,13 +4,19 @@ // using Microsoft.SqlTools.ServiceLayer.Formatter; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class BinaryQueryExpressionFormatterTests : FormatterUnitTestsBase { - [Fact] + [SetUp] + public void Init() + { + InitFormatterUnitTestsBase(); + } + + [Test] public void BQE_IndentOperands() { FormatOptions options = new FormatOptions(); @@ -19,7 +25,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("BQE_IndentOperands.sql"), options, true); } - [Fact] + [Test] public void BQE_KeywordCasing_UpperCase() { FormatOptions options = new FormatOptions(); @@ -28,7 +34,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("BQE_KeywordCasing_UpperCase.sql"), options, true); } - [Fact] + [Test] public void BQE_KeywordCasing_LowerCase() { FormatOptions options = new FormatOptions(); @@ -37,7 +43,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("BQE_KeywordCasing_LowerCase.sql"), options, true); } - [Fact] + [Test] public void BQE_KeywordCasing_NoFormat() { FormatOptions options = new FormatOptions(); @@ -46,7 +52,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("BQE_KeywordCasing_NoFormat.sql"), options, true); } - [Fact] + [Test] public void BQE_OperatorsOnNewLine() { FormatOptions options = new FormatOptions(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CommonTableExpressionFormatterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CommonTableExpressionFormatterTests.cs index 6f5cdaac..deca953e 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CommonTableExpressionFormatterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CommonTableExpressionFormatterTests.cs @@ -5,35 +5,41 @@ using Microsoft.SqlTools.ServiceLayer.Formatter; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class CommonTableExpressionFormatterTests : FormatterUnitTestsBase { - [Fact] + [SetUp] + public void Init() + { + InitFormatterUnitTestsBase(); + } + + [Test] public void CTE() { LoadAndFormatAndCompare("CTE", GetInputFile("CTE.sql"), GetBaselineFile("CTE.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CTE_OneColumn() { LoadAndFormatAndCompare("CTE_OneColumn", GetInputFile("CTE_OneColumn.sql"), GetBaselineFile("CTE_OneColumn.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CTE_MultipleExpressions() { LoadAndFormatAndCompare("CTE_MultipleExpressions", GetInputFile("CTE_MultipleExpressions.sql"), GetBaselineFile("CTE_MultipleExpressions.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CTE_CommasBeforeDefinition() { FormatOptions options = new FormatOptions(); @@ -44,7 +50,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("CTE_CommasBeforeDefinition.sql"), options, false); } - [Fact] + [Test] public void CTE_EachReferenceOnNewLine() { FormatOptions options = new FormatOptions(); @@ -54,7 +60,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("CTE_EachReferenceOnNewLine.sql"), options, true); } - [Fact] + [Test] public void CTE_EachReferenceOnNewLine_CommasBeforeDefinition() { FormatOptions options = new FormatOptions(); @@ -66,7 +72,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("CTE_EachReferenceOnNewLine_CommasBeforeDefinition.sql"), options, false); } - [Fact] + [Test] public void CTE_UseTabs() { FormatOptions options = new FormatOptions(); @@ -76,7 +82,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("CTE_UseTabs.sql"), options, true); } - [Fact] + [Test] public void CTE_20Spaces() { FormatOptions options = new FormatOptions(); @@ -86,7 +92,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("CTE_20Spaces.sql"), options, true); } - [Fact] + [Test] public void CTE_UpperCaseKeywords() { FormatOptions options = new FormatOptions(); @@ -96,7 +102,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("CTE_UpperCaseKeywords.sql"), options, true); } - [Fact] + [Test] public void CTE_LowerCaseKeywords() { FormatOptions options = new FormatOptions(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateProcedureFormatterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateProcedureFormatterTests.cs index 173fa415..b1193591 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateProcedureFormatterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateProcedureFormatterTests.cs @@ -4,69 +4,75 @@ // using Microsoft.SqlTools.ServiceLayer.Formatter; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class CreateProcedureFormatterTests : FormatterUnitTestsBase { - [Fact] + [SetUp] + public void Init() + { + InitFormatterUnitTestsBase(); + } + + [Test] public void CreateProcedure_BackwardsCompatible() { LoadAndFormatAndCompare("CreateProcedure_BackwardsCompatible", GetInputFile("CreateProcedure_BackwardsCompatible.sql"), GetBaselineFile("CreateProcedure_BackwardsCompatible.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_BeginEnd() { LoadAndFormatAndCompare("CreateProcedure_BeginEnd", GetInputFile("CreateProcedure_BeginEnd.sql"), GetBaselineFile("CreateProcedure_BeginEnd.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_Minimal() { LoadAndFormatAndCompare("CreateProcedure_Minimal", GetInputFile("CreateProcedure_Minimal.sql"), GetBaselineFile("CreateProcedure_Minimal.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_MultipleBatches() { LoadAndFormatAndCompare("CreateProcedure_MultipleBatches", GetInputFile("CreateProcedure_MultipleBatches.sql"), GetBaselineFile("CreateProcedure_MultipleBatches.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_MultipleParams() { LoadAndFormatAndCompare("CreateProcedure_MultipleParams", GetInputFile("CreateProcedure_MultipleParams.sql"), GetBaselineFile("CreateProcedure_MultipleParams.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_OneParam() { LoadAndFormatAndCompare("CreateProcedure_OneParam", GetInputFile("CreateProcedure_OneParam.sql"), GetBaselineFile("CreateProcedure_OneParam.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_ParamsRecompileReturn() { LoadAndFormatAndCompare("CreateProcedure_ParamsRecompileReturn", GetInputFile("CreateProcedure_ParamsRecompileReturn.sql"), GetBaselineFile("CreateProcedure_ParamsRecompileReturn.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_Select() { LoadAndFormatAndCompare("CreateProcedure_Select", GetInputFile("CreateProcedure_Select.sql"), GetBaselineFile("CreateProcedure_Select.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_CommaBeforeNextColumn() { // Verifies that commas are placed before the next column instead of after the current one, @@ -83,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter }, true); } - [Fact] + [Test] public void CreateProcedure_CommaBeforeNextColumnRepeated() { // Verifies that formatting isn't changed for text that's already been formatted @@ -101,7 +107,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter true); } - [Fact] + [Test] public void CreateProcedure_CommaBeforeNextColumnNoNewline() { // Verifies that commas are placed before the next column instead of after the current one, @@ -119,35 +125,35 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter }, true); } - [Fact] + [Test] public void CreateProcedure_TwoPartName() { LoadAndFormatAndCompare("CreateProcedure_TwoPartName", GetInputFile("CreateProcedure_TwoPartName.sql"), GetBaselineFile("CreateProcedure_TwoPartName.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_WithCTE() { LoadAndFormatAndCompare("CreateProcedure_WithCTE", GetInputFile("CreateProcedure_WithCTE.sql"), GetBaselineFile("CreateProcedure_WithCTE.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_WithEncryptionModule() { LoadAndFormatAndCompare("CreateProcedure_WithEncryptionModule", GetInputFile("CreateProcedure_WithEncryptionModule.sql"), GetBaselineFile("CreateProcedure_WithEncryptionModule.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_WithExecuteAsModule() { LoadAndFormatAndCompare("CreateProcedure_WithExecuteAsModule", GetInputFile("CreateProcedure_WithExecuteAsModule.sql"), GetBaselineFile("CreateProcedure_WithExecuteAsModule.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateProcedure_WithThreeModules() { LoadAndFormatAndCompare("CreateProcedure_WithThreeModules", GetInputFile("CreateProcedure_WithThreeModules.sql"), diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateTableFormatterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateTableFormatterTests.cs index cbf5fb7c..f65f3349 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateTableFormatterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateTableFormatterTests.cs @@ -4,14 +4,20 @@ // using Microsoft.SqlTools.ServiceLayer.Formatter; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class CreateTableFormatterTests : FormatterUnitTestsBase { - [Fact] + [SetUp] + public void Init() + { + InitFormatterUnitTestsBase(); + } + + [Test] public void CreateTable() { LoadAndFormatAndCompare("CreateTable", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable.sql"), new FormatOptions(), true); @@ -20,7 +26,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter /** * The test contains a timestamp column, which is the shortest (1 token) possible length for a column item. */ - [Fact] + [Test] public void CreateTable_Timestamp() { FormatOptions options = new FormatOptions(); @@ -28,7 +34,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_Timestamp", GetInputFile("CreateTable_Timestamp.sql"), GetBaselineFile("CreateTable_Timestamp.sql"), options, true); } - [Fact] + [Test] public void CreateTable_CommasBeforeDefinition() { FormatOptions options = new FormatOptions(); @@ -38,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_CommasBeforeDefinition", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable_CommasBeforeDefinition.sql"), options, false); } - [Fact] + [Test] public void CreateTable_UseTabs() { FormatOptions options = new FormatOptions(); @@ -46,7 +52,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_UseTabs", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable_UseTabs.sql"), options, true); } - [Fact] + [Test] public void CreateTable_20Spaces() { FormatOptions options = new FormatOptions(); @@ -54,7 +60,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_20Spaces", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable_20Spaces.sql"), options, true); } - [Fact] + [Test] public void CreateTable_UpperCaseKeywords() { FormatOptions options = new FormatOptions(); @@ -62,7 +68,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_UpperCaseKeywords", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable_UpperCaseKeywords.sql"), options, true); } - [Fact] + [Test] public void CreateTable_LowerCaseKeywords() { FormatOptions options = new FormatOptions(); @@ -70,7 +76,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_LowerCaseKeywords", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable_LowerCaseKeywords.sql"), options, true); } - [Fact] + [Test] public void CreateTable_UpperCaseDataTypes() { FormatOptions options = new FormatOptions(); @@ -78,7 +84,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_UpperCaseDataTypes", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable_UpperCaseDataTypes.sql"), options, true); } - [Fact] + [Test] public void CreateTable_LowerCaseDataTypes() { FormatOptions options = new FormatOptions(); @@ -86,14 +92,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_LowerCaseDataTypes", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable_LowerCaseDataTypes.sql"), options, true); } - [Fact] + [Test] public void CreateTable_AlignInColumns() { FormatOptions options = new FormatOptions() { AlignColumnDefinitionsInColumns = true }; LoadAndFormatAndCompare("CreateTable_AlignInColumns", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable_AlignInColumns.sql"), options, true); } - [Fact] + [Test] public void CreateTable_AlignInColumnsUseTabs() { FormatOptions options = new FormatOptions(); @@ -102,19 +108,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_AlignInColumnsUseTabs", GetInputFile("CreateTable.sql"), GetBaselineFile("CreateTable_AlignInColumnsUseTabs.sql"), options, true); } - [Fact] + [Test] public void CreateTable_On() { LoadAndFormatAndCompare("CreateTableOn", GetInputFile("CreateTableFull.sql"), GetBaselineFile("CreateTableOn.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateTable_Formatted() { LoadAndFormatAndCompare("CreateTable_Formatted", GetInputFile("CreateTable_Formatted.sql"), GetBaselineFile("CreateTable_Formatted.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateTable_CommentsBeforeComma() { FormatOptions options = new FormatOptions(); @@ -124,7 +130,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTable_CommentsBeforeComma", GetInputFile("CreateTable_CommentBeforeComma.sql"), GetBaselineFile("CreateTable_CommentBeforeComma.sql"), options, true); } - [Fact] + [Test] public void CreateTableAddress_AlignInColumns() { FormatOptions options = new FormatOptions(); @@ -132,7 +138,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LoadAndFormatAndCompare("CreateTableAddress_AlignInColumns", GetInputFile("Address.sql"), GetBaselineFile("CreateTableAddress_AlignInColumns.sql"), options, true); } - [Fact] + [Test] public void CreateTableAddress_AlignInColumnsUseTabs() { FormatOptions options = new FormatOptions(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateViewFormatterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateViewFormatterTests.cs index 18d07239..c25f585d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateViewFormatterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/CreateViewFormatterTests.cs @@ -5,62 +5,68 @@ using Microsoft.SqlTools.ServiceLayer.Formatter; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class CreateViewFormatterTests : FormatterUnitTestsBase { - [Fact] + [SetUp] + public void Init() + { + InitFormatterUnitTestsBase(); + } + + [Test] public void CreateView_Full() { LoadAndFormatAndCompare("CreateView_Full", GetInputFile("CreateView_Full.sql"), GetBaselineFile("CreateView_Full.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateView_FullWithComments() { LoadAndFormatAndCompare("CreateView_FullWithComments", GetInputFile("CreateView_FullWithComments.sql"), GetBaselineFile("CreateView_FullWithComments.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateView_MultipleColumns() { LoadAndFormatAndCompare("CreateView_MultipleColumns", GetInputFile("CreateView_MultipleColumns.sql"), GetBaselineFile("CreateView_MultipleColumns.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateView_MultipleOptions() { LoadAndFormatAndCompare("CreateView_MultipleOptions", GetInputFile("CreateView_MultipleOptions.sql"), GetBaselineFile("CreateView_MultipleOptions.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateView_OneColumn() { LoadAndFormatAndCompare("CreateView_OneColumn", GetInputFile("CreateView_OneColumn.sql"), GetBaselineFile("CreateView_OneColumn.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateView_OneColumnOneOption() { LoadAndFormatAndCompare("CreateView_OneColumnOneOption", GetInputFile("CreateView_OneColumnOneOption.sql"), GetBaselineFile("CreateView_OneColumnOneOption.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateView_OneOption() { LoadAndFormatAndCompare("CreateView_OneOption", GetInputFile("CreateView_OneOption.sql"), GetBaselineFile("CreateView_OneOption.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void CreateView_Simple() { LoadAndFormatAndCompare("CreateView_Simple", GetInputFile("CreateView_Simple.sql"), diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/FormatterSettingsTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/FormatterSettingsTests.cs index 6da2dc94..5a943880 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/FormatterSettingsTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/FormatterSettingsTests.cs @@ -8,25 +8,25 @@ using Microsoft.SqlTools.ServiceLayer.Formatter; using Microsoft.SqlTools.ServiceLayer.Formatter.Contracts; using Microsoft.SqlTools.ServiceLayer.SqlContext; using Newtonsoft.Json.Linq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class FormatterSettingsTests { - [Fact] + [Test] public void ValidateFormatterServiceDefaults() { var sqlToolsSettings = new SqlToolsSettings(); Assert.Null(sqlToolsSettings.SqlTools.Format.AlignColumnDefinitionsInColumns); - Assert.Equal(CasingOptions.None, sqlToolsSettings.SqlTools.Format.DatatypeCasing); - Assert.Equal(CasingOptions.None, sqlToolsSettings.SqlTools.Format.KeywordCasing); + Assert.AreEqual(CasingOptions.None, sqlToolsSettings.SqlTools.Format.DatatypeCasing); + Assert.AreEqual(CasingOptions.None, sqlToolsSettings.SqlTools.Format.KeywordCasing); Assert.Null(sqlToolsSettings.SqlTools.Format.PlaceCommasBeforeNextStatement); Assert.Null(sqlToolsSettings.SqlTools.Format.PlaceSelectStatementReferencesOnNewLine); Assert.Null(sqlToolsSettings.SqlTools.Format.UseBracketForIdentifiers); } - [Fact] + [Test] public void ValidateFormatSettingsParsedFromJson() { ValidateFormatSettings("mssql"); @@ -57,14 +57,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter SqlToolsSettings sqlToolsSettings = messageParams.ToObject(); Assert.True(sqlToolsSettings.SqlTools.Format.AlignColumnDefinitionsInColumns); - Assert.Equal(CasingOptions.Lowercase, sqlToolsSettings.SqlTools.Format.DatatypeCasing); - Assert.Equal(CasingOptions.Uppercase, sqlToolsSettings.SqlTools.Format.KeywordCasing); + Assert.AreEqual(CasingOptions.Lowercase, sqlToolsSettings.SqlTools.Format.DatatypeCasing); + Assert.AreEqual(CasingOptions.Uppercase, sqlToolsSettings.SqlTools.Format.KeywordCasing); Assert.True(sqlToolsSettings.SqlTools.Format.PlaceCommasBeforeNextStatement); Assert.True(sqlToolsSettings.SqlTools.Format.PlaceSelectStatementReferencesOnNewLine); Assert.True(sqlToolsSettings.SqlTools.Format.UseBracketForIdentifiers); } - [Fact] + [Test] public void FormatOptionsMatchDefaultSettings() { var options = new FormatOptions(); @@ -74,14 +74,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter private static void AssertOptionsHaveDefaultValues(FormatOptions options) { Assert.False(options.AlignColumnDefinitionsInColumns); - Assert.Equal(CasingOptions.None, options.DatatypeCasing); - Assert.Equal(CasingOptions.None, options.KeywordCasing); + Assert.AreEqual(CasingOptions.None, options.DatatypeCasing); + Assert.AreEqual(CasingOptions.None, options.KeywordCasing); Assert.False(options.PlaceCommasBeforeNextStatement); Assert.False(options.PlaceEachReferenceOnNewLineInQueryStatements); Assert.False(options.EncloseIdentifiersInSquareBrackets); } - [Fact] + [Test] public void CanCopyDefaultFormatSettingsToOptions() { var sqlToolsSettings = new SqlToolsSettings(); @@ -90,7 +90,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter AssertOptionsHaveDefaultValues(options); } - [Fact] + [Test] public void CanCopyAlteredFormatSettingsToOptions() { SqlToolsSettings sqlToolsSettings = CreateNonDefaultFormatSettings(); @@ -116,8 +116,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter private static void AssertOptionsHaveExpectedNonDefaultValues(FormatOptions options) { Assert.True(options.AlignColumnDefinitionsInColumns); - Assert.Equal(CasingOptions.Lowercase, options.DatatypeCasing); - Assert.Equal(CasingOptions.Uppercase, options.KeywordCasing); + Assert.AreEqual(CasingOptions.Lowercase, options.DatatypeCasing); + Assert.AreEqual(CasingOptions.Uppercase, options.KeywordCasing); Assert.True(options.PlaceCommasBeforeNextStatement); Assert.True(options.PlaceEachReferenceOnNewLineInQueryStatements); Assert.True(options.EncloseIdentifiersInSquareBrackets); @@ -130,7 +130,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter Assert.False(options.DoNotFormatKeywords); } - [Fact] + [Test] public void CanMergeRequestOptionsAndSettings() { var sqlToolsSettings = CreateNonDefaultFormatSettings(); @@ -142,7 +142,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter AssertOptionsHaveExpectedNonDefaultValues(options); Assert.False(options.UseTabs); Assert.True(options.UseSpaces); - Assert.Equal(2, options.SpacesPerIndent); + Assert.AreEqual(2, options.SpacesPerIndent); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/FormatterUnitTestBase.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/FormatterUnitTestBase.cs index 8cefa3ba..0ec6dc30 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/FormatterUnitTestBase.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/FormatterUnitTestBase.cs @@ -18,7 +18,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class FormatterUnitTestsBase { - public FormatterUnitTestsBase() + protected void InitFormatterUnitTestsBase() { HostMock = new Mock(); WorkspaceServiceMock = new Mock>(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/GeneralFormatterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/GeneralFormatterTests.cs index 63e4363c..e63e5b0f 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/GeneralFormatterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/GeneralFormatterTests.cs @@ -4,13 +4,19 @@ // using Microsoft.SqlTools.ServiceLayer.Formatter; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class GeneralFormatterTests : FormatterUnitTestsBase { - [Fact] + [SetUp] + public void Init() + { + InitFormatterUnitTestsBase(); + } + + [Test] public void GoNewLineShouldBePreserved() { LoadAndFormatAndCompare("GoNewLineShouldBePreserved", @@ -24,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter verifyFormat: true); } - [Fact] + [Test] public void KeywordCaseConversionUppercase() { LoadAndFormatAndCompare("KeywordCaseConversion", @@ -34,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter verifyFormat: true); } - [Fact] + [Test] public void KeywordCaseConversionLowercase() { LoadAndFormatAndCompare("KeywordCaseConversion", @@ -44,7 +50,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter verifyFormat: true); } - [Fact] + [Test] public void SelectWithOrderByShouldCorrectlyIndent() { LoadAndFormatAndCompare("SelectWithOrderByShouldCorrectlyIndent", @@ -54,7 +60,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter verifyFormat: true); } - [Fact] + [Test] public void SelectStatementShouldCorrectlyIndent() { LoadAndFormatAndCompare("SelectStatementShouldCorrectlyIndent", diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/InsertFormatterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/InsertFormatterTests.cs index c18ba630..1c922bce 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/InsertFormatterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/InsertFormatterTests.cs @@ -5,42 +5,48 @@ using Microsoft.SqlTools.ServiceLayer.Formatter; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class InsertFormatterTests : FormatterUnitTestsBase { - [Fact] + [SetUp] + public void Init() + { + InitFormatterUnitTestsBase(); + } + + [Test] public void Insert_DefaultValues() { LoadAndFormatAndCompare("Insert_DefaultValues", GetInputFile("Insert_DefaultValues.sql"), GetBaselineFile("Insert_DefaultValues.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void Insert_OpenQuery() { LoadAndFormatAndCompare("Insert_OpenQuery", GetInputFile("Insert_OpenQuery.sql"), GetBaselineFile("Insert_OpenQuery.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void Insert_OutputInto() { LoadAndFormatAndCompare("Insert_OutputInto", GetInputFile("Insert_OutputInto.sql"), GetBaselineFile("Insert_OutputInto.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void Insert_OutputStatement() { LoadAndFormatAndCompare("Insert_OutputStatement", GetInputFile("Insert_OutputStatement.sql"), GetBaselineFile("Insert_OutputStatement.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void Insert_Select() { FormatOptions options = new FormatOptions(); @@ -49,7 +55,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("Insert_Select.sql"), options, true); } - [Fact] + [Test] public void Insert_SelectSource() { FormatOptions options = new FormatOptions(); @@ -58,21 +64,21 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("Insert_SelectSource.sql"), options, true); } - [Fact] + [Test] public void Insert_TopSpecification() { LoadAndFormatAndCompare("Insert_TopSpecification", GetInputFile("Insert_TopSpecification.sql"), GetBaselineFile("Insert_TopSpecification.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void Insert_TopWithComments() { LoadAndFormatAndCompare("Insert_TopWithComments", GetInputFile("Insert_TopWithComments.sql"), GetBaselineFile("Insert_TopWithComments.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void Insert_Full() { LoadAndFormatAndCompare("Insert_Full", GetInputFile("Insert_Full.sql"), diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/SqlSelectStatementFormatterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/SqlSelectStatementFormatterTests.cs index c88a7354..4ebec0cc 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/SqlSelectStatementFormatterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/SqlSelectStatementFormatterTests.cs @@ -4,21 +4,27 @@ // using Microsoft.SqlTools.ServiceLayer.Formatter; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class SqlSelectStatementFormatterTests : FormatterUnitTestsBase { - [Fact] + [SetUp] + public void Init() + { + InitFormatterUnitTestsBase(); + } + + [Test] public void SimpleQuery() { LoadAndFormatAndCompare("SimpleQuery", GetInputFile("SimpleQuery.sql"), GetBaselineFile("SimpleQuery.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void SimpleQuery_CommasBeforeDefinition() { FormatOptions options = new FormatOptions(); @@ -29,7 +35,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("SimpleQuery_CommasBeforeDefinition.sql"), options, false); } - [Fact] + [Test] public void SimpleQuery_EachReferenceOnNewLine() { FormatOptions options = new FormatOptions(); @@ -39,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("SimpleQuery_EachReferenceOnNewLine.sql"), options, true); } - [Fact] + [Test] public void SimpleQuery_EachReferenceOnNewLine_CommasBeforeDefinition() { FormatOptions options = new FormatOptions(); @@ -51,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetInputFile("SimpleQuery.sql"), GetBaselineFile("SimpleQuery_EachReferenceOnNewLine_CommasBeforeDefinition.sql"), options, false); } - [Fact] + [Test] public void SimpleQuery_UseTabs() { FormatOptions options = new FormatOptions(); @@ -61,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("SimpleQuery_UseTabs.sql"), options, true); } - [Fact] + [Test] public void SimpleQuery_20Spaces() { FormatOptions options = new FormatOptions(); @@ -71,7 +77,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("SimpleQuery_20Spaces.sql"), options, true); } - [Fact] + [Test] public void SimpleQuery_UpperCaseKeywords() { FormatOptions options = new FormatOptions(); @@ -81,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("SimpleQuery_UpperCaseKeywords.sql"), options, true); } - [Fact] + [Test] public void SimpleQuery_LowerCaseKeywords() { FormatOptions options = new FormatOptions(); @@ -91,14 +97,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter GetBaselineFile("SimpleQuery_LowerCaseKeywords.sql"), options, true); } - [Fact] + [Test] public void SimpleQuery_ForBrowseClause() { LoadAndFormatAndCompare("SimpleQuery_ForBrowseClause", GetInputFile("SimpleQuery_ForBrowseClause.sql"), GetBaselineFile("SimpleQuery_ForBrowseClause.sql"), new FormatOptions(), true); } - [Fact] + [Test] public void SimpleQuery_ForXmlClause() { LoadAndFormatAndCompare("SimpleQuery_ForXmlClause", GetInputFile("SimpleQuery_ForXmlClause.sql"), diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/TSqlFormatterServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/TSqlFormatterServiceTests.cs index d7ef6cc7..9324c97b 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/TSqlFormatterServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Formatter/TSqlFormatterServiceTests.cs @@ -16,19 +16,22 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { public class TSqlFormatterServiceTests : FormatterUnitTestsBase { - private Mock workspaceMock = new Mock(); + private Mock workspaceMock; private TextDocumentIdentifier textDocument; DocumentFormattingParams docFormatParams; DocumentRangeFormattingParams rangeFormatParams; - public TSqlFormatterServiceTests() + [SetUp] + public void InitTSqlFormatterServiceTests() { + InitFormatterUnitTestsBase(); + workspaceMock = new Mock(); textDocument = new TextDocumentIdentifier { Uri = "script file" @@ -64,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter LanguageServiceMock.Setup(x => x.ShouldSkipNonMssqlFile(It.IsAny())).Returns(skipFile); } - [Fact] + [Test] public async Task FormatDocumentShouldReturnSingleEdit() { // Given a document that we want to format @@ -76,12 +79,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter verify: (edits => { // Then expect a single edit to be returned and for it to match the standard formatting - Assert.Equal(1, edits.Length); + Assert.AreEqual(1, edits.Length); AssertFormattingEqual(formattedSqlContents, edits[0].NewText); })); } - [Fact] + [Test] public async Task FormatDocumentShouldSkipNonMssqlFile() { // Given a non-MSSQL document @@ -93,12 +96,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter verify: (edits => { // Then expect a single edit to be returned and for it to match the standard formatting - Assert.Equal(0, edits.Length); + Assert.AreEqual(0, edits.Length); LanguageServiceMock.Verify(x => x.ShouldSkipNonMssqlFile(docFormatParams.TextDocument.Uri), Times.Once); })); } - [Fact] + [Test] public async Task FormatRangeShouldReturnSingleEdit() { // Given a document that we want to format @@ -110,12 +113,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter verify: (edits => { // Then expect a single edit to be returned and for it to match the standard formatting - Assert.Equal(1, edits.Length); + Assert.AreEqual(1, edits.Length); AssertFormattingEqual(formattedSqlContents, edits[0].NewText); })); } - [Fact] + [Test] public async Task FormatRangeShouldSkipNonMssqlFile() { // Given a non-MSSQL document @@ -127,13 +130,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter verify: (edits => { // Then expect a single edit to be returned and for it to match the standard formatting - Assert.Equal(0, edits.Length); + Assert.AreEqual(0, edits.Length); LanguageServiceMock.Verify(x => x.ShouldSkipNonMssqlFile(docFormatParams.TextDocument.Uri), Times.Once); })); } - [Fact] + [Test] public async Task FormatDocumentTelemetryShouldIncludeFormatTypeProperty() { await RunAndVerifyTelemetryTest( @@ -145,12 +148,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { // Then expect a telemetry event to have been sent with the right format definition Assert.NotNull(actualParams); - Assert.Equal(TelemetryEventNames.FormatCode, actualParams.Params.EventName); - Assert.Equal(TelemetryPropertyNames.DocumentFormatType, actualParams.Params.Properties[TelemetryPropertyNames.FormatType]); + Assert.AreEqual(TelemetryEventNames.FormatCode, actualParams.Params.EventName); + Assert.AreEqual(TelemetryPropertyNames.DocumentFormatType, actualParams.Params.Properties[TelemetryPropertyNames.FormatType]); }); } - [Fact] + [Test] public async Task FormatRangeTelemetryShouldIncludeFormatTypeProperty() { await RunAndVerifyTelemetryTest( @@ -162,11 +165,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { // Then expect a telemetry event to have been sent with the right format definition Assert.NotNull(actualParams); - Assert.Equal(TelemetryEventNames.FormatCode, actualParams.Params.EventName); - Assert.Equal(TelemetryPropertyNames.RangeFormatType, actualParams.Params.Properties[TelemetryPropertyNames.FormatType]); + Assert.AreEqual(TelemetryEventNames.FormatCode, actualParams.Params.EventName); + Assert.AreEqual(TelemetryPropertyNames.RangeFormatType, actualParams.Params.Properties[TelemetryPropertyNames.FormatType]); // And expect range to have been correctly formatted - Assert.Equal(1, result.Length); + Assert.AreEqual(1, result.Length); AssertFormattingEqual(formattedSqlContents, result[0].NewText); }); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageExtensibility/ExternalLanguageOperationTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageExtensibility/ExternalLanguageOperationTests.cs index 7ed06c18..a1fb7068 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageExtensibility/ExternalLanguageOperationTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageExtensibility/ExternalLanguageOperationTests.cs @@ -5,13 +5,13 @@ using Moq; using System; using System.Collections.Generic; using System.Data; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageExtensibility { public class ExternalLanguageOperationTests { - [Fact] + [Test] public void VerifyDeleteLanguageWithInvalidName() { ExternalLanguageOperations operations = new ExternalLanguageOperations(); @@ -23,7 +23,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageExtensibility }); } - [Fact] + [Test] public void VerifyDeleteLanguage() { ExternalLanguageOperations operations = new ExternalLanguageOperations(); @@ -39,7 +39,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageExtensibility }); } - [Fact] + [Test] public void VerifyCreateLanguage() { ExternalLanguageOperations operations = new ExternalLanguageOperations(); @@ -63,7 +63,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageExtensibility }); } - [Fact] + [Test] public void VerifyCreateLanguageWithLocalFile() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) @@ -90,7 +90,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageExtensibility } } - [Fact] + [Test] public void VerifyUpdateLanguage() { ExternalLanguageOperations operations = new ExternalLanguageOperations(); @@ -130,7 +130,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageExtensibility }); } - [Fact] + [Test] public void VerifyUpdateContentLanguage() { ExternalLanguageOperations operations = new ExternalLanguageOperations(); @@ -168,7 +168,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageExtensibility }); } - [Fact] + [Test] public void VerifyRemoveContentLanguage() { ExternalLanguageOperations operations = new ExternalLanguageOperations(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/AutocompleteTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/AutocompleteTests.cs index f8102e4e..d724a525 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/AutocompleteTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/AutocompleteTests.cs @@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Moq; -using Xunit; +using NUnit.Framework; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Location = Microsoft.SqlTools.ServiceLayer.Workspace.Contracts.Location; @@ -22,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer public class AutocompleteTests : LanguageServiceTestBase { - [Fact] + [Test] public void HandleCompletionRequestDisabled() { InitializeTestObjects(); @@ -30,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.NotNull(langService.HandleCompletionRequest(null, null)); } - [Fact] + [Test] public void HandleCompletionResolveRequestDisabled() { InitializeTestObjects(); @@ -38,7 +38,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.NotNull(langService.HandleCompletionResolveRequest(null, null)); } - [Fact] + [Test] public void HandleSignatureHelpRequestDisabled() { InitializeTestObjects(); @@ -46,7 +46,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.NotNull(langService.HandleSignatureHelpRequest(null, null)); } - [Fact] + [Test] public async Task HandleSignatureHelpRequestNonMssqlFile() { InitializeTestObjects(); @@ -75,7 +75,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer signatureRequestContext.Verify(m => m.SendError(It.IsAny(), It.IsAny()), Times.Never()); } - [Fact] + [Test] public void AddOrUpdateScriptParseInfoNullUri() { InitializeTestObjects(); @@ -83,8 +83,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.True(langService.ScriptParseInfoMap.ContainsKey("abracadabra")); } - [Fact] - public async void HandleDefinitionRequest_InvalidTextDocument_SendsEmptyListResponse() + [Test] + public async Task HandleDefinitionRequest_InvalidTextDocument_SendsEmptyListResponse() { InitializeTestObjects(); textDocument.TextDocument.Uri = "invaliduri"; @@ -104,22 +104,22 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.True(result.Length == 0, $"Unexpected values passed to SendResult : [{ string.Join(",", (object[])result)}]"); } - [Fact] + [Test] public void RemoveScriptParseInfoNullUri() { InitializeTestObjects(); Assert.False(langService.RemoveScriptParseInfo("abc123")); } - [Fact] + [Test] public void IsPreviewWindowNullScriptFileTest() { InitializeTestObjects(); Assert.False(langService.IsPreviewWindow(null)); } - [Fact] - public async void HandleCompletionRequest_InvalidTextDocument_SendsNullResult() + [Test] + public async Task HandleCompletionRequest_InvalidTextDocument_SendsNullResult() { InitializeTestObjects(); // setup the mock for SendResult to capture the items @@ -136,7 +136,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.Null(completionItems); } - [Fact] + [Test] public void GetDiagnosticFromMarkerTest() { var scriptFileMarker = new ScriptFileMarker() @@ -155,26 +155,26 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer } }; var diagnostic = DiagnosticsHelper.GetDiagnosticFromMarker(scriptFileMarker); - Assert.Equal(diagnostic.Message, scriptFileMarker.Message); + Assert.AreEqual(diagnostic.Message, scriptFileMarker.Message); } - [Fact] + [Test] public void MapDiagnosticSeverityTest() { var level = ScriptFileMarkerLevel.Error; - Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Error); + Assert.AreEqual(DiagnosticSeverity.Error, DiagnosticsHelper.MapDiagnosticSeverity(level)); level = ScriptFileMarkerLevel.Warning; - Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Warning); + Assert.AreEqual(DiagnosticSeverity.Warning, DiagnosticsHelper.MapDiagnosticSeverity(level)); level = ScriptFileMarkerLevel.Information; - Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Information); + Assert.AreEqual(DiagnosticSeverity.Information, DiagnosticsHelper.MapDiagnosticSeverity(level)); level = (ScriptFileMarkerLevel)100; - Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Error); + Assert.AreEqual(DiagnosticSeverity.Error, DiagnosticsHelper.MapDiagnosticSeverity(level)); } /// /// Tests the primary completion list event handler /// - [Fact] + [Test] public void GetCompletionsHandlerTest() { InitializeTestObjects(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/BindingQueueTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/BindingQueueTests.cs index 40f5c2a5..b1c20f4c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/BindingQueueTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/BindingQueueTests.cs @@ -13,7 +13,7 @@ using Microsoft.SqlServer.Management.SqlParser.MetadataProvider; using Microsoft.SqlServer.Management.SqlParser.Parser; using Microsoft.SqlTools.ServiceLayer.LanguageServices; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer { @@ -115,7 +115,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// /// Queues a single task /// - [Fact] + [Test] public void QueueOneBindingOperationTest() { InitializeTestSettings(); @@ -129,15 +129,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer this.bindingQueue.StopQueueProcessor(15000); - Assert.Equal(1, this.bindCallCount); - Assert.Equal(0, this.timeoutCallCount); + Assert.AreEqual(1, this.bindCallCount); + Assert.AreEqual(0, this.timeoutCallCount); Assert.False(this.isCancelationRequested); } /// /// Queues a single task /// - [Fact] + [Test] public void QueueWithUnhandledExceptionTest() { InitializeTestSettings(); @@ -158,14 +158,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.True(isExceptionHandled); var result = queueItem.GetResultAsT(); - Assert.Equal(defaultReturnObject, result); + Assert.AreEqual(defaultReturnObject, result); } /// /// Queue a 100 short tasks /// // Disable flaky test (mairvine - 3/15/2018) - // [Fact] + // [Test] public void Queue100BindingOperationTest() { InitializeTestSettings(); @@ -182,15 +182,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer this.bindingQueue.StopQueueProcessor(15000); - Assert.Equal(100, this.bindCallCount); - Assert.Equal(0, this.timeoutCallCount); + Assert.AreEqual(100, this.bindCallCount); + Assert.AreEqual(0, this.timeoutCallCount); Assert.False(this.isCancelationRequested); } /// /// Queue an task with a long operation causing a timeout /// - [Fact] + [Test] public void QueueWithTimeout() { InitializeTestSettings(); @@ -207,8 +207,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer this.bindingQueue.StopQueueProcessor(15000); - Assert.Equal(0, this.bindCallCount); - Assert.Equal(1, this.timeoutCallCount); + Assert.AreEqual(0, this.bindCallCount); + Assert.AreEqual(1, this.timeoutCallCount); Assert.True(this.isCancelationRequested); } @@ -216,7 +216,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Queue a task with a long operation causing a timeout /// and make sure subsequent tasks don't execute while task is completing /// - [Fact] + [Test] public void QueueWithTimeoutDoesNotRunNextTask() { string operationKey = "testkey"; @@ -261,7 +261,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer this.bindingQueue.StopQueueProcessor(15000); - Assert.Equal(1, this.timeoutCallCount); + Assert.AreEqual(1, this.timeoutCallCount); Assert.False(firstOperationCanceled); Assert.False(secondOperationExecuted); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/CompletionServiceTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/CompletionServiceTest.cs index 02c5070d..fe137b73 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/CompletionServiceTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/CompletionServiceTest.cs @@ -14,14 +14,14 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer { public class CompletionServiceTest { // Disable flaky test (mairvine - 3/15/2018) - // [Fact] + // [Test] public void CompletionItemsShouldCreatedUsingSqlParserIfTheProcessDoesNotTimeout() { ConnectedBindingQueue bindingQueue = new ConnectedBindingQueue(); @@ -40,10 +40,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer AutoCompletionResult result = completionService.CreateCompletions(connectionInfo, docInfo, useLowerCaseSuggestions); Assert.NotNull(result); - Assert.NotEqual(result.CompletionItems == null ? 0 : result.CompletionItems.Count(), defaultCompletionList.Count()); + var count = result.CompletionItems == null ? 0 : result.CompletionItems.Count(); + + Assert.That(count, Is.Not.EqualTo(defaultCompletionList.Count())); } - [Fact] + [Test] public void CompletionItemsShouldCreatedUsingDefaultListIfTheSqlParserProcessTimesout() { ConnectedBindingQueue bindingQueue = new ConnectedBindingQueue(); @@ -61,7 +63,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer AutoCompletionResult result = completionService.CreateCompletions(connectionInfo, docInfo, useLowerCaseSuggestions); Assert.NotNull(result); - Assert.Equal(result.CompletionItems.Count(), defaultCompletionList.Count()); + Assert.AreEqual(result.CompletionItems.Count(), defaultCompletionList.Count()); Thread.Sleep(3000); Assert.True(connectionInfo.IntellisenseMetrics.Quantile.Any()); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/InteractionMetricsTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/InteractionMetricsTest.cs index a71d27b4..ffc4fbc2 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/InteractionMetricsTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/InteractionMetricsTest.cs @@ -5,57 +5,57 @@ using System; using System.Collections.Generic; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer { public class InteractionMetricsTest { - [Fact] + [Test] public void MetricsShouldGetSortedGivenUnSortedArray() { int[] metrics = new int[] { 4, 8, 1, 11, 3 }; int[] expected = new int[] { 1, 3, 4, 8, 11 }; InteractionMetrics interactionMetrics = new InteractionMetrics(metrics); - Assert.Equal(interactionMetrics.Metrics, expected); + Assert.AreEqual(interactionMetrics.Metrics, expected); } - [Fact] + [Test] public void MetricsShouldThrowExceptionGivenNullInput() { int[] metrics = null; Assert.Throws(() => new InteractionMetrics(metrics)); } - [Fact] + [Test] public void MetricsShouldThrowExceptionGivenEmptyInput() { int[] metrics = new int[] { }; Assert.Throws(() => new InteractionMetrics(metrics)); } - [Fact] + [Test] public void MetricsShouldNotChangeGivenSortedArray() { int[] metrics = new int[] { 1, 3, 4, 8, 11 }; int[] expected = new int[] { 1, 3, 4, 8, 11 }; InteractionMetrics interactionMetrics = new InteractionMetrics(metrics); - Assert.Equal(interactionMetrics.Metrics, expected); + Assert.AreEqual(interactionMetrics.Metrics, expected); } - [Fact] + [Test] public void MetricsShouldNotChangeGivenArrayWithOneItem() { int[] metrics = new int[] { 11 }; int[] expected = new int[] { 11 }; InteractionMetrics interactionMetrics = new InteractionMetrics(metrics); - Assert.Equal(interactionMetrics.Metrics, expected); + Assert.AreEqual(interactionMetrics.Metrics, expected); } - [Fact] + [Test] public void MetricsCalculateQuantileCorrectlyGivenSeveralUpdates() { int[] metrics = new int[] { 50, 100, 300, 500, 1000, 2000 }; @@ -72,12 +72,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Dictionary quantile = interactionMetrics.Quantile; Assert.NotNull(quantile); - Assert.Equal(quantile.Count, 5); - Assert.Equal(quantile["50"], 1); - Assert.Equal(quantile["100"], 2); - Assert.Equal(quantile["300"], 1); - Assert.Equal(quantile["500"], 2); - Assert.Equal(quantile["2000"], 2); + Assert.AreEqual(5, quantile.Count); + Assert.AreEqual(1, quantile["50"]); + Assert.AreEqual(2, quantile["100"]); + Assert.AreEqual(1, quantile["300"]); + Assert.AreEqual(2, quantile["500"]); + Assert.AreEqual(2, quantile["2000"]); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/LanguageServiceTestBase.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/LanguageServiceTestBase.cs index fda18ca5..d3d89054 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/LanguageServiceTestBase.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/LanguageServiceTestBase.cs @@ -19,7 +19,7 @@ using Microsoft.SqlTools.ServiceLayer.Workspace; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using GlobalCommon = Microsoft.SqlTools.ServiceLayer.Test.Common; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer { diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/LanguageServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/LanguageServiceTests.cs index 8e84a9ec..99141535 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/LanguageServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/LanguageServiceTests.cs @@ -8,7 +8,7 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer { @@ -20,7 +20,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// /// Verify that the latest SqlParser (2016 as of this writing) is used by default /// - [Fact] + [Test] public void LatestSqlParserIsUsedByDefault() { // This should only parse correctly on SQL server 2016 or newer @@ -37,13 +37,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ScriptFileMarker[] fileMarkers = service.GetSemanticMarkers(scriptFile); // verify that no errors are detected - Assert.Equal(0, fileMarkers.Length); + Assert.AreEqual(0, fileMarkers.Length); } /// /// Verify that the SQL parser correctly detects errors in text /// - [Fact] + [Test] public void ParseSelectStatementWithoutErrors() { // sql statement with no errors @@ -58,13 +58,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ScriptFileMarker[] fileMarkers = service.GetSemanticMarkers(scriptFile); // verify there are no errors - Assert.Equal(0, fileMarkers.Length); + Assert.AreEqual(0, fileMarkers.Length); } /// /// Verify that the SQL parser correctly detects errors in text /// - [Fact] + [Test] public void ParseSelectStatementWithError() { // sql statement with errors @@ -79,19 +79,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ScriptFileMarker[] fileMarkers = service.GetSemanticMarkers(scriptFile); // verify there is one error - Assert.Equal(1, fileMarkers.Length); + Assert.AreEqual(1, fileMarkers.Length); // verify the position of the error - Assert.Equal(9, fileMarkers[0].ScriptRegion.StartColumnNumber); - Assert.Equal(1, fileMarkers[0].ScriptRegion.StartLineNumber); - Assert.Equal(10, fileMarkers[0].ScriptRegion.EndColumnNumber); - Assert.Equal(1, fileMarkers[0].ScriptRegion.EndLineNumber); + Assert.AreEqual(9, fileMarkers[0].ScriptRegion.StartColumnNumber); + Assert.AreEqual(1, fileMarkers[0].ScriptRegion.StartLineNumber); + Assert.AreEqual(10, fileMarkers[0].ScriptRegion.EndColumnNumber); + Assert.AreEqual(1, fileMarkers[0].ScriptRegion.EndLineNumber); } /// /// Verify that the SQL parser correctly detects errors in text /// - [Fact] + [Test] public void ParseMultilineSqlWithErrors() { // multiline sql with errors @@ -109,26 +109,26 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ScriptFileMarker[] fileMarkers = service.GetSemanticMarkers(scriptFile); // verify there are two errors - Assert.Equal(2, fileMarkers.Length); + Assert.AreEqual(2, fileMarkers.Length); // check position of first error - Assert.Equal(9, fileMarkers[0].ScriptRegion.StartColumnNumber); - Assert.Equal(1, fileMarkers[0].ScriptRegion.StartLineNumber); - Assert.Equal(10, fileMarkers[0].ScriptRegion.EndColumnNumber); - Assert.Equal(1, fileMarkers[0].ScriptRegion.EndLineNumber); + Assert.AreEqual(9, fileMarkers[0].ScriptRegion.StartColumnNumber); + Assert.AreEqual(1, fileMarkers[0].ScriptRegion.StartLineNumber); + Assert.AreEqual(10, fileMarkers[0].ScriptRegion.EndColumnNumber); + Assert.AreEqual(1, fileMarkers[0].ScriptRegion.EndLineNumber); // check position of second error - Assert.Equal(9, fileMarkers[1].ScriptRegion.StartColumnNumber); - Assert.Equal(3, fileMarkers[1].ScriptRegion.StartLineNumber); - Assert.Equal(10, fileMarkers[1].ScriptRegion.EndColumnNumber); - Assert.Equal(3, fileMarkers[1].ScriptRegion.EndLineNumber); + Assert.AreEqual(9, fileMarkers[1].ScriptRegion.StartColumnNumber); + Assert.AreEqual(3, fileMarkers[1].ScriptRegion.StartLineNumber); + Assert.AreEqual(10, fileMarkers[1].ScriptRegion.EndColumnNumber); + Assert.AreEqual(3, fileMarkers[1].ScriptRegion.EndLineNumber); } /// /// Verify that GetSignatureHelp returns null when the provided TextDocumentPosition /// has no associated ScriptParseInfo. /// - [Fact] + [Test] public void GetSignatureHelpReturnsNullIfParseInfoNotInitialized() { // Given service doesn't have parseinfo intialized for a document @@ -144,10 +144,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.Null(signatureHelp); } - [Fact] + [Test] public void EmptyCompletionListTest() { - Assert.Equal(AutoCompleteHelper.EmptyCompletionList.Length, 0); + Assert.AreEqual(0, AutoCompleteHelper.EmptyCompletionList.Length); } internal class TestScriptDocumentInfo : ScriptDocumentInfo @@ -170,7 +170,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer } } - [Fact] + [Test] public void GetDefaultCompletionListWithNoMatchesTest() { var scriptFile = new ScriptFile(); @@ -189,7 +189,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer } - [Fact] + [Test] public void GetDefaultCompletionListWithMatchesTest() { var scriptFile = new ScriptFile(); @@ -205,7 +205,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer }, scriptFile, scriptInfo, "all"); CompletionItem[] result = AutoCompleteHelper.GetDefaultCompletionItems(scriptDocumentInfo, false); - Assert.Equal(result.Length, 1); + Assert.AreEqual(1, result.Length); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/PeekDefinitionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/PeekDefinitionTests.cs index 6224cc8c..71ec55a8 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/PeekDefinitionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/PeekDefinitionTests.cs @@ -24,7 +24,7 @@ using Microsoft.SqlTools.ServiceLayer.Utility; using Microsoft.SqlTools.ServiceLayer.Workspace; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Moq; -using Xunit; +using NUnit.Framework; using GlobalCommon = Microsoft.SqlTools.ServiceLayer.Test.Common; using Location = Microsoft.SqlTools.ServiceLayer.Workspace.Contracts.Location; @@ -38,7 +38,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// /// Tests the definition event handler. When called with no active connection, an error is sent /// - [Fact] + [Test] public async Task DefinitionsHandlerWithNoConnectionTest() { InitializeTestObjects(); @@ -54,7 +54,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// /// Tests creating location objects on windows and non-windows systems /// - [Fact] + [Test] public void GetLocationFromFileForValidFilePathTest() { string filePath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "C:\\test\\script.sql" : "/test/script.sql"; @@ -62,13 +62,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Location[] locations = peekDefinition.GetLocationFromFile(filePath, 0); string expectedFilePath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "file:///C:/test/script.sql" : "file:/test/script.sql"; - Assert.Equal(locations[0].Uri, expectedFilePath); + Assert.AreEqual(locations[0].Uri, expectedFilePath); } /// /// Test PeekDefinition.GetSchemaFromDatabaseQualifiedName with a valid database name /// - [Fact] + [Test] public void GetSchemaFromDatabaseQualifiedNameWithValidNameTest() { Scripter peekDefinition = new Scripter(null, null); @@ -77,14 +77,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string expectedSchemaName = "test"; string actualSchemaName = peekDefinition.GetSchemaFromDatabaseQualifiedName(validDatabaseQualifiedName, objectName); - Assert.Equal(actualSchemaName, expectedSchemaName); + Assert.AreEqual(actualSchemaName, expectedSchemaName); } /// /// Test PeekDefinition.GetSchemaFromDatabaseQualifiedName with a valid object name and no schema /// - [Fact] + [Test] public void GetSchemaFromDatabaseQualifiedNameWithNoSchemaTest() { Scripter peekDefinition = new Scripter(null, null); @@ -93,13 +93,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string expectedSchemaName = "dbo"; string actualSchemaName = peekDefinition.GetSchemaFromDatabaseQualifiedName(validDatabaseQualifiedName, objectName); - Assert.Equal(actualSchemaName, expectedSchemaName); + Assert.AreEqual(actualSchemaName, expectedSchemaName); } /// /// Test PeekDefinition.GetSchemaFromDatabaseQualifiedName with a invalid database name /// - [Fact] + [Test] public void GetSchemaFromDatabaseQualifiedNameWithInvalidNameTest() { Scripter peekDefinition = new Scripter(null, null); @@ -108,13 +108,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string expectedSchemaName = "dbo"; string actualSchemaName = peekDefinition.GetSchemaFromDatabaseQualifiedName(validDatabaseQualifiedName, objectName); - Assert.Equal(actualSchemaName, expectedSchemaName); + Assert.AreEqual(actualSchemaName, expectedSchemaName); } /// /// Test deletion of peek definition scripts for a valid temp folder that exists /// - [Fact] + [Test] public void DeletePeekDefinitionScriptsTest() { Scripter peekDefinition = new Scripter(null, null); @@ -126,7 +126,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// /// Test deletion of peek definition scripts for a temp folder that does not exist /// - [Fact] + [Test] public void DeletePeekDefinitionScriptsWhenFolderDoesNotExistTest() { Scripter peekDefinition = new Scripter(null, null); @@ -141,7 +141,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Given a valid object name string and a vaild quickInfo string containing the object name /// Expect the full object name (database.schema.objectName) /// - [Fact] + [Test] public void GetFullObjectNameFromQuickInfoWithValidStringsTest() { Scripter peekDefinition = new Scripter(null, null); @@ -149,7 +149,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string quickInfoText = "table master.dbo.testTable"; string result = peekDefinition.GetFullObjectNameFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); string expected = "master.dbo.testTable"; - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); } /// @@ -157,7 +157,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Given a valid object name string and a vaild quickInfo string containing the object name /// Expect the full object name (database.schema.objectName) /// - [Fact] + [Test] public void GetFullObjectNameFromQuickInfoWithValidStringsandIgnoreCaseTest() { Scripter peekDefinition = new Scripter(null, null); @@ -165,7 +165,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string quickInfoText = "table master.dbo.testTable"; string result = peekDefinition.GetFullObjectNameFromQuickInfo(quickInfoText, objectName, StringComparison.OrdinalIgnoreCase); string expected = "master.dbo.testTable"; - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); } /// @@ -173,7 +173,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Given a null object name string and a vaild quickInfo string containing the object name( and vice versa) /// Expect null /// - [Fact] + [Test] public void GetFullObjectNameFromQuickInfoWithNullStringsTest() { Scripter peekDefinition = new Scripter(null, null); @@ -182,17 +182,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string objectName = null; string quickInfoText = "table master.dbo.testTable"; string result = peekDefinition.GetFullObjectNameFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); quickInfoText = null; objectName = "tableName"; result = peekDefinition.GetFullObjectNameFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); quickInfoText = null; objectName = null; result = peekDefinition.GetFullObjectNameFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); } /// @@ -200,7 +200,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Given a valid object name string and a vaild quickInfo string that does not contain the object name /// Expect null /// - [Fact] + [Test] public void GetFullObjectNameFromQuickInfoWithIncorrectObjectNameTest() { Scripter peekDefinition = new Scripter(null, null); @@ -208,7 +208,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string quickInfoText = "table master.dbo.tableName"; string result = peekDefinition.GetFullObjectNameFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); string expected = null; - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); } /// @@ -216,7 +216,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Given a valid object name string and a vaild quickInfo string containing the object name /// Expect correct object type /// - [Fact] + [Test] public void GetTokenTypeFromQuickInfoWithValidStringsTest() { Scripter peekDefinition = new Scripter(null, null); @@ -224,7 +224,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string quickInfoText = "table master.dbo.tableName"; string result = peekDefinition.GetTokenTypeFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); string expected = "table"; - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); } @@ -233,7 +233,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Given a valid object name string and a vaild quickInfo string containing the object name /// Expect correct object type /// - [Fact] + [Test] public void GetTokenTypeFromQuickInfoWithValidStringsandIgnoreCaseTest() { Scripter peekDefinition = new Scripter(null, null); @@ -241,7 +241,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string quickInfoText = "table master.dbo.tableName"; string result = peekDefinition.GetTokenTypeFromQuickInfo(quickInfoText, objectName, StringComparison.OrdinalIgnoreCase); string expected = "table"; - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); } /// @@ -249,7 +249,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Given a null object name string and a vaild quickInfo string containing the object name( and vice versa) /// Expect null /// - [Fact] + [Test] public void GetTokenTypeFromQuickInfoWithNullStringsTest() { Scripter peekDefinition = new Scripter(null, null); @@ -258,17 +258,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string objectName = null; string quickInfoText = "table master.dbo.testTable"; string result = peekDefinition.GetTokenTypeFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); quickInfoText = null; objectName = "tableName"; result = peekDefinition.GetTokenTypeFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); quickInfoText = null; objectName = null; result = peekDefinition.GetTokenTypeFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); } /// @@ -276,7 +276,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Given a valid object name string and a vaild quickInfo string that does not containthe object name /// Expect null /// - [Fact] + [Test] public void GetTokenTypeFromQuickInfoWithIncorrectObjectNameTest() { Scripter peekDefinition = new Scripter(null, null); @@ -284,14 +284,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer string quickInfoText = "table master.dbo.tableName"; string result = peekDefinition.GetTokenTypeFromQuickInfo(quickInfoText, objectName, StringComparison.Ordinal); string expected = null; - Assert.Equal(expected, result); + Assert.AreEqual(expected, result); } /// /// Test getting definition using quickInfo text without a live connection /// Expect an error result (because you cannot script without a live connection) /// - [Fact] + [Test] public void GetDefinitionUsingQuickInfoWithoutConnectionTest() { Scripter peekDefinition = new Scripter(null, null); @@ -306,7 +306,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer /// Test getting definition using declaration Type without a live connection /// Expect an error result (because you cannot script without a live connection) /// - [Fact] + [Test] public void GetDefinitionUsingDeclarationItemWithoutConnectionTest() { Scripter peekDefinition = new Scripter(null, null); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/SqlCompletionItemTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/SqlCompletionItemTests.cs index 6e90d43c..b40b8f27 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/SqlCompletionItemTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/LanguageServer/SqlCompletionItemTests.cs @@ -9,14 +9,14 @@ using Microsoft.SqlServer.Management.SqlParser.Intellisense; using Microsoft.SqlTools.ServiceLayer.LanguageServices; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion; using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer { public class SqlCompletionItemTests { - [Fact] + [Test] public void InsertTextShouldIncludeBracketGivenNameWithSpace() { string declarationTitle = "name with space"; @@ -30,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.True(completionItem.InsertText.StartsWith("[") && completionItem.InsertText.EndsWith("]")); } - [Fact] + [Test] public void ConstructorShouldThrowExceptionGivenEmptyDeclarionType() { string declarationTitle = ""; @@ -39,14 +39,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer Assert.Throws(() => new SqlCompletionItem(declarationTitle, declarationType, tokenText)); } - [Fact] + [Test] public void ConstructorShouldThrowExceptionGivenNullDeclarion() { string tokenText = ""; Assert.Throws(() => new SqlCompletionItem(null, tokenText)); } - [Fact] + [Test] public void InsertTextShouldIncludeBracketGivenNameWithSpecialCharacter() { string declarationTitle = "name @"; @@ -56,12 +56,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, declarationTitle); - Assert.Equal(completionItem.Label, declarationTitle); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, declarationTitle); + Assert.AreEqual(completionItem.Label, declarationTitle); } - [Fact] + [Test] public void LabelShouldIncludeBracketGivenTokenWithBracket() { string declarationTitle = "name"; @@ -71,12 +71,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Fact] + [Test] public void LabelShouldIncludeBracketGivenTokenWithBrackets() { string declarationTitle = "name"; @@ -86,12 +86,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Fact] + [Test] public void LabelShouldIncludeBracketGivenSqlObjectNameWithBracket() { string declarationTitle = @"Bracket\["; @@ -101,12 +101,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, declarationTitle); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, declarationTitle); + Assert.AreEqual(completionItem.Label, declarationTitle); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, declarationTitle); } - [Fact] + [Test] public void LabelShouldIncludeBracketGivenSqlObjectNameWithBracketAndTokenWithBracket() { string declarationTitle = @"Bracket\["; @@ -116,12 +116,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Fact] + [Test] public void LabelShouldNotIncludeBracketGivenNameWithBrackets() { string declarationTitle = "[name]"; @@ -131,12 +131,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Fact] + [Test] public void LabelShouldIncludeBracketGivenNameWithOneBracket() { string declarationTitle = "[name"; @@ -146,12 +146,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Fact] + [Test] public void LabelShouldIncludeQuotedIdentifiersGivenTokenWithQuotedIdentifier() { string declarationTitle = "name"; @@ -161,12 +161,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Fact] + [Test] public void LabelShouldIncludeQuotedIdentifiersGivenTokenWithQuotedIdentifiers() { string declarationTitle = "name"; @@ -176,12 +176,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Fact] + [Test] public void InsertTextShouldNotIncludeBracketGivenReservedName() { foreach (string word in AutoCompleteHelper.DefaultCompletionText) @@ -192,13 +192,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, word); - Assert.Equal(completionItem.InsertText, word); - Assert.Equal(completionItem.Detail, word); + Assert.AreEqual(completionItem.Label, word); + Assert.AreEqual(completionItem.InsertText, word); + Assert.AreEqual(completionItem.Detail, word); } } - [Fact] + [Test] public void LabelShouldNotIncludeBracketIfTokenIncludesQuotedIdentifiersGivenReservedName() { string declarationTitle = "User"; @@ -208,12 +208,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Fact] + [Test] public void LabelShouldNotIncludeDoubleBracketIfTokenIncludesBracketsGivenReservedName() { string declarationTitle = "User"; @@ -223,12 +223,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Fact] + [Test] public void TempTablesShouldNotBeEscaped() { string declarationTitle = "#TestTable"; @@ -238,16 +238,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Label, expected); - Assert.Equal(completionItem.InsertText, expected); - Assert.Equal(completionItem.Detail, expected); + Assert.AreEqual(completionItem.Label, expected); + Assert.AreEqual(completionItem.InsertText, expected); + Assert.AreEqual(completionItem.Detail, expected); } - [Theory] - [InlineData(DeclarationType.BuiltInFunction)] - [InlineData(DeclarationType.ScalarValuedFunction)] - [InlineData(DeclarationType.TableValuedFunction)] - public void FunctionsShouldHaveParenthesesAdded(DeclarationType declarationType) + [Test] + public void FunctionsShouldHaveParenthesesAdded([Values(DeclarationType.BuiltInFunction, DeclarationType.ScalarValuedFunction, DeclarationType.TableValuedFunction)] DeclarationType declarationType) { foreach (string word in AutoCompleteHelper.DefaultCompletionText) { @@ -256,14 +253,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(declarationTitle, completionItem.Label); - Assert.Equal($"{declarationTitle}()", completionItem.InsertText); - Assert.Equal(declarationTitle, completionItem.Detail); + Assert.AreEqual(declarationTitle, completionItem.Label); + Assert.AreEqual($"{declarationTitle}()", completionItem.InsertText); + Assert.AreEqual(declarationTitle, completionItem.Detail); } } - [Fact] + [Test] public void GlobalVariableSystemFunctionsShouldNotHaveParenthesesAdded() { string declarationTitle = "@@CONNECTIONS"; @@ -271,20 +268,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, DeclarationType.BuiltInFunction, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(declarationTitle, completionItem.Label); - Assert.Equal($"{declarationTitle}", completionItem.InsertText); - Assert.Equal(declarationTitle, completionItem.Detail); + Assert.AreEqual(declarationTitle, completionItem.Label); + Assert.AreEqual($"{declarationTitle}", completionItem.InsertText); + Assert.AreEqual(declarationTitle, completionItem.Detail); } - [Theory] - [InlineData(DeclarationType.Server)] - [InlineData(DeclarationType.Database)] - [InlineData(DeclarationType.Table)] - [InlineData(DeclarationType.Column)] - [InlineData(DeclarationType.View)] - [InlineData(DeclarationType.Schema)] - public void NamedIdentifiersShouldBeBracketQuoted(DeclarationType declarationType) + [Test] + public void NamedIdentifiersShouldBeBracketQuoted( + [Values(DeclarationType.Server, DeclarationType.Database, DeclarationType.Table, DeclarationType.Column, DeclarationType.View, DeclarationType.Schema)] DeclarationType declarationType) { string declarationTitle = declarationType.ToString(); // All words - both reserved and not - should be bracket quoted for these types @@ -294,13 +286,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer SqlCompletionItem item = new SqlCompletionItem(declarationTitle, declarationType, tokenText); CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(declarationTitle, completionItem.Label); - Assert.Equal($"[{declarationTitle}]", completionItem.InsertText); - Assert.Equal(declarationTitle, completionItem.Detail); + Assert.AreEqual(declarationTitle, completionItem.Label); + Assert.AreEqual($"[{declarationTitle}]", completionItem.InsertText); + Assert.AreEqual(declarationTitle, completionItem.Detail); } } - [Fact] + [Test] public void KindShouldBeModuleGivenSchemaDeclarationType() { CompletionItemKind expectedType = CompletionItemKind.Module; @@ -308,7 +300,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ValidateDeclarationType(declarationType, expectedType); } - [Fact] + [Test] public void KindShouldBeFieldGivenColumnDeclarationType() { CompletionItemKind expectedType = CompletionItemKind.Field; @@ -316,7 +308,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ValidateDeclarationType(declarationType, expectedType); } - [Fact] + [Test] public void KindShouldBeFileGivenTableDeclarationType() { CompletionItemKind expectedType = CompletionItemKind.File; @@ -324,7 +316,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ValidateDeclarationType(declarationType, expectedType); } - [Fact] + [Test] public void KindShouldBeFileGivenViewDeclarationType() { CompletionItemKind expectedType = CompletionItemKind.File; @@ -332,7 +324,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ValidateDeclarationType(declarationType, expectedType); } - [Fact] + [Test] public void KindShouldBeMethodGivenDatabaseDeclarationType() { CompletionItemKind expectedType = CompletionItemKind.Method; @@ -340,7 +332,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ValidateDeclarationType(declarationType, expectedType); } - [Fact] + [Test] public void KindShouldBeValueGivenScalarValuedFunctionDeclarationType() { CompletionItemKind expectedType = CompletionItemKind.Value; @@ -348,7 +340,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ValidateDeclarationType(declarationType, expectedType); } - [Fact] + [Test] public void KindShouldBeValueGivenTableValuedFunctionDeclarationType() { CompletionItemKind expectedType = CompletionItemKind.Value; @@ -356,7 +348,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer ValidateDeclarationType(declarationType, expectedType); } - [Fact] + [Test] public void KindShouldBeUnitGivenUnknownDeclarationType() { CompletionItemKind expectedType = CompletionItemKind.Unit; @@ -372,7 +364,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer CompletionItem completionItem = item.CreateCompletionItem(0, 1, 2); - Assert.Equal(completionItem.Kind, expectedType); + Assert.AreEqual(completionItem.Kind, expectedType); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageDispatcherTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageDispatcherTests.cs index c82aad74..bb748bf9 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageDispatcherTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageDispatcherTests.cs @@ -9,13 +9,13 @@ using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol.Channel; using Microsoft.SqlTools.Hosting.Protocol.Contracts; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging { public class MessageDispatcherTests { - [Fact] + [Test] public void SetRequestHandlerWithOverrideTest() { RequestType requestType = RequestType.Create("test/requestType"); @@ -30,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging Assert.True(dispatcher.requestHandlers.Count > 0); } - [Fact] + [Test] public void SetEventHandlerTest() { EventType eventType = EventType.Create("test/eventType"); @@ -44,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging Assert.True(dispatcher.eventHandlers.Count > 0); } - [Fact] + [Test] public void SetEventHandlerWithOverrideTest() { EventType eventType = EventType.Create("test/eventType"); @@ -59,7 +59,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging Assert.True(dispatcher.eventHandlers.Count > 0); } - [Fact] + [Test] public void OnListenTaskCompletedFaultedTaskTest() { Task t = null; diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageReaderTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageReaderTests.cs index 2fa31cfd..9c5fe71a 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageReaderTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageReaderTests.cs @@ -10,7 +10,7 @@ using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol.Contracts; using Microsoft.SqlTools.Hosting.Protocol.Serializers; using Newtonsoft.Json; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging { @@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging this.messageSerializer = new V8MessageSerializer(); } - [Fact] + [Test] public void ReadsMessage() { MemoryStream inputStream = new MemoryStream(); @@ -38,12 +38,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging inputStream.Seek(0, SeekOrigin.Begin); Message messageResult = messageReader.ReadMessage().Result; - Assert.Equal("testEvent", messageResult.Method); + Assert.AreEqual("testEvent", messageResult.Method); inputStream.Dispose(); } - [Fact] + [Test] public void ReadsManyBufferedMessages() { MemoryStream inputStream = new MemoryStream(); @@ -73,13 +73,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging for (int i = 0; i < overflowMessageCount; i++) { Message messageResult = messageReader.ReadMessage().Result; - Assert.Equal("testEvent", messageResult.Method); + Assert.AreEqual("testEvent", messageResult.Method); } inputStream.Dispose(); } - [Fact] + [Test] public void ReadMalformedMissingHeaderTest() { using (MemoryStream inputStream = new MemoryStream()) @@ -93,13 +93,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging inputStream.Flush(); inputStream.Seek(0, SeekOrigin.Begin); - // Then: - // ... An exception should be thrown while reading - Assert.ThrowsAsync(() => messageReader.ReadMessage()).Wait(); + Assert.ThrowsAsync(() => messageReader.ReadMessage(), "An exception should be thrown while reading"); } } - [Fact] + [Test] public void ReadMalformedContentLengthNonIntegerTest() { using (MemoryStream inputStream = new MemoryStream()) @@ -113,13 +111,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging inputStream.Flush(); inputStream.Seek(0, SeekOrigin.Begin); - // Then: - // ... An exception should be thrown while reading - Assert.ThrowsAsync(() => messageReader.ReadMessage()).Wait(); + Assert.ThrowsAsync(() => messageReader.ReadMessage(), "An exception should be thrown while reading") ; } } - [Fact] + [Test] public void ReadMissingContentLengthHeaderTest() { using (MemoryStream inputStream = new MemoryStream()) @@ -133,13 +129,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging inputStream.Flush(); inputStream.Seek(0, SeekOrigin.Begin); - // Then: - // ... An exception should be thrown while reading - Assert.ThrowsAsync(() => messageReader.ReadMessage()).Wait(); + Assert.ThrowsAsync(() => messageReader.ReadMessage(), "An exception should be thrown while reading"); } } - [Fact] + [Test] public void ReadMalformedContentLengthTooShortTest() { using (MemoryStream inputStream = new MemoryStream()) @@ -157,16 +151,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging inputStream.Flush(); inputStream.Seek(0, SeekOrigin.Begin); - // Then: - // ... The first read should fail with an exception while deserializing - Assert.ThrowsAsync(() => messageReader.ReadMessage()).Wait(); + Assert.ThrowsAsync(() => messageReader.ReadMessage(), "The first read should fail with an exception while deserializing"); - // ... The second read should fail with an exception while reading headers - Assert.ThrowsAsync(() => messageReader.ReadMessage()).Wait(); + Assert.ThrowsAsync(() => messageReader.ReadMessage(), "The second read should fail with an exception while reading headers"); } } - [Fact] + [Test] public void ReadMalformedThenValidTest() { // If: @@ -183,18 +174,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging inputStream.Flush(); inputStream.Seek(0, SeekOrigin.Begin); - // Then: - // ... An exception should be thrown while reading the first one - Assert.ThrowsAsync(() => messageReader.ReadMessage()).Wait(); + Assert.ThrowsAsync(() => messageReader.ReadMessage(), "An exception should be thrown while reading the first one"); // ... A test event should be successfully read from the second one Message messageResult = messageReader.ReadMessage().Result; Assert.NotNull(messageResult); - Assert.Equal("testEvent", messageResult.Method); + Assert.AreEqual("testEvent", messageResult.Method); } } - [Fact] + [Test] public void ReaderResizesBufferForLargeMessages() { MemoryStream inputStream = new MemoryStream(); @@ -215,12 +204,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging inputStream.Seek(0, SeekOrigin.Begin); Message messageResult = messageReader.ReadMessage().Result; - Assert.Equal("testEvent", messageResult.Method); + Assert.AreEqual("testEvent", messageResult.Method); inputStream.Dispose(); } - [Fact] + [Test] public void ReaderDoesNotModifyDateStrings() { MemoryStream inputStream = new MemoryStream(); @@ -240,7 +229,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging inputStream.Seek(0, SeekOrigin.Begin); Message messageResult = messageReader.ReadMessage().Result; - Assert.Equal(dateString, messageResult.Contents.Value("someString")); + Assert.AreEqual(dateString, messageResult.Contents.Value("someString")); inputStream.Dispose(); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageWriterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageWriterTests.cs index ad5d7fad..0e5739dd 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageWriterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Messaging/MessageWriterTests.cs @@ -10,7 +10,7 @@ using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.Hosting.Protocol.Contracts; using Microsoft.SqlTools.Hosting.Protocol.Serializers; using Newtonsoft.Json.Linq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging { @@ -23,7 +23,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging this.messageSerializer = new V8MessageSerializer(); } - [Fact] + [Test] public void SerializeMessageTest() { // serialize\deserialize a request @@ -35,29 +35,29 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging var serializedMessage = this.messageSerializer.SerializeMessage(message); Assert.NotNull(serializedMessage); var deserializedMessage = this.messageSerializer.DeserializeMessage(serializedMessage); - Assert.Equal(message.Id, deserializedMessage.Id); + Assert.AreEqual(message.Id, deserializedMessage.Id); // serialize\deserialize a response message.MessageType = MessageType.Response; serializedMessage = this.messageSerializer.SerializeMessage(message); Assert.NotNull(serializedMessage); deserializedMessage = this.messageSerializer.DeserializeMessage(serializedMessage); - Assert.Equal(message.Id, deserializedMessage.Id); + Assert.AreEqual(message.Id, deserializedMessage.Id); // serialize\deserialize a response with an error message.Error = JToken.FromObject("error"); serializedMessage = this.messageSerializer.SerializeMessage(message); Assert.NotNull(serializedMessage); deserializedMessage = this.messageSerializer.DeserializeMessage(serializedMessage); - Assert.Equal(message.Error, deserializedMessage.Error); + Assert.AreEqual(message.Error, deserializedMessage.Error); // serialize\deserialize an unknown response type serializedMessage.Remove("type"); serializedMessage.Add("type", JToken.FromObject("dontknowthisone")); - Assert.Equal(this.messageSerializer.DeserializeMessage(serializedMessage).MessageType, MessageType.Unknown); + Assert.AreEqual(MessageType.Unknown, this.messageSerializer.DeserializeMessage(serializedMessage).MessageType); } - [Fact] + [Test] public async Task WritesMessage() { MemoryStream outputStream = new MemoryStream(); @@ -74,14 +74,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging byte[] buffer = new byte[128]; await outputStream.ReadAsync(buffer, 0, expectedHeaderString.Length); - Assert.Equal( + Assert.AreEqual( expectedHeaderString, Encoding.ASCII.GetString(buffer, 0, expectedHeaderString.Length)); // Read the message await outputStream.ReadAsync(buffer, 0, Common.ExpectedMessageByteCount); - Assert.Equal(Common.TestEventString, + Assert.AreEqual(Common.TestEventString, Encoding.UTF8.GetString(buffer, 0, Common.ExpectedMessageByteCount)); outputStream.Dispose(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Microsoft.SqlTools.ServiceLayer.UnitTests.csproj b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Microsoft.SqlTools.ServiceLayer.UnitTests.csproj index 9ce5eab2..46ba3d63 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Microsoft.SqlTools.ServiceLayer.UnitTests.csproj +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Microsoft.SqlTools.ServiceLayer.UnitTests.csproj @@ -12,9 +12,9 @@ - - - + + + diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/NodePathGeneratorTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/NodePathGeneratorTests.cs index 48ae58e7..6fc42581 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/NodePathGeneratorTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/NodePathGeneratorTests.cs @@ -17,7 +17,7 @@ using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes; using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.SmoModel; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; -using Xunit; +using NUnit.Framework; using Microsoft.SqlTools.ServiceLayer.LanguageServices; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; @@ -52,7 +52,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer databaseSession = new ObjectExplorerService.ObjectExplorerSession("databaseUri", databaseRoot, null, null); } - [Fact] + [Test] public void FindCorrectPathsForTableWithServerRoot() { var paths = NodePathGenerator.FindNodePaths(serverSession, "Table", "testSchema", "testTable", databaseName); @@ -64,14 +64,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer "testServer/Databases/System Databases/testDatabase/Tables/System Tables/testSchema.testTable" }; - Assert.Equal(expectedPaths.Count, paths.Count); + Assert.AreEqual(expectedPaths.Count, paths.Count); foreach (var expectedPath in expectedPaths) { Assert.True(paths.Contains(expectedPath)); } } - [Fact] + [Test] public void FindCorrectPathsForTableWithDatabaseRoot() { var paths = NodePathGenerator.FindNodePaths(databaseSession, "Table", "testSchema", "testTable", null); @@ -81,14 +81,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer "testServer/testDatabase/Tables/System Tables/testSchema.testTable" }; - Assert.Equal(expectedPaths.Count, paths.Count); + Assert.AreEqual(expectedPaths.Count, paths.Count); foreach (var expectedPath in expectedPaths) { Assert.True(paths.Contains(expectedPath)); } } - [Fact] + [Test] public void FindCorrectPathsForColumnWithServerRoot() { var paths = NodePathGenerator.FindNodePaths(serverSession, "Column", null, "testColumn", databaseName, new List { "testSchema.testTable" }); @@ -104,14 +104,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer "testServer/Databases/System Databases/testDatabase/Views/System Views/testSchema.testTable/Columns/testColumn" }; - Assert.Equal(expectedPaths.Count, paths.Count); + Assert.AreEqual(expectedPaths.Count, paths.Count); foreach (var expectedPath in expectedPaths) { Assert.True(paths.Contains(expectedPath)); } } - [Fact] + [Test] public void FindCorrectPathsForColumnWithDatabaseRoot() { var paths = NodePathGenerator.FindNodePaths(databaseSession, "Column", null, "testColumn", databaseName, new List { "testSchema.testTable" }); @@ -123,14 +123,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer "testServer/testDatabase/Views/System Views/testSchema.testTable/Columns/testColumn" }; - Assert.Equal(expectedPaths.Count, paths.Count); + Assert.AreEqual(expectedPaths.Count, paths.Count); foreach (var expectedPath in expectedPaths) { Assert.True(paths.Contains(expectedPath)); } } - [Fact] + [Test] public void FindCorrectPathsForDatabase() { var paths = NodePathGenerator.FindNodePaths(serverSession, "Database", null, databaseName, null); @@ -140,25 +140,25 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer "testServer/Databases/System Databases/testDatabase" }; - Assert.Equal(expectedPaths.Count, paths.Count); + Assert.AreEqual(expectedPaths.Count, paths.Count); foreach (var expectedPath in expectedPaths) { Assert.True(paths.Contains(expectedPath)); } } - [Fact] + [Test] public void FindPathForInvalidTypeReturnsEmpty() { var serverPaths = NodePathGenerator.FindNodePaths(serverSession, "WrongType", "testSchema", "testTable", databaseName); - Assert.Equal(0, serverPaths.Count); + Assert.AreEqual(0, serverPaths.Count); } - [Fact] + [Test] public void FindPathMissingParentReturnsEmpty() { var serverPaths = NodePathGenerator.FindNodePaths(serverSession, "Column", "testSchema", "testColumn", databaseName); - Assert.Equal(0, serverPaths.Count); + Assert.AreEqual(0, serverPaths.Count); } } } \ No newline at end of file diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/NodeTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/NodeTests.cs index d382eb79..896e3324 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/NodeTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/NodeTests.cs @@ -18,7 +18,7 @@ using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes; using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.SmoModel; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; -using Xunit; +using NUnit.Framework; using Microsoft.SqlTools.ServiceLayer.Connection; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer @@ -35,7 +35,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer private string fakeConnectionString = "Data Source=server;Initial Catalog=database;Integrated Security=False;User Id=user"; private ServerConnection serverConnection = null; - public NodeTests() + [SetUp] + public void InitNodeTests() { defaultServerInfo = TestObjects.GetTestServerInfo(); serverConnection = new ServerConnection(new SqlConnection(fakeConnectionString)); @@ -58,33 +59,33 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer ServiceProvider = ExtensionServiceProvider.CreateDefaultServiceProvider(); } - [Fact] + [Test] public void ServerNodeConstructorValidatesFields() { Assert.Throws(() => new ServerNode(null, ServiceProvider, serverConnection)); Assert.Throws(() => new ServerNode(defaultConnParams, null, serverConnection)); } - [Fact] + [Test] public void ServerNodeConstructorShouldSetValuesCorrectly() { // Given a server node with valid inputs ServerNode node = new ServerNode(defaultConnParams, ServiceProvider, serverConnection); // Then expect all fields set correctly Assert.False(node.IsAlwaysLeaf, "Server node should never be a leaf"); - Assert.Equal(defaultConnectionDetails.ServerName, node.NodeValue); + Assert.AreEqual(defaultConnectionDetails.ServerName, node.NodeValue); string expectedLabel = defaultConnectionDetails.ServerName + " (SQL Server " + defaultServerInfo.ServerVersion + " - " + defaultConnectionDetails.UserName + ")"; - Assert.Equal(expectedLabel, node.Label); + Assert.AreEqual(expectedLabel, node.Label); - Assert.Equal(NodeTypes.Server.ToString(), node.NodeType); + Assert.AreEqual(NodeTypes.Server.ToString(), node.NodeType); string[] nodePath = node.GetNodePath().Split(TreeNode.PathPartSeperator); - Assert.Equal(1, nodePath.Length); - Assert.Equal(defaultConnectionDetails.ServerName, nodePath[0]); + Assert.AreEqual(1, nodePath.Length); + Assert.AreEqual(defaultConnectionDetails.ServerName, nodePath[0]); } - [Fact] + [Test] public void ServerNodeLabelShouldIgnoreUserNameIfEmptyOrNull() { // Given no username set @@ -104,10 +105,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer string label = new ServerNode(connParams, ServiceProvider, serverConnection).Label; // Then only server name and version shown string expectedLabel = defaultConnectionDetails.ServerName + " (SQL Server " + defaultServerInfo.ServerVersion + ")"; - Assert.Equal(expectedLabel, label); + Assert.AreEqual(expectedLabel, label); } - [Fact] + [Test] public void ServerNodeConstructorShouldShowDbNameForCloud() { defaultServerInfo.IsCloud = true; @@ -117,7 +118,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer // Then expect label to not include db name string expectedLabel = defaultConnectionDetails.ServerName + " (SQL Server " + defaultServerInfo.ServerVersion + " - " + defaultConnectionDetails.UserName + ")"; - Assert.Equal(expectedLabel, node.Label); + Assert.AreEqual(expectedLabel, node.Label); // But given a server node for a cloud DB that's not master defaultConnectionDetails.DatabaseName = "NotMaster"; @@ -127,10 +128,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer // Then expect label to include db name expectedLabel = defaultConnectionDetails.ServerName + " (SQL Server " + defaultServerInfo.ServerVersion + " - " + defaultConnectionDetails.UserName + ", " + defaultConnectionDetails.DatabaseName + ")"; - Assert.Equal(expectedLabel, node.Label); + Assert.AreEqual(expectedLabel, node.Label); } - [Fact] + [Test] public void ToNodeInfoIncludeAllFields() { // Given a server connection @@ -138,29 +139,29 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer // When converting to NodeInfo NodeInfo info = node.ToNodeInfo(); // Then all fields should match - Assert.Equal(node.IsAlwaysLeaf, info.IsLeaf); - Assert.Equal(node.Label, info.Label); - Assert.Equal(node.NodeType, info.NodeType); + Assert.AreEqual(node.IsAlwaysLeaf, info.IsLeaf); + Assert.AreEqual(node.Label, info.Label); + Assert.AreEqual(node.NodeType, info.NodeType); string[] nodePath = node.GetNodePath().Split(TreeNode.PathPartSeperator); string[] nodeInfoPathParts = info.NodePath.Split(TreeNode.PathPartSeperator); - Assert.Equal(nodePath.Length, nodeInfoPathParts.Length); + Assert.AreEqual(nodePath.Length, nodeInfoPathParts.Length); for (int i = 0; i < nodePath.Length; i++) { - Assert.Equal(nodePath[i], nodeInfoPathParts[i]); + Assert.AreEqual(nodePath[i], nodeInfoPathParts[i]); } } - [Fact] + [Test] public void AddChildShouldSetParent() { TreeNode parent = new TreeNode("parent"); TreeNode child = new TreeNode("child"); Assert.Null(child.Parent); parent.AddChild(child); - Assert.Equal(parent, child.Parent); + Assert.AreEqual(parent, child.Parent); } - [Fact] + [Test] public void GetChildrenShouldReturnReadonlyList() { TreeNode node = new TreeNode("parent"); @@ -168,7 +169,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer Assert.Throws(() => children.Add(new TreeNode("child"))); } - [Fact] + [Test] public void GetChildrenShouldReturnAddedNodesInOrder() { TreeNode parent = new TreeNode("parent"); @@ -178,33 +179,33 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer parent.AddChild(child); } IList children = parent.GetChildren(); - Assert.Equal(expectedKids.Length, children.Count); + Assert.AreEqual(expectedKids.Length, children.Count); for (int i = 0; i < expectedKids.Length; i++) { - Assert.Equal(expectedKids[i], children[i]); + Assert.AreEqual(expectedKids[i], children[i]); } } - [Fact] + [Test] public void MultiLevelTreeShouldFormatPath() { TreeNode root = new TreeNode("root"); - Assert.Equal("root" , root.GetNodePath()); + Assert.AreEqual("root" , root.GetNodePath()); TreeNode level1Child1 = new TreeNode("L1C1 (with extra info)"); level1Child1.NodePathName = "L1C1"; TreeNode level1Child2 = new TreeNode("L1C2"); root.AddChild(level1Child1); root.AddChild(level1Child2); - Assert.Equal("root/L1C1" , level1Child1.GetNodePath()); - Assert.Equal("root/L1C2", level1Child2.GetNodePath()); + Assert.AreEqual("root/L1C1" , level1Child1.GetNodePath()); + Assert.AreEqual("root/L1C2", level1Child2.GetNodePath()); TreeNode level2Child1 = new TreeNode("L2C2"); level1Child1.AddChild(level2Child1); - Assert.Equal("root/L1C1/L2C2", level2Child1.GetNodePath()); + Assert.AreEqual("root/L1C1/L2C2", level2Child1.GetNodePath()); } - [Fact] + [Test] public void ServerNodeContextShouldIncludeServer() { // given a successful Server creation @@ -216,13 +217,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer // Then I expect it to contain the server I created Assert.NotNull(context); - Assert.Equal(smoServer, context.Server); + Assert.AreEqual(smoServer, context.Server); // And the server should be the parent - Assert.Equal(smoServer, context.Parent); + Assert.AreEqual(smoServer, context.Parent); Assert.Null(context.Database); } - [Fact] + [Test] public void ServerNodeContextShouldSetErrorMessageIfSqlConnectionIsNull() { // given a connectionInfo with no SqlConnection to use for queries @@ -237,7 +238,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer Assert.Null(context); } - [Fact] + [Test] public void ServerNodeContextShouldSetErrorMessageIfConnFailureExceptionThrown() { // given a connectionInfo with no SqlConnection to use for queries @@ -250,12 +251,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer // Then I expect it to be in an error state Assert.Null(context); - Assert.Equal( + Assert.AreEqual( string.Format(CultureInfo.CurrentCulture, SR.TreeNodeError, expectedMsg), node.ErrorStateMessage); } - [Fact] + [Test] public void ServerNodeContextShouldSetErrorMessageIfExceptionThrown() { // given a connectionInfo with no SqlConnection to use for queries @@ -268,12 +269,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer // Then I expect it to be in an error state Assert.Null(context); - Assert.Equal( + Assert.AreEqual( string.Format(CultureInfo.CurrentCulture, SR.TreeNodeError, expectedMsg), node.ErrorStateMessage); } - [Fact] + [Test] public void QueryContextShouldNotCallOpenOnAlreadyOpenConnection() { // given a server connection that will state its connection is open @@ -304,7 +305,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer return wrapper; } - [Fact] + [Test] public void QueryContextShouldReopenClosedConnectionWhenGettingServer() { // given a server connection that will state its connection is closed @@ -321,7 +322,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer wrapper.Verify(c => c.OpenConnection(It.IsAny()), Times.Once); } - [Fact] + [Test] public void QueryContextShouldReopenClosedConnectionWhenGettingParent() { // given a server connection that will state its connection is closed @@ -380,7 +381,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer return node; } - [Fact] + [Test] public void ServerNodeChildrenShouldIncludeFoldersAndDatabases() { // Given a server with 1 database @@ -404,19 +405,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer IList children = node.Expand(new CancellationToken()); // Then I expect it to contain server-level folders - Assert.Equal(3, children.Count); + Assert.AreEqual(3, children.Count); VerifyTreeNode(children[0], "Folder", SR.SchemaHierarchy_Databases); VerifyTreeNode(children[1], "Folder", SR.SchemaHierarchy_Security); VerifyTreeNode(children[2], "Folder", SR.SchemaHierarchy_ServerObjects); // And the database is contained under it TreeNode databases = children[0]; IList dbChildren = databases.Expand(new CancellationToken()); - Assert.Equal(2, dbChildren.Count); - Assert.Equal(SR.SchemaHierarchy_SystemDatabases, dbChildren[0].NodeValue); + Assert.AreEqual(2, dbChildren.Count); + Assert.AreEqual(SR.SchemaHierarchy_SystemDatabases, dbChildren[0].NodeValue); TreeNode dbNode = dbChildren[1]; - Assert.Equal(dbName, dbNode.NodeValue); - Assert.Equal(dbName, dbNode.Label); + Assert.AreEqual(dbName, dbNode.NodeValue); + Assert.AreEqual(dbName, dbNode.Label); Assert.False(dbNode.IsAlwaysLeaf); // Note: would like to verify Database in the context, but cannot since it's a Sealed class and isn't easily mockable @@ -427,8 +428,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer { T nodeAsT = node as T; Assert.NotNull(nodeAsT); - Assert.Equal(nodeType, nodeAsT.NodeType); - Assert.Equal(folderValue, nodeAsT.NodeValue); + Assert.AreEqual(nodeType, nodeAsT.NodeType); + Assert.AreEqual(folderValue, nodeAsT.NodeValue); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/ObjectExplorerServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/ObjectExplorerServiceTests.cs index ea9f3853..1a6a246d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/ObjectExplorerServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/ObjectExplorerServiceTests.cs @@ -17,7 +17,7 @@ using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; using Moq.Protected; -using Xunit; +using NUnit.Framework; using Microsoft.SqlTools.ServiceLayer.LanguageServices; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; @@ -42,7 +42,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer ConnectedBindingQueue connectedBindingQueue; Mock mockConnectionOpener; - public ObjectExplorerServiceTests() + + [SetUp] + public void InitObjectExplorerServiceTests() { connectionServiceMock = new Mock(); serviceHostMock = new Mock(); @@ -59,7 +61,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer service.ConnectedBindingQueue = connectedBindingQueue; } - [Fact] + [Test] public async Task CreateSessionRequestErrorsIfConnectionDetailsIsNull() { object errorResponse = null; @@ -71,7 +73,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer Assert.True(((string)errorResponse).Contains("ArgumentNullException")); } - [Fact] + [Test] public async Task CreateSessionRequestReturnsFalseOnConnectionFailure() { // Given the connection service fails to connect @@ -97,7 +99,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer } - [Fact] + [Test] public async Task CreateSessionRequestWithMasterConnectionReturnsServerSuccessAndNodeInfo() { // Given the connection service fails to connect @@ -111,7 +113,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer await CreateSessionRequestAndVerifyServerNodeHelper(details); } - [Fact] + [Test] public async Task CreateSessionRequestWithEmptyConnectionReturnsServerSuccessAndNodeInfo() { // Given the connection service fails to connect @@ -125,7 +127,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer await CreateSessionRequestAndVerifyServerNodeHelper(details); } - [Fact] + [Test] public async Task CreateSessionRequestWithMsdbConnectionReturnsServerSuccessAndNodeInfo() { // Given the connection service fails to connect @@ -139,7 +141,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer await CreateSessionRequestAndVerifyServerNodeHelper(details); } - [Fact] + [Test] public async Task CreateSessionRequestWithDefaultConnectionReturnsServerSuccessAndNodeInfo() { // Given the connection service fails to connect @@ -154,19 +156,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer await CreateSessionRequestAndVerifyServerNodeHelper(details); } - [Fact] + [Test] public async Task ExpandNodeGivenValidSessionShouldReturnTheNodeChildren() { await ExpandAndVerifyServerNodes(); } - [Fact] + [Test] public async Task RefreshNodeGivenValidSessionShouldReturnTheNodeChildren() { await RefreshAndVerifyServerNodes(); } - [Fact] + [Test] public async Task ExpandNodeGivenInvalidSessionShouldReturnEmptyList() { ExpandParams expandParams = new ExpandParams() @@ -182,12 +184,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer test: (requestContext) => CallServiceExpand(expandParams, requestContext), verify: (actual => { - Assert.Equal(actual.SessionId, expandParams.SessionId); + Assert.AreEqual(actual.SessionId, expandParams.SessionId); Assert.Null(actual.Nodes); })); } - [Fact] + [Test] public async Task RefreshNodeGivenInvalidSessionShouldReturnEmptyList() { RefreshParams expandParams = new RefreshParams() @@ -202,12 +204,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer test: (requestContext) => CallServiceRefresh(expandParams, requestContext), verify: (actual => { - Assert.Equal(actual.SessionId, expandParams.SessionId); + Assert.AreEqual(actual.SessionId, expandParams.SessionId); Assert.Null(actual.Nodes); })); } - [Fact] + [Test] public async Task RefreshNodeGivenNullSessionShouldReturnEmptyList() { RefreshParams expandParams = new RefreshParams() @@ -222,12 +224,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer test: (requestContext) => CallServiceRefresh(expandParams, requestContext), verify: (actual => { - Assert.Equal(actual.SessionId, expandParams.SessionId); + Assert.AreEqual(actual.SessionId, expandParams.SessionId); Assert.Null(actual.Nodes); })); } - [Fact] + [Test] public async Task CloseSessionGivenInvalidSessionShouldReturnEmptyList() { CloseSessionParams closeSessionParamsparams = new CloseSessionParams() @@ -241,12 +243,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer test: (requestContext) => CallCloseSession(closeSessionParamsparams, requestContext), verify: (actual => { - Assert.Equal(actual.SessionId, closeSessionParamsparams.SessionId); + Assert.AreEqual(actual.SessionId, closeSessionParamsparams.SessionId); Assert.False(actual.Success); })); } - [Fact] + [Test] public async Task CloseSessionGivenValidSessionShouldCloseTheSessionAndDisconnect() { var session = await CreateSession(); @@ -261,7 +263,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer test: (requestContext) => CallCloseSession(closeSessionParamsparams, requestContext), verify: (actual => { - Assert.Equal(actual.SessionId, closeSessionParamsparams.SessionId); + Assert.AreEqual(actual.SessionId, closeSessionParamsparams.SessionId); Assert.True(actual.Success); Assert.False(service.SessionIds.Contains(session.SessionId)); })); @@ -269,27 +271,27 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer connectionServiceMock.Verify(c => c.Disconnect(It.IsAny())); } - [Fact] + [Test] public async Task FindNodesReturnsMatchingNode() { var session = await CreateSession(); var foundNodes = service.FindNodes(session.SessionId, "Server", null, null, null); - Assert.Equal(1, foundNodes.Count); - Assert.Equal("Server", foundNodes[0].NodeType); - Assert.Equal(session.RootNode.NodePath, foundNodes[0].ToNodeInfo().NodePath); + Assert.AreEqual(1, foundNodes.Count); + Assert.AreEqual("Server", foundNodes[0].NodeType); + Assert.AreEqual(session.RootNode.NodePath, foundNodes[0].ToNodeInfo().NodePath); } - [Fact] + [Test] public async Task FindNodesReturnsEmptyListForNoMatch() { var session = await CreateSession(); var foundNodes = service.FindNodes(session.SessionId, "Table", "testSchema", "testTable", "testDatabase"); - Assert.Equal(0, foundNodes.Count); + Assert.AreEqual(0, foundNodes.Count); } - [Fact] + [Test] public void FindNodeCanExpandParentNodes() { var mockTreeNode = new Mock(); @@ -342,7 +344,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer test: (requestContext) => CallServiceExpand(expandParams, requestContext), verify: (actual => { - Assert.Equal(actual.SessionId, session.SessionId); + Assert.AreEqual(actual.SessionId, session.SessionId); Assert.NotNull(actual.SessionId); VerifyServerNodeChildren(actual.Nodes); })); @@ -363,7 +365,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer test: (requestContext) => CallServiceRefresh(expandParams, requestContext), verify: (actual => { - Assert.Equal(actual.SessionId, session.SessionId); + Assert.AreEqual(actual.SessionId, session.SessionId); Assert.NotNull(actual.SessionId); VerifyServerNodeChildren(actual.Nodes); })); @@ -460,10 +462,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer private void VerifyServerNode(NodeInfo serverNode, ConnectionDetails details) { Assert.NotNull(serverNode); - Assert.Equal(NodeTypes.Server.ToString(), serverNode.NodeType); + Assert.AreEqual(NodeTypes.Server.ToString(), serverNode.NodeType); string[] pathParts = serverNode.NodePath.Split(TreeNode.PathPartSeperator); - Assert.Equal(1, pathParts.Length); - Assert.Equal(details.ServerName, pathParts[0]); + Assert.AreEqual(1, pathParts.Length); + Assert.AreEqual(details.ServerName, pathParts[0]); Assert.True(serverNode.Label.Contains(details.ServerName)); Assert.False(serverNode.IsLeaf); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/ServerVersionHelperTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/ServerVersionHelperTests.cs index 95e9f411..ff7cbeae 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/ServerVersionHelperTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/ServerVersionHelperTests.cs @@ -5,22 +5,22 @@ using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.ServiceLayer.ObjectExplorer; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer { public class ServerVersionHelperTests { - [Fact] + [Test] public void GetValidForFlagShouldReturnAllGivenUnKnownVersion() { ValidForFlag validforFlag = ServerVersionHelper.GetValidForFlag(SqlServerType.Unknown); ValidForFlag expected = ValidForFlag.All; - Assert.Equal(validforFlag, expected); + Assert.AreEqual(validforFlag, expected); } - [Fact] + [Test] public void GetValidForFlagShouldReturnTheFlagCorrectlyGivenValidVersion() { VerifyGetValidForFlag(SqlServerType.AzureV12, ValidForFlag.AzureV12); @@ -33,16 +33,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyGetValidForFlag(SqlServerType.SqlOnDemand, ValidForFlag.SqlOnDemand); } - [Fact] + [Test] public void GetValidForFlagShouldReturnTheFlagIncludingSqlDwGivenSqlDwdatabase() { ValidForFlag validforFlag = ServerVersionHelper.GetValidForFlag(SqlServerType.AzureV12, true); ValidForFlag expected = ValidForFlag.SqlDw; - Assert.Equal(validforFlag, expected); + Assert.AreEqual(validforFlag, expected); } - [Fact] + [Test] public void CalculateServerTypeShouldReturnSql2005Given2005Version() { string serverVersion = "9.1.2.3"; @@ -51,7 +51,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer } - [Fact] + [Test] public void CalculateServerTypeShouldReturnSql2008Given2008Version() { string serverVersion = "10.1.2.3"; @@ -59,7 +59,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyCalculateServerType(serverVersion, expected); } - [Fact] + [Test] public void CalculateServerTypeShouldReturnSql2012Given2012Version() { string serverVersion = "11.1.2.3"; @@ -67,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyCalculateServerType(serverVersion, expected); } - [Fact] + [Test] public void CalculateServerTypeShouldReturnSql2014Given2014Version() { string serverVersion = "12.1.2.3"; @@ -75,7 +75,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyCalculateServerType(serverVersion, expected); } - [Fact] + [Test] public void CalculateServerTypeShouldReturnSql2016Given2016Version() { string serverVersion = "13.1.2.3"; @@ -83,7 +83,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyCalculateServerType(serverVersion, expected); } - [Fact] + [Test] public void CalculateServerTypeShouldReturnSql2017Given2017Version() { string serverVersion = "14.1.2.3"; @@ -91,7 +91,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyCalculateServerType(serverVersion, expected); } - [Fact] + [Test] public void IsValidForShouldReturnTrueGivenSqlDwAndAll() { ValidForFlag serverValidFor = ValidForFlag.SqlDw; @@ -100,7 +100,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyIsValidFor(serverValidFor, validFor, expected); } - [Fact] + [Test] public void IsValidForShouldReturnTrueGivenSqlDwAndNone() { ValidForFlag serverValidFor = ValidForFlag.SqlDw; @@ -109,7 +109,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyIsValidFor(serverValidFor, validFor, expected); } - [Fact] + [Test] public void IsValidForShouldReturnTrueGivenSqlDwAndSqlDw() { ValidForFlag serverValidFor = ValidForFlag.SqlDw; @@ -118,7 +118,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyIsValidFor(serverValidFor, validFor, expected); } - [Fact] + [Test] public void IsValidForShouldReturnTrueGivenSqlDwAndNotSqlDw() { ValidForFlag serverValidFor = ValidForFlag.SqlDw; @@ -127,7 +127,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyIsValidFor(serverValidFor, validFor, expected); } - [Fact] + [Test] public void IsValidForShouldReturnTrueGivenSqlDwAndAllOnPrem() { ValidForFlag serverValidFor = ValidForFlag.SqlDw; @@ -136,7 +136,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer VerifyIsValidFor(serverValidFor, validFor, expected); } - [Fact] + [Test] public void CalculateServerTypeShouldReturnSqlOnDemandGivenEngineEdition() { int engineEdition = 11; @@ -147,7 +147,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer private void VerifyIsValidFor(ValidForFlag serverValidFor, ValidForFlag validFor, bool expected) { bool actual = ServerVersionHelper.IsValidFor(serverValidFor, validFor); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); } private void VerifyCalculateServerType(string serverVersion, SqlServerType expected) @@ -157,7 +157,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer ServerVersion = serverVersion }; SqlServerType actual = ServerVersionHelper.CalculateServerType(serverInfo); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); } private void VerifyCalculateServerTypeForEngineEdition(int engineEdition, SqlServerType expected) @@ -176,7 +176,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer ValidForFlag validforFlag = ServerVersionHelper.GetValidForFlag(serverType); ValidForFlag expected = validForFlag; - Assert.Equal(validforFlag, expected); + Assert.AreEqual(validforFlag, expected); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/SmoQueryModelTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/SmoQueryModelTests.cs index 439f0ef9..4fb53fba 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/SmoQueryModelTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/SmoQueryModelTests.cs @@ -9,14 +9,14 @@ using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlTools.Extensibility; using Microsoft.SqlTools.ServiceLayer.ObjectExplorer; using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.SmoModel; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer { public class SmoQueryModelTests { - [Fact] + [Test] public void ShouldFindDatabaseQuerierFromRealPath() { // Given the extension type loader is set to find SmoCollectionQuerier objects @@ -25,53 +25,53 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer SmoQuerier querier = serviceProvider.GetService(q => q.SupportedObjectTypes.Contains(typeof(Database))); // Then I expect to get back the SqlDatabaseQuerier Assert.NotNull(querier); - Assert.Equal(typeof(SqlDatabaseQuerier), querier.GetType()); + Assert.AreEqual(typeof(SqlDatabaseQuerier), querier.GetType()); // And I expect the service provider to have been set by the extension code Assert.NotNull(querier.ServiceProvider); } - [Fact] + [Test] public void ShouldFindQuerierIfInExtensionList() { VerifyQuerierLookup(typeof(Table), typeof(SqlTableQuerier), expectExists: true); } - [Fact] + [Test] public void ShouldNotFindQuerierIfNotInExtensionList() { VerifyQuerierLookup(typeof(Database), null, expectExists: false); } - [Fact] + [Test] public void SqlServerDdlTriggerQuerierShouldNotBeAvailableForSqlDw() { SmoQuerier querier = GetSmoQuerier(typeof(ServerDdlTrigger)); Assert.False(querier.ValidFor.HasFlag(ValidForFlag.SqlDw)); } - [Fact] + [Test] public void SqlSynonymQuerierShouldNotBeAvailableForSqlDw() { SmoQuerier querier = GetSmoQuerier(typeof(Synonym)); Assert.False(querier.ValidFor.HasFlag(ValidForFlag.SqlDw)); } - [Fact] + [Test] public void SqlTriggerQuerierShouldNotBeAvailableForSqlDw() { SmoQuerier querier = GetSmoQuerier(typeof(Trigger)); Assert.False(querier.ValidFor.HasFlag(ValidForFlag.SqlDw)); } - [Fact] + [Test] public void SqlFullTextIndexQuerierShouldNotBeAvailableForSqlDw() { SmoQuerier querier = GetSmoQuerier(typeof(FullTextIndex)); Assert.False(querier.ValidFor.HasFlag(ValidForFlag.SqlDw)); } - [Fact] + [Test] public void TableValuedFunctionsIncludeInlineFunctions() { var tableFactory = new TableValuedFunctionsChildFactory(); @@ -106,7 +106,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer if (expectExists) { Assert.NotNull(querier); - Assert.Equal(querierType, querier.GetType()); + Assert.AreEqual(querierType, querier.GetType()); Assert.NotNull(querier.ServiceProvider); } else diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/UsersChildFactoryTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/UsersChildFactoryTests.cs index aed7f7db..96fa56c2 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/UsersChildFactoryTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ObjectExplorer/UsersChildFactoryTests.cs @@ -5,26 +5,26 @@ using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.SmoModel; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer { public class UsersChildFactoryTests { - [Fact] + [Test] public void GetStatusShouldReturnEmptyStringGivenNull() { string expected = string.Empty; string actual = UserCustomeNodeHelper.GetStatus(null); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); } - [Fact] + [Test] public void GetStatusShouldReturnEmptyStringGivenNotUser() { string expected = string.Empty; string actual = UserCustomeNodeHelper.GetStatus(new Database()); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerServiceTests.cs index 7eb6ed9e..7efe8216 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerServiceTests.cs @@ -15,10 +15,11 @@ using Microsoft.SqlTools.ServiceLayer.Profiler; using Microsoft.SqlTools.ServiceLayer.Profiler.Contracts; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler { + [TestFixture] /// /// Unit tests for ProfilerService /// @@ -29,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler /// /// // TODO: Fix flaky test. See https://github.com/Microsoft/sqltoolsservice/issues/459 - //[Fact] + //[Test] public async Task TestStartProfilingRequest() { string sessionId = null; @@ -84,7 +85,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler requestContext.VerifyAll(); // Check that the correct XEvent session was started - Assert.Equal(sessionId, "1"); + Assert.AreEqual("1", sessionId); // check that the proper owner Uri was used Assert.True(recievedEvents); @@ -94,7 +95,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler /// Test stopping a session and receiving event callback /// /// - [Fact] + [Test] public async Task TestStopProfilingRequest() { bool success = false; @@ -147,7 +148,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler /// Test pausing then resuming a session /// /// - [Fact] + [Test] public async Task TestPauseProfilingRequest() { bool success = false; @@ -238,7 +239,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler /// /// Test notifications for stopped sessions /// - [Fact] + [Test] public async Task TestStoppedSessionNotification() { bool sessionStopped = false; diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerSessionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerSessionTests.cs index 92509260..85a00e83 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerSessionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerSessionTests.cs @@ -7,7 +7,7 @@ using System; using System.Threading; using Microsoft.SqlTools.ServiceLayer.Profiler; using Microsoft.SqlTools.ServiceLayer.Profiler.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler { @@ -19,7 +19,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler /// /// Test the FilterOldEvents method /// - [Fact] + [Test] public void TestFilterOldEvents() { // create a profiler session and get some test events @@ -30,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler // filter all the results from the first poll // these events happened before the profiler began profilerSession.FilterOldEvents(profilerEvents); - Assert.Equal(profilerEvents.Count, 0); + Assert.AreEqual(0, profilerEvents.Count); // add a new event var newEvent = new ProfilerEvent("new event", "1/1/2017"); @@ -42,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler // filtering should leave only the new event profilerSession.FilterOldEvents(profilerEvents); - Assert.Equal(profilerEvents.Count, 1); + Assert.AreEqual(1, profilerEvents.Count); Assert.True(profilerEvents[0].Equals(newEvent)); //poll again with no new events @@ -50,13 +50,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler // filter should now filter all the events since they've been seen before profilerSession.FilterOldEvents(profilerEvents); - Assert.Equal(profilerEvents.Count, 0); + Assert.AreEqual(0, profilerEvents.Count); } /// /// Test the FilterProfilerEvents method /// - [Fact] + [Test] public void TestFilterProfilerEvents() { // create a profiler session and get some test events @@ -72,15 +72,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler profilerEvents.Add(newEvent); // verify that the polling event is removed - Assert.Equal(profilerEvents.Count, expectedEventCount + 1); + Assert.AreEqual(profilerEvents.Count, expectedEventCount + 1); var newProfilerEvents = profilerSession.FilterProfilerEvents(profilerEvents); - Assert.Equal(newProfilerEvents.Count, expectedEventCount); + Assert.AreEqual(newProfilerEvents.Count, expectedEventCount); } /// /// Test notifications for lost events /// - [Fact] + [Test] public void TestEventsLost() { // create a profiler session and get some test events @@ -90,7 +90,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler // filter all the results from the first poll // these events happened before the profiler began profilerSession.FilterOldEvents(profilerEvents); - Assert.Equal(profilerEvents.Count, 0); + Assert.AreEqual(0, profilerEvents.Count); // No events should be lost Assert.False(profilerSession.EventsLost); @@ -127,7 +127,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler /// /// Test the TryEnterPolling method /// - [Fact] + [Test] public void TestTryEnterPolling() { DateTime startTime = DateTime.Now; @@ -148,7 +148,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler bool outsideDelay = DateTime.Now.Subtract(startTime) >= profilerSession.PollingDelay; // verify we can only enter again if we're outside polling delay interval - Assert.Equal(profilerSession.TryEnterPolling(), outsideDelay); + Assert.AreEqual(profilerSession.TryEnterPolling(), outsideDelay); // reset IsPolling in case the delay has elasped on slow machine or while debugging profilerSession.IsPolling = false; diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerTestObjects.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerTestObjects.cs index 96a51947..94dcd171 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerTestObjects.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Profiler/ProfilerTestObjects.cs @@ -15,7 +15,7 @@ using Microsoft.SqlTools.ServiceLayer.Profiler; using Microsoft.SqlTools.ServiceLayer.Profiler.Contracts; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler { diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/CancelTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/CancelTests.cs index 3230a21e..b6eb3dfb 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/CancelTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/CancelTests.cs @@ -14,13 +14,13 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.Workspace; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution { public class CancelTests { - [Fact] + [Test] public async Task CancelInProgressQueryTest() { // If: @@ -46,12 +46,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... The query should not have been disposed but should have been cancelled - Assert.Equal(1, queryService.ActiveQueries.Count); - Assert.Equal(true, queryService.ActiveQueries[Constants.OwnerUri].HasCancelled); + Assert.AreEqual(1, queryService.ActiveQueries.Count); + Assert.AreEqual(true, queryService.ActiveQueries[Constants.OwnerUri].HasCancelled); cancelRequest.Validate(); } - [Fact] + [Test] public async Task CancelExecutedQueryTest() { // If: @@ -77,12 +77,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... The query should not have been disposed and cancel should not have excecuted - Assert.NotEmpty(queryService.ActiveQueries); - Assert.Equal(false, queryService.ActiveQueries[Constants.OwnerUri].HasCancelled); + Assert.That(queryService.ActiveQueries, Is.Not.Empty); + Assert.AreEqual(false, queryService.ActiveQueries[Constants.OwnerUri].HasCancelled); cancelRequest.Validate(); } - [Fact] + [Test] public async Task CancelNonExistantTest() { // If: @@ -100,7 +100,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution cancelRequest.Validate(); } - [Fact] + [Test] public async Task CancelQueryBeforeExecutionStartedTest() { // Setup query settings @@ -130,9 +130,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution await query.ExecutionTask; // Validate that query has not been executed but cancelled and query failed called function was called - Assert.Equal(true, query.HasCancelled); - Assert.Equal(false, query.HasExecuted); - Assert.Equal("Error Occured", errorMessage); + Assert.AreEqual(true, query.HasCancelled); + Assert.AreEqual(false, query.HasExecuted); + Assert.AreEqual("Error Occured", errorMessage); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsCsvFileStreamWriterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsCsvFileStreamWriterTests.cs index ab6e4723..c26a9fcc 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsCsvFileStreamWriterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsCsvFileStreamWriterTests.cs @@ -11,23 +11,23 @@ using System.Text.RegularExpressions; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage { public class SaveAsCsvFileStreamWriterTests { - [Theory] - [InlineData("Something\rElse")] - [InlineData("Something\nElse")] - [InlineData("Something\"Else")] - [InlineData("Something,Else")] - [InlineData("\tSomething")] - [InlineData("Something\t")] - [InlineData(" Something")] - [InlineData("Something ")] - [InlineData(" \t\r\n\",\r\n\"\r ")] - public void EncodeCsvFieldShouldWrap(string field) + [Test] + public void EncodeCsvFieldShouldWrap( + [Values("Something\rElse", + "Something\nElse", + "Something\"Else", + "Something,Else", + "\tSomething", + "Something\t", + " Something", + "Something ", + " \t\r\n\",\r\n\"\r ")] string field) { // If: I CSV encode a field that has forbidden characters in it string output = SaveAsCsvFileStreamWriter.EncodeCsvField(field, ',', '\"'); @@ -37,11 +37,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage && Regex.IsMatch(output, ".*\"$")); } - [Theory] - [InlineData("Something")] - [InlineData("Something valid.")] - [InlineData("Something\tvalid")] - public void EncodeCsvFieldShouldNotWrap(string field) + [Test] + public void EncodeCsvFieldShouldNotWrap( + [Values( + "Something", + "Something valid.", + "Something\tvalid" + )] string field) { // If: I CSV encode a field that does not have forbidden characters in it string output = SaveAsCsvFileStreamWriter.EncodeCsvField(field, ',', '\"'); @@ -50,27 +52,27 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage Assert.False(Regex.IsMatch(output, "^\".*\"$")); } - [Fact] + [Test] public void EncodeCsvFieldReplace() { // If: I CSV encode a field that has a double quote in it, string output = SaveAsCsvFileStreamWriter.EncodeCsvField("Some\"thing", ',', '\"'); // Then: It should be replaced with double double quotes - Assert.Equal("\"Some\"\"thing\"", output); + Assert.AreEqual("\"Some\"\"thing\"", output); } - [Fact] + [Test] public void EncodeCsvFieldNull() { // If: I CSV encode a null string output = SaveAsCsvFileStreamWriter.EncodeCsvField(null, ',', '\"'); // Then: there should be a string version of null returned - Assert.Equal("NULL", output); + Assert.AreEqual("NULL", output); } - [Fact] + [Test] public void WriteRowWithoutColumnSelectionOrHeader() { // Setup: @@ -100,12 +102,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // Then: It should write one line with 2 items, comma delimited string outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n'); string[] lines = outputString.Split(new[] { Environment.NewLine }, StringSplitOptions.None); - Assert.Equal(1, lines.Length); + Assert.AreEqual(1, lines.Length); string[] values = lines[0].Split(','); - Assert.Equal(2, values.Length); + Assert.AreEqual(2, values.Length); } - [Fact] + [Test] public void WriteRowWithHeader() { // Setup: @@ -139,20 +141,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... It should have written two lines string outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n'); string[] lines = outputString.Split(new[] { Environment.NewLine }, StringSplitOptions.None); - Assert.Equal(2, lines.Length); + Assert.AreEqual(2, lines.Length); // ... It should have written a header line with two, comma separated names string[] headerValues = lines[0].Split(','); - Assert.Equal(2, headerValues.Length); + Assert.AreEqual(2, headerValues.Length); for (int i = 0; i < columns.Count; i++) { - Assert.Equal(columns[i].ColumnName, headerValues[i]); + Assert.AreEqual(columns[i].ColumnName, headerValues[i]); } // Note: No need to check values, it is done as part of the previous test } - [Fact] + [Test] public void WriteRowWithColumnSelection() { // Setup: @@ -194,26 +196,26 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... It should have written two lines string outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n'); string[] lines = outputString.Split(new[] { Environment.NewLine }, StringSplitOptions.None); - Assert.Equal(2, lines.Length); + Assert.AreEqual(2, lines.Length); // ... It should have written a header line with two, comma separated names string[] headerValues = lines[0].Split(','); - Assert.Equal(2, headerValues.Length); + Assert.AreEqual(2, headerValues.Length); for (int i = 1; i <= 2; i++) { - Assert.Equal(columns[i].ColumnName, headerValues[i - 1]); + Assert.AreEqual(columns[i].ColumnName, headerValues[i - 1]); } // ... The second line should have two, comma separated values string[] dataValues = lines[1].Split(','); - Assert.Equal(2, dataValues.Length); + Assert.AreEqual(2, dataValues.Length); for (int i = 1; i <= 2; i++) { - Assert.Equal(data[i].DisplayValue, dataValues[i - 1]); + Assert.AreEqual(data[i].DisplayValue, dataValues[i - 1]); } } - [Fact] + [Test] public void WriteRowWithCustomDelimiters() { // Setup: @@ -248,20 +250,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... It should have written two lines string outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n'); string[] lines = outputString.Split(new[] { Environment.NewLine }, StringSplitOptions.None); - Assert.Equal(2, lines.Length); + Assert.AreEqual(2, lines.Length); // ... It should have written a header line with two, pipe("|") separated names string[] headerValues = lines[0].Split('|'); - Assert.Equal(2, headerValues.Length); + Assert.AreEqual(2, headerValues.Length); for (int i = 0; i < columns.Count; i++) { - Assert.Equal(columns[i].ColumnName, headerValues[i]); + Assert.AreEqual(columns[i].ColumnName, headerValues[i]); } // Note: No need to check values, it is done as part of the previous tests } - [Fact] + [Test] public void WriteRowsWithCustomLineSeperator() { // Setup: @@ -301,7 +303,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... It should have splitten the lines by system's default line seperator outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n'); lines = outputString.Split(new[] { Environment.NewLine }, StringSplitOptions.None); - Assert.Equal(2, lines.Length); + Assert.AreEqual(2, lines.Length); // If: I set \n (line feed) as seperator and write a row requestParams.LineSeperator = "\n"; @@ -316,7 +318,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... It should have splitten the lines by \n outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n'); lines = outputString.Split(new[] { '\n' }, StringSplitOptions.None); - Assert.Equal(2, lines.Length); + Assert.AreEqual(2, lines.Length); // If: I set \r\n (carriage return + line feed) as seperator and write a row requestParams.LineSeperator = "\r\n"; @@ -331,11 +333,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... It should have splitten the lines by \r\n outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n'); lines = outputString.Split(new[] { "\r\n" }, StringSplitOptions.None); - Assert.Equal(2, lines.Length); + Assert.AreEqual(2, lines.Length); } - [Fact] + [Test] public void WriteRowWithCustomTextIdentifier() { // Setup: @@ -373,10 +375,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // Then: // ... It should have splitten the columns by delimiter, embedded in text identifier when field contains delimiter or the text identifier string outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n'); - Assert.Equal("\'item;1\';item,2;item\"3;\'item\'\'4\'", outputString); + Assert.AreEqual("\'item;1\';item,2;item\"3;\'item\'\'4\'", outputString); } - [Fact] + [Test] public void WriteRowWithCustomEncoding() { // Setup: @@ -408,7 +410,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... It should have written the umlaut using the encoding Windows-1252 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); string outputString = Encoding.GetEncoding("Windows-1252").GetString(output).TrimEnd('\0', '\r', '\n'); - Assert.Equal("ü", outputString); + Assert.AreEqual("ü", outputString); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsExcelFileStreamWriterHelperTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsExcelFileStreamWriterHelperTests.cs index 43bf029d..aca4487a 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsExcelFileStreamWriterHelperTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsExcelFileStreamWriterHelperTests.cs @@ -12,7 +12,7 @@ using System.IO.Compression; using System.Text.RegularExpressions; using System.Xml; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage { @@ -86,36 +86,36 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage using (var reader = new StreamReader(zip.GetEntry(fileName).Open())) { string realContent = reader.ReadToEnd(); - Assert.Equal(referenceContent, realContent); + Assert.AreEqual(referenceContent, realContent); } } } - [Fact] + [Test] public void CheckContentType() { ContentMatch("[Content_Types].xml"); } - [Fact] + [Test] public void CheckTopRels() { ContentMatch("_rels/.rels"); } - [Fact] + [Test] public void CheckWorkbookRels() { ContentMatch("xl/_rels/workbook.xml.rels"); } - [Fact] + [Test] public void CheckStyles() { ContentMatch("xl/styles.xml"); } - [Fact] + [Test] public void CheckWorkbook() { ContentMatch("xl/workbook.xml"); } - [Fact] + [Test] public void CheckSheet1() { ContentMatch("xl/worksheets/sheet1.xml"); @@ -148,16 +148,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } - [Fact] + [Test] public void ReferenceA1() { var xmlWriter = _xmlWriterMock.Object; var manager = new SaveAsExcelFileStreamWriterHelper.ReferenceManager(xmlWriter); manager.WriteAndIncreaseRowReference(); manager.WriteAndIncreaseColumnReference(); - Assert.Equal("A1", LastWrittenReference); + Assert.AreEqual("A1", LastWrittenReference); } - [Fact] + [Test] public void ReferenceZ1() { var xmlWriter = _xmlWriterMock.Object; @@ -168,11 +168,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage manager.IncreaseColumnReference(); } manager.WriteAndIncreaseColumnReference(); - Assert.Equal("Z1", LastWrittenReference); + Assert.AreEqual("Z1", LastWrittenReference); manager.WriteAndIncreaseColumnReference(); - Assert.Equal("AA1", LastWrittenReference); + Assert.AreEqual("AA1", LastWrittenReference); } - [Fact] + [Test] public void ReferenceZZ1() { var xmlWriter = _xmlWriterMock.Object; @@ -184,11 +184,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage manager.IncreaseColumnReference(); } manager.WriteAndIncreaseColumnReference(); - Assert.Equal("ZZ1", LastWrittenReference); + Assert.AreEqual("ZZ1", LastWrittenReference); manager.WriteAndIncreaseColumnReference(); - Assert.Equal("AAA1", LastWrittenReference); + Assert.AreEqual("AAA1", LastWrittenReference); } - [Fact] + [Test] public void ReferenceXFD() { var xmlWriter = _xmlWriterMock.Object; @@ -202,31 +202,31 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage //The 16384 should be the maximal column and not throw manager.AssureColumnReference(); manager.WriteAndIncreaseColumnReference(); - Assert.Equal("XFD1", LastWrittenReference); + Assert.AreEqual("XFD1", LastWrittenReference); var ex = Assert.Throws( () => manager.AssureColumnReference()); - Assert.Contains("max column number is 16384", ex.Message); + Assert.That(ex.Message, Does.Contain("max column number is 16384")); } - [Fact] + [Test] public void ReferenceRowReset() { var xmlWriter = _xmlWriterMock.Object; var manager = new SaveAsExcelFileStreamWriterHelper.ReferenceManager(xmlWriter); manager.WriteAndIncreaseRowReference(); - Assert.Equal(1, LastWrittenRow); + Assert.AreEqual(1, LastWrittenRow); manager.WriteAndIncreaseColumnReference(); - Assert.Equal("A1", LastWrittenReference); + Assert.AreEqual("A1", LastWrittenReference); manager.WriteAndIncreaseColumnReference(); - Assert.Equal("B1", LastWrittenReference); + Assert.AreEqual("B1", LastWrittenReference); //add row should reset column reference manager.WriteAndIncreaseRowReference(); - Assert.Equal(2, LastWrittenRow); + Assert.AreEqual(2, LastWrittenRow); manager.WriteAndIncreaseColumnReference(); - Assert.Equal("A2", LastWrittenReference); + Assert.AreEqual("A2", LastWrittenReference); } - [Fact] + [Test] public void AddRowMustBeCalledBeforeAddCellException() { var xmlWriter = _xmlWriterMock.Object; @@ -234,7 +234,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage var ex = Assert.Throws( () => manager.AssureColumnReference()); - Assert.Contains("AddRow must be called before AddCell", ex.Message); + Assert.That(ex.Message, Does.Contain("AddRow must be called before AddCell")); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsJsonFileStreamWriterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsJsonFileStreamWriterTests.cs index a0b4cb16..bc64318a 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsJsonFileStreamWriterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/SaveAsJsonFileStreamWriterTests.cs @@ -11,13 +11,13 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Newtonsoft.Json; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage { public class SaveAsJsonFileStreamWriterTests { - [Fact] + [Test] public void ArrayWrapperTest() { // Setup: @@ -34,10 +34,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... The output should be an empty array string outputString = Encoding.UTF8.GetString(output).TrimEnd('\0'); object[] outputArray = JsonConvert.DeserializeObject(outputString); - Assert.Equal(0, outputArray.Length); + Assert.AreEqual(0, outputArray.Length); } - [Fact] + [Test] public void WriteRowWithoutColumnSelection() { // Setup: @@ -74,19 +74,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... There should be 2 items in the array, // ... The item should have two fields, and two values, assigned appropriately - Assert.Equal(2, outputObject.Length); + Assert.AreEqual(2, outputObject.Length); foreach (var item in outputObject) { - Assert.Equal(2, item.Count); + Assert.AreEqual(2, item.Count); for (int i = 0; i < columns.Count; i++) { Assert.True(item.ContainsKey(columns[i].ColumnName)); - Assert.Equal(data[i].RawObject == null ? null : data[i].DisplayValue, item[columns[i].ColumnName]); + Assert.AreEqual(data[i].RawObject == null ? null : data[i].DisplayValue, item[columns[i].ColumnName]); } } } - [Fact] + [Test] public void WriteRowWithColumnSelection() { // Setup: @@ -132,19 +132,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... There should be 2 items in the array // ... The items should have 2 fields and values - Assert.Equal(2, outputObject.Length); + Assert.AreEqual(2, outputObject.Length); foreach (var item in outputObject) { - Assert.Equal(2, item.Count); + Assert.AreEqual(2, item.Count); for (int i = 1; i <= 2; i++) { Assert.True(item.ContainsKey(columns[i].ColumnName)); - Assert.Equal(data[i].RawObject == null ? null : data[i].DisplayValue, item[columns[i].ColumnName]); + Assert.AreEqual(data[i].RawObject == null ? null : data[i].DisplayValue, item[columns[i].ColumnName]); } } } - [Fact] + [Test] public void WriteRowWithSpecialTypesSuccess() { @@ -186,14 +186,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage // ... There should be 2 items in the array, // ... The item should have three fields, and three values, assigned appropriately // ... The deserialized values should match the display value - Assert.Equal(2, outputObject.Length); + Assert.AreEqual(2, outputObject.Length); foreach (var item in outputObject) { - Assert.Equal(3, item.Count); + Assert.AreEqual(3, item.Count); for (int i = 0; i < columns.Count; i++) { Assert.True(item.ContainsKey(columns[i].ColumnName)); - Assert.Equal(data[i].RawObject == null ? null : data[i].DisplayValue, item[columns[i].ColumnName]); + Assert.AreEqual(data[i].RawObject == null ? null : data[i].DisplayValue, item[columns[i].ColumnName]); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/ServiceBufferFileStreamReaderWriterTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/ServiceBufferFileStreamReaderWriterTests.cs index 3c546a2d..26a6a74d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/ServiceBufferFileStreamReaderWriterTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DataStorage/ServiceBufferFileStreamReaderWriterTests.cs @@ -15,13 +15,13 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage; using Microsoft.SqlTools.ServiceLayer.SqlContext; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage { public class ServiceBufferReaderWriterTests { - [Fact] + [Test] public void ReaderStreamNull() { // If: I create a service buffer file stream reader with a null stream @@ -29,7 +29,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage Assert.Throws(() => new ServiceBufferFileStreamReader(null, new QueryExecutionSettings())); } - [Fact] + [Test] public void ReaderSettingsNull() { // If: I create a service buffer file stream reader with null settings @@ -37,7 +37,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage Assert.Throws(() => new ServiceBufferFileStreamReader(Stream.Null, null)); } - [Fact] + [Test] public void ReaderInvalidStreamCannotRead() { // If: I create a service buffer file stream reader with a stream that cannot be read @@ -52,7 +52,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage }); } - [Fact] + [Test] public void ReaderInvalidStreamCannotSeek() { // If: I create a service buffer file stream reader with a stream that cannot seek @@ -67,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage }); } - [Fact] + [Test] public void WriterStreamNull() { // If: I create a service buffer file stream writer with a null stream @@ -75,7 +75,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage Assert.Throws(() => new ServiceBufferFileStreamWriter(null, new QueryExecutionSettings())); } - [Fact] + [Test] public void WriterSettingsNull() { // If: I create a service buffer file stream writer with null settings @@ -83,7 +83,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage Assert.Throws(() => new ServiceBufferFileStreamWriter(Stream.Null, null)); } - [Fact] + [Test] public void WriterInvalidStreamCannotWrite() { // If: I create a service buffer file stream writer with a stream that cannot be read @@ -98,7 +98,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage }); } - [Fact] + [Test] public void WriterInvalidStreamCannotSeek() { // If: I create a service buffer file stream writer with a stream that cannot seek @@ -129,7 +129,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage using (ServiceBufferFileStreamWriter writer = new ServiceBufferFileStreamWriter(new MemoryStream(storage), overrideSettings)) { int writtenBytes = writeFunc(writer, value); - Assert.Equal(valueLength, writtenBytes); + Assert.AreEqual(valueLength, writtenBytes); } // ... And read the type T back @@ -140,78 +140,80 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } // Then: - Assert.Equal(value, outValue.Value.RawObject); - Assert.Equal(valueLength, outValue.TotalLength); + Assert.AreEqual(value, outValue.Value.RawObject); + Assert.AreEqual(valueLength, outValue.TotalLength); Assert.NotNull(outValue.Value); // ... The id we set should be stored in the returned db cell value - Assert.Equal(rowId, outValue.Value.RowId); + Assert.AreEqual(rowId, outValue.Value.RowId); return outValue.Value.DisplayValue; } - [Theory] - [InlineData(0)] - [InlineData(10)] - [InlineData(-10)] - [InlineData(short.MaxValue)] // Two byte number - [InlineData(short.MinValue)] // Negative two byte number - public void Int16(short value) + [Test] + + + + + + public void Int16([Values( + 0, + 10, + -10, + short.MaxValue, // Two byte number + short.MinValue // Negative two byte number + )] short value) { VerifyReadWrite(sizeof(short) + 1, value, (writer, val) => writer.WriteInt16(val), (reader, rowId) => reader.ReadInt16(0, rowId)); } - [Theory] - [InlineData(0)] - [InlineData(10)] - [InlineData(-10)] - [InlineData(short.MaxValue)] // Two byte number - [InlineData(short.MinValue)] // Negative two byte number - [InlineData(int.MaxValue)] // Four byte number - [InlineData(int.MinValue)] // Negative four byte number - public void Int32(int value) + [Test] + public void Int32([Values( + 0, + 10, + -10, + short.MaxValue, // Two byte number + short.MinValue, // Negative two byte number + int.MaxValue, // Four byte number + int.MinValue // Negative four byte number + )] int value) { VerifyReadWrite(sizeof(int) + 1, value, (writer, val) => writer.WriteInt32(val), (reader, rowId) => reader.ReadInt32(0, rowId)); } - [Theory] - [InlineData(0)] - [InlineData(10)] - [InlineData(-10)] - [InlineData(short.MaxValue)] // Two byte number - [InlineData(short.MinValue)] // Negative two byte number - [InlineData(int.MaxValue)] // Four byte number - [InlineData(int.MinValue)] // Negative four byte number - [InlineData(long.MaxValue)] // Eight byte number - [InlineData(long.MinValue)] // Negative eight byte number - public void Int64(long value) + [Test] + public void Int64([Values( + 0, + 10, + -10, + short.MaxValue, // Two byte number + short.MinValue, // Negative two byte number + int.MaxValue, // Four byte number + int.MinValue, // Negative four byte number + long.MaxValue, // Eight byte number + long.MinValue // Negative eight byte number + )] long value) { VerifyReadWrite(sizeof(long) + 1, value, (writer, val) => writer.WriteInt64(val), (reader, rowId) => reader.ReadInt64(0, rowId)); } - [Theory] - [InlineData(0)] - [InlineData(10)] - public void Byte(byte value) + [Test] + public void Byte([Values(0,10)] byte value) { VerifyReadWrite(sizeof(byte) + 1, value, (writer, val) => writer.WriteByte(val), (reader, rowId) => reader.ReadByte(0, rowId)); } - [Theory] - [InlineData('a')] - [InlineData('1')] - [InlineData((char)0x9152)] // Test something in the UTF-16 space - public void Char(char value) + [Test] + public void Char([Values('a', + '1', + (char)0x9152)] // Test something in the UTF-16 space + char value) { VerifyReadWrite(sizeof(char) + 1, value, (writer, val) => writer.WriteChar(val), (reader, rowId) => reader.ReadChar(0, rowId)); } - [Theory] - [InlineData(true, true)] - [InlineData(false, true)] - [InlineData(true, false)] - [InlineData(false, false)] - public void Boolean(bool value, bool preferNumeric) + [Test] + public void Boolean([Values] bool value, [Values] bool preferNumeric) { string displayValue = VerifyReadWrite(sizeof(bool) + 1, value, (writer, val) => writer.WriteBoolean(val), @@ -232,37 +234,39 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Theory] - [InlineData(0)] - [InlineData(10.1)] - [InlineData(-10.1)] - [InlineData(float.MinValue)] - [InlineData(float.MaxValue)] - [InlineData(float.PositiveInfinity)] - [InlineData(float.NegativeInfinity)] - public void Single(float value) + [Test] + public void Single([Values( + 0, + 10.1F, + -10.1F, + float.MinValue, + float.MaxValue, + float.PositiveInfinity, + float.NegativeInfinity + )] float value) { VerifyReadWrite(sizeof(float) + 1, value, (writer, val) => writer.WriteSingle(val), (reader, rowId) => reader.ReadSingle(0, rowId)); } - [Theory] - [InlineData(0)] - [InlineData(10.1)] - [InlineData(-10.1)] - [InlineData(float.MinValue)] - [InlineData(float.MaxValue)] - [InlineData(float.PositiveInfinity)] - [InlineData(float.NegativeInfinity)] - [InlineData(double.PositiveInfinity)] - [InlineData(double.NegativeInfinity)] - [InlineData(double.MinValue)] - [InlineData(double.MaxValue)] - public void Double(double value) + [Test] + public void Double([Values( + 0, + 10.1, + -10.1, + float.MinValue, + float.MaxValue, + float.PositiveInfinity, + float.NegativeInfinity, + double.PositiveInfinity, + double.NegativeInfinity, + double.MinValue, + double.MaxValue + )]double value) { VerifyReadWrite(sizeof(double) + 1, value, (writer, val) => writer.WriteDouble(val), (reader, rowId) => reader.ReadDouble(0, rowId)); } - [Fact] + [Test] public void SqlDecimalTest() { // Setup: Create some test values @@ -278,7 +282,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Fact] + [Test] public void Decimal() { // Setup: Create some test values @@ -295,7 +299,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Fact] + [Test] public void DateTest() { // Setup: Create some test values @@ -318,7 +322,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Fact] + [Test] public void DateTimeTest() { // Setup: Create some test values @@ -341,15 +345,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Theory] - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - [InlineData(4)] - [InlineData(5)] - [InlineData(6)] - [InlineData(7)] - public void DateTime2Test(int precision) + [Test] + public void DateTime2Test([Values(1,2,3,4,5,6,7)] int precision) { // Setup: Create some test values // NOTE: We are doing these here instead of InlineData because DateTime values can't be written as constant expressions @@ -379,7 +376,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Fact] + [Test] public void DateTime2ZeroScaleTest() { // Setup: Create some test values @@ -402,7 +399,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Fact] + [Test] public void DateTime2InvalidScaleTest() { // Setup: Create some test values @@ -426,7 +423,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Fact] + [Test] public void DateTimeOffsetTest() { // Setup: Create some test values @@ -446,7 +443,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Fact] + [Test] public void TimeSpanTest() { // Setup: Create some test values @@ -462,7 +459,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Fact] + [Test] public void StringNullTest() { // Setup: Create a mock file stream @@ -479,13 +476,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Theory] - [InlineData(0, null)] // Test of empty string - [InlineData(1, new[] { 'j' })] - [InlineData(1, new[] { (char)0x9152 })] - [InlineData(100, new[] { 'j', (char)0x9152 })] // Test alternating utf-16/ascii characters - [InlineData(512, new[] { 'j', (char)0x9152 })] // Test that requires a 4 byte length - public void StringTest(int length, char[] values) + [Test, Sequential] + public void StringTest([Values(0,1,1,100,512)] int length, + [Values(null, + new[] { 'j' }, + new[] { (char)0x9152 }, + new[] { 'j', (char)0x9152 }, // Test alternating utf-16/ascii characters + new[] { 'j', (char)0x9152 })] // Test that requires a 4 byte length + char[] values) { // Setup: // ... Generate the test value @@ -500,7 +498,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage (reader, rowId) => reader.ReadString(0, rowId)); } - [Fact] + [Test] public void BytesNullTest() { // Setup: Create a mock file stream wrapper @@ -517,13 +515,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage } } - [Theory] - [InlineData(0, new byte[] { 0x00 })] // Test of empty byte[] - [InlineData(1, new byte[] { 0x00 })] - [InlineData(1, new byte[] { 0xFF })] - [InlineData(100, new byte[] { 0x10, 0xFF, 0x00 })] - [InlineData(512, new byte[] { 0x10, 0xFF, 0x00 })] // Test that requires a 4 byte length - public void Bytes(int length, byte[] values) + [Test, Sequential] + public void Bytes([Values(0, 1, 1, 100, 512)] int length, + [Values(new byte[] { 0x00 }, // Test of empty byte[] + new byte[] { 0x00 }, + new byte[] { 0xFF }, + new byte[] { 0x10, 0xFF, 0x00 }, + new byte[] { 0x10, 0xFF, 0x00 } // Test that requires a 4 byte length + )] + byte[] values) { // Setup: // ... Generate the test value @@ -539,26 +539,28 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage (reader, rowId) => reader.ReadBytes(0, rowId)); } - public static IEnumerable GuidTestParameters + private static IEnumerable GuidTestParameters { get { - yield return new object[] {Guid.Empty}; - yield return new object[] {Guid.NewGuid()}; - yield return new object[] {Guid.NewGuid()}; + yield return Guid.Empty; + yield return Guid.NewGuid(); + yield return Guid.NewGuid(); } } - [Theory] - [MemberData(nameof(GuidTestParameters))] - public void GuidTest(Guid testValue) + [Test] + public void GuidTest() { - VerifyReadWrite(testValue.ToByteArray().Length + 1, testValue, - (writer, val) => writer.WriteGuid(testValue), - (reader, rowId) => reader.ReadGuid(0, rowId)); + foreach (var testValue in GuidTestParameters) + { + VerifyReadWrite(testValue.ToByteArray().Length + 1, testValue, + (writer, val) => writer.WriteGuid(testValue), + (reader, rowId) => reader.ReadGuid(0, rowId)); + } } - [Fact] + [Test] public void MoneyTest() { // Setup: Create some test values diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DbCellValueTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DbCellValueTests.cs index 87df902e..8b5cff8d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DbCellValueTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DbCellValueTests.cs @@ -5,13 +5,13 @@ using System; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution { public class DbCellValueTests { - [Fact] + [Test] public void ConstructValid() { // If: I construct a new DbCellValue @@ -23,12 +23,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution }; // Then: It should have the values I specified in it - Assert.Equal("qqq", dbc.DisplayValue); - Assert.Equal(12, dbc.RawObject); + Assert.AreEqual("qqq", dbc.DisplayValue); + Assert.AreEqual(12, dbc.RawObject); Assert.True(dbc.IsNull); } - [Fact] + [Test] public void CopyToNullOther() { // If: I copy a DbCellValue to null @@ -36,7 +36,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution Assert.Throws(() => new DbCellValue().CopyTo(null)); } - [Fact] + [Test] public void CopyToValid() { // If: I copy a DbCellValue to another DbCellValue @@ -45,9 +45,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution source.CopyTo(dest); // Then: The source values should be in the dest - Assert.Equal(source.DisplayValue, dest.DisplayValue); - Assert.Equal(source.IsNull, dest.IsNull); - Assert.Equal(source.RawObject, dest.RawObject); + Assert.AreEqual(source.DisplayValue, dest.DisplayValue); + Assert.AreEqual(source.IsNull, dest.IsNull); + Assert.AreEqual(source.RawObject, dest.RawObject); } } } \ No newline at end of file diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DisposeTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DisposeTests.cs index 9be9ab3d..8ff1429c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DisposeTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/DisposeTests.cs @@ -14,13 +14,13 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.Workspace; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution { public class DisposeTests { - [Fact] + [Test] public void DisposeResultSet() { // Setup: Mock file stream factory, mock db reader @@ -34,7 +34,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution mockFileStreamFactory.Verify(fsf => fsf.DisposeFile(It.IsAny()), Times.Once); } - [Fact] + [Test] public async Task DisposeExecutedQuery() { // If: @@ -57,10 +57,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... And the active queries should be empty disposeRequest.Validate(); - Assert.Empty(queryService.ActiveQueries); + Assert.That(queryService.ActiveQueries, Is.Empty); } - [Fact] + [Test] public async Task QueryDisposeMissingQuery() { // If: @@ -78,7 +78,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution disposeRequest.Validate(); } - [Fact] + [Test] public async Task ServiceDispose() { // Setup: @@ -95,14 +95,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask; // ... And it sticks around as an active query - Assert.Equal(1, queryService.ActiveQueries.Count); + Assert.AreEqual(1, queryService.ActiveQueries.Count); // ... The query execution service is disposed, like when the service is shutdown queryService.Dispose(); // Then: // ... There should no longer be an active query - Assert.Empty(queryService.ActiveQueries); + Assert.That(queryService.ActiveQueries, Is.Empty); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/BatchTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/BatchTests.cs index 3a517d37..ad536bcf 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/BatchTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/BatchTests.cs @@ -16,13 +16,13 @@ using Microsoft.SqlTools.ServiceLayer.Connection; using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.Test.Common; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution { public class BatchTests { - [Fact] + [Test] public void BatchCreationTest() { // If I create a new batch... @@ -30,32 +30,32 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... The text of the batch should be stored - Assert.NotEmpty(batch.BatchText); + Assert.That(batch.BatchText, Is.Not.Empty); // ... It should not have executed and no error Assert.False(batch.HasExecuted, "The query should not have executed."); Assert.False(batch.HasError); // ... The results should be empty - Assert.Empty(batch.ResultSets); - Assert.Empty(batch.ResultSummaries); + Assert.That(batch.ResultSets, Is.Empty); + Assert.That(batch.ResultSummaries, Is.Empty); // ... The start line of the batch should be 0 - Assert.Equal(0, batch.Selection.StartLine); + Assert.AreEqual(0, batch.Selection.StartLine); // ... It's ordinal ID should be what I set it to - Assert.Equal(Common.Ordinal, batch.Id); + Assert.AreEqual(Common.Ordinal, batch.Id); // ... The summary should have the same info - Assert.Equal(Common.Ordinal, batch.Summary.Id); + Assert.AreEqual(Common.Ordinal, batch.Summary.Id); Assert.Null(batch.Summary.ResultSetSummaries); - Assert.Equal(0, batch.Summary.Selection.StartLine); - Assert.NotEqual(default(DateTime).ToString("o"), batch.Summary.ExecutionStart); // Should have been set at construction + Assert.AreEqual(0, batch.Summary.Selection.StartLine); + Assert.That(batch.Summary.ExecutionStart, Is.Not.EqualTo(default(DateTime).ToString("o"))); // Should have been set at construction Assert.Null(batch.Summary.ExecutionEnd); Assert.Null(batch.Summary.ExecutionElapsed); } - [Fact] + [Test] public async Task BatchExecuteNoResultSets() { // Setup: @@ -77,9 +77,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... Callbacks should have been called the appropriate number of times - Assert.Equal(1, batchStartCalls); - Assert.Equal(1, batchEndCalls); - Assert.Equal(0, resultSetCalls); + Assert.AreEqual(1, batchStartCalls); + Assert.AreEqual(1, batchEndCalls); + Assert.AreEqual(0, resultSetCalls); // ... The batch and the summary should be correctly assigned ValidateBatch(batch, 0, false); @@ -87,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution ValidateMessages(batch, 1, messages); } - [Fact] + [Test] public async Task BatchExecuteOneResultSet() { // Setup: @@ -113,9 +113,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... Callbacks should have been called the appropriate number of times - Assert.Equal(1, batchStartCalls); - Assert.Equal(1, batchEndCalls); - Assert.Equal(1, resultSetCalls); + Assert.AreEqual(1, batchStartCalls); + Assert.AreEqual(1, batchEndCalls); + Assert.AreEqual(1, resultSetCalls); // ... There should be exactly one result set ValidateBatch(batch, resultSets, false); @@ -123,7 +123,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution ValidateMessages(batch, 1, messages); } - [Fact] + [Test] public async Task BatchExecuteTwoResultSets() { // Setup: @@ -149,9 +149,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... Callbacks should have been called the appropriate number of times - Assert.Equal(1, batchStartCalls); - Assert.Equal(1, batchEndCalls); - Assert.Equal(2, resultSetCalls); + Assert.AreEqual(1, batchStartCalls); + Assert.AreEqual(1, batchEndCalls); + Assert.AreEqual(2, resultSetCalls); // ... It should have executed without error ValidateBatch(batch, resultSets, false); @@ -159,7 +159,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution ValidateMessages(batch, 1, messages); } - [Fact] + [Test] public async Task BatchExecuteMultiExecutions() { // Setup: @@ -185,9 +185,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... Callbacks should have been called the appropriate number of times - Assert.Equal(1, batchStartCalls); - Assert.Equal(1, batchEndCalls); - Assert.Equal(2, resultSetCalls); + Assert.AreEqual(1, batchStartCalls); + Assert.AreEqual(1, batchEndCalls); + Assert.AreEqual(2, resultSetCalls); // ... There should be exactly two result sets ValidateBatch(batch, 2, false); @@ -196,7 +196,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution ValidateMessages(batch, 2, messages); } - [Fact] + [Test] public async Task BatchExecuteInvalidQuery() { // Setup: @@ -218,23 +218,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... Callbacks should have been called the appropriate number of times - Assert.Equal(1, batchStartCalls); - Assert.Equal(1, batchEndCalls); + Assert.AreEqual(1, batchStartCalls); + Assert.AreEqual(1, batchEndCalls); // ... It should have executed with error ValidateBatch(batch, 0, true); ValidateBatchSummary(batch); - // ... There should be one error message returned - Assert.Equal(1, messages.Count); - Assert.All(messages, m => - { - Assert.True(m.IsError); - Assert.Equal(batch.Id, m.BatchId); - }); + Assert.That(messages.Select(m => new { m.IsError, m.BatchId.Value }), Is.EqualTo(new[] { new { IsError = true, Value = batch.Id } }), "There should be one error message returned"); } - [Fact] + [Test] public async Task BatchExecuteInvalidQueryMultiExecutions() { // Setup: @@ -256,23 +250,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... Callbacks should have been called the appropriate number of times - Assert.Equal(1, batchStartCalls); - Assert.Equal(1, batchEndCalls); + Assert.AreEqual(1, batchStartCalls); + Assert.AreEqual(1, batchEndCalls); // ... It should have executed with error ValidateBatch(batch, 0, true); ValidateBatchSummary(batch); // ... There should be two error messages returned and 4 info messages (loop start/end, plus 2 for ignoring the error) - Assert.Equal(6, messages.Count); - Assert.All(messages, m => - { - Assert.Equal(batch.Id, m.BatchId); - }); - Assert.Equal(2, messages.Where(m => m.IsError).Count()); + Assert.AreEqual(6, messages.Count); + Assert.That(messages.Select(m => m.BatchId), Is.EquivalentTo(new[] { batch.Id, batch.Id, batch.Id, batch.Id, batch.Id, batch.Id })); + Assert.That(messages.Select(m => m.IsError), Has.Exactly(2).True); } - [Fact] + [Test] public async Task BatchExecuteExecuted() { // Setup: Build a data set to return @@ -296,7 +287,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution b => { throw new Exception("Batch completion callback should not have been called"); }, m => { throw new Exception("Message callback should not have been called"); }, null); - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => batch.Execute(GetConnection(ci), CancellationToken.None)); // ... The data should still be available without error @@ -304,10 +295,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution ValidateBatchSummary(batch); } - [Theory] - [InlineData("")] - [InlineData(null)] - public void BatchExecuteNoSql(string query) + [Test] + public void BatchExecuteNoSql([Values(null, "")] string query) { // If: // ... I create a batch that has an empty query @@ -316,7 +305,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution Assert.Throws(() => new Batch(query, Common.SubsectionDocument, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory())); } - [Fact] + [Test] public void BatchNoBufferFactory() { // If: @@ -326,7 +315,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution Assert.Throws(() => new Batch("stuff", Common.SubsectionDocument, Common.Ordinal, null)); } - [Fact] + [Test] public void BatchInvalidOrdinal() { // If: @@ -336,7 +325,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution Assert.Throws(() => new Batch("stuff", Common.SubsectionDocument, -1, MemoryFileSystem.GetFileStreamFactory())); } - [Fact] + [Test] public void StatementCompletedHandlerTest() { // If: @@ -357,7 +346,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution Assert.True(messageCalls == 2); } - [Fact] + [Test] public async Task ServerMessageHandlerShowsErrorMessages() { // Set up the batch to track message calls @@ -384,14 +373,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution await batch.HandleSqlErrorMessage(1, 15, 0, 1, string.Empty, errorMessage); // Then one error message call should be recorded - Assert.Equal(1, errorMessageCalls); - Assert.Equal(0, infoMessageCalls); + Assert.AreEqual(1, errorMessageCalls); + Assert.AreEqual(0, infoMessageCalls); // And the actual message should be a formatted version of the error message Assert.True(actualMessage.Length > errorMessage.Length); } - [Fact] + [Test] public async Task ServerMessageHandlerShowsInfoMessages() { // Set up the batch to track message calls @@ -418,11 +407,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution await batch.HandleSqlErrorMessage(0, 0, 0, 1, string.Empty, infoMessage); // Then one info message call should be recorded - Assert.Equal(0, errorMessageCalls); - Assert.Equal(1, infoMessageCalls); + Assert.AreEqual(0, errorMessageCalls); + Assert.AreEqual(1, infoMessageCalls); // And the actual message should be the exact info message - Assert.Equal(infoMessage, actualMessage); + Assert.AreEqual(infoMessage, actualMessage); } private static DbConnection GetConnection(ConnectionInfo info) @@ -441,15 +430,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution Assert.NotNull(batch.ResultSummaries); // Make sure the number of result sets matches - Assert.Equal(expectedResultSets, batch.ResultSets.Count); + Assert.AreEqual(expectedResultSets, batch.ResultSets.Count); for (int i = 0; i < expectedResultSets; i++) { - Assert.Equal(i, batch.ResultSets[i].Id); + Assert.AreEqual(i, batch.ResultSets[i].Id); } - Assert.Equal(expectedResultSets, batch.ResultSummaries.Length); + Assert.AreEqual(expectedResultSets, batch.ResultSummaries.Length); // Make sure that the error state is set properly - Assert.Equal(isError, batch.HasError); + Assert.AreEqual(isError, batch.HasError); } private static void ValidateBatchSummary(Batch batch) @@ -457,10 +446,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution BatchSummary batchSummary = batch.Summary; Assert.NotNull(batchSummary); - Assert.Equal(batch.Id, batchSummary.Id); - Assert.Equal(batch.ResultSets.Count, batchSummary.ResultSetSummaries.Length); - Assert.Equal(batch.Selection, batchSummary.Selection); - Assert.Equal(batch.HasError, batchSummary.HasError); + Assert.AreEqual(batch.Id, batchSummary.Id); + Assert.AreEqual(batch.ResultSets.Count, batchSummary.ResultSetSummaries.Length); + Assert.AreEqual(batch.Selection, batchSummary.Selection); + Assert.AreEqual(batch.HasError, batchSummary.HasError); // Something other than default date is provided for start and end times Assert.True(DateTime.Parse(batchSummary.ExecutionStart) > default(DateTime)); @@ -472,15 +461,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution private static void ValidateMessages(Batch batch, int expectedMessages, IList messages) { // There should be equal number of messages to result sets - Assert.Equal(expectedMessages, messages.Count); + Assert.AreEqual(expectedMessages, messages.Count); // No messages should be errors // All messages must have the batch ID - Assert.All(messages, m => - { - Assert.False(m.IsError); - Assert.Equal(batch.Id, m.BatchId); - }); + Assert.That(messages.Select(m => new { m.IsError, m.BatchId.Value }), Has.All.EqualTo(new { IsError = false, Value = batch.Id })); } private static void BatchCallbackHelper(Batch batch, Action startCallback, Action endCallback, diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/DbColumnWrapperTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/DbColumnWrapperTests.cs index 70457626..0b37ed7c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/DbColumnWrapperTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/DbColumnWrapperTests.cs @@ -5,7 +5,7 @@ using System.Data.Common; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution { @@ -55,7 +55,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution /// /// Basic data type and properties test /// - [Fact] + [Test] public void DataTypeAndPropertiesTest() { // check default constructor doesn't throw @@ -89,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution /// /// constructor test /// - [Fact] + [Test] public void DbColumnConstructorTests() { // check that various constructor parameters initial the wrapper correctly diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/QueryTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/QueryTests.cs index aabba053..34207603 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/QueryTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/QueryTests.cs @@ -12,14 +12,14 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.SqlContext; using Microsoft.SqlTools.ServiceLayer.Test.Common; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution { public class QueryTests { - [Fact] + [Test] public void QueryCreationCorrect() { // If: @@ -30,12 +30,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... I should get back two batches to execute that haven't been executed - Assert.NotEmpty(query.QueryText); + Assert.That(query.QueryText, Is.Not.Empty); Assert.False(query.HasExecuted); - Assert.Throws(() => query.BatchSummaries); + Assert.Throws(() => { var x = query.BatchSummaries; }); } - [Fact] + [Test] public void QueryExecuteNoConnectionInfo() { // If: @@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution Assert.Throws(() => new Query("Some Query", null, new QueryExecutionSettings(), MemoryFileSystem.GetFileStreamFactory())); } - [Fact] + [Test] public void QueryExecuteNoSettings() { // If: @@ -56,7 +56,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution new Query("Some query", Common.CreateTestConnectionInfo(null, false, false), null, MemoryFileSystem.GetFileStreamFactory())); } - [Fact] + [Test] public void QueryExecuteNoBufferFactory() { // If: @@ -67,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution new Query("Some query", Common.CreateTestConnectionInfo(null, false, false), new QueryExecutionSettings(), null)); } - [Fact] + [Test] public void QueryExecuteSingleBatch() { // Setup: @@ -92,21 +92,21 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... There should be exactly 1 batch - Assert.NotEmpty(query.Batches); - Assert.Equal(1, query.Batches.Length); + Assert.That(query.Batches, Is.Not.Empty); + Assert.AreEqual(1, query.Batches.Length); // ... The query should have completed successfully with one batch summary returned Assert.True(query.HasExecuted); - Assert.NotEmpty(query.BatchSummaries); - Assert.Equal(1, query.BatchSummaries.Length); + Assert.That(query.BatchSummaries, Is.Not.Empty); + Assert.AreEqual(1, query.BatchSummaries.Length); // ... The batch callbacks should have been called precisely 1 time - Assert.Equal(1, batchStartCallbacksReceived); - Assert.Equal(1, batchCompleteCallbacksReceived); - Assert.Equal(1, batchMessageCallbacksReceived); + Assert.AreEqual(1, batchStartCallbacksReceived); + Assert.AreEqual(1, batchCompleteCallbacksReceived); + Assert.AreEqual(1, batchMessageCallbacksReceived); } - [Fact] + [Test] public async Task QueryExecuteSingleNoOpBatch() { // Setup: Keep track of all the messages received @@ -129,16 +129,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... There should be no batches - Assert.Equal(1, query.Batches.Length); + Assert.AreEqual(1, query.Batches.Length); // ... The query shouldn't have completed successfully Assert.False(query.HasExecuted); // ... The message callback should have been called 0 times - Assert.Equal(0, messages.Count); + Assert.AreEqual(0, messages.Count); } - [Fact] + [Test] public void QueryExecuteMultipleResultBatches() { // Setup: @@ -165,21 +165,21 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... I should get back a query with one batch (no op batch is not included) - Assert.NotEmpty(query.Batches); - Assert.Equal(2, query.Batches.Length); + Assert.That(query.Batches, Is.Not.Empty); + Assert.AreEqual(2, query.Batches.Length); // ... The query should have completed successfully with two batch summaries returned Assert.True(query.HasExecuted); - Assert.NotEmpty(query.BatchSummaries); - Assert.Equal(2, query.BatchSummaries.Length); + Assert.That(query.BatchSummaries, Is.Not.Empty); + Assert.AreEqual(2, query.BatchSummaries.Length); // ... The batch start, complete, and message callbacks should have been called precisely 2 times - Assert.Equal(2, batchStartCallbacksReceived); - Assert.Equal(2, batchCompletedCallbacksReceived); - Assert.Equal(2, batchMessageCallbacksReceived); + Assert.AreEqual(2, batchStartCallbacksReceived); + Assert.AreEqual(2, batchCompletedCallbacksReceived); + Assert.AreEqual(2, batchMessageCallbacksReceived); } - [Fact] + [Test] public async Task QueryExecuteMultipleBatchesWithNoOp() { // Setup: @@ -205,19 +205,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... I should get back a query with two batches - Assert.NotEmpty(query.Batches); - Assert.Equal(2, query.Batches.Length); + Assert.That(query.Batches, Is.Not.Empty); + Assert.AreEqual(2, query.Batches.Length); // ... The query should have completed successfully Assert.True(query.HasExecuted); // ... The batch callbacks should have been called 2 times (for each no op batch) - Assert.Equal(2, batchStartCallbacksReceived); - Assert.Equal(2, batchCompletionCallbacksReceived); - Assert.Equal(2, batchMessageCallbacksReceived); + Assert.AreEqual(2, batchStartCallbacksReceived); + Assert.AreEqual(2, batchCompletionCallbacksReceived); + Assert.AreEqual(2, batchMessageCallbacksReceived); } - [Fact] + [Test] public async Task QueryExecuteMultipleNoOpBatches() { // Setup: @@ -241,16 +241,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... I should get back a query with no batches - Assert.Equal(2, query.Batches.Length); + Assert.AreEqual(2, query.Batches.Length); // ... The query shouldn't have completed successfully Assert.False(query.HasExecuted); // ... The message callback should have been called exactly once - Assert.Equal(0, messages.Count); + Assert.AreEqual(0, messages.Count); } - [Fact] + [Test] public void QueryExecuteInvalidBatch() { // Setup: @@ -277,18 +277,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... I should get back a query with one batch - Assert.NotEmpty(query.Batches); - Assert.Equal(1, query.Batches.Length); + Assert.That(query.Batches, Is.Not.Empty); + Assert.AreEqual(1, query.Batches.Length); // ... There should be an error on the batch Assert.True(query.HasExecuted); - Assert.NotEmpty(query.BatchSummaries); - Assert.Equal(1, query.BatchSummaries.Length); + Assert.That(query.BatchSummaries, Is.Not.Empty); + Assert.AreEqual(1, query.BatchSummaries.Length); Assert.True(messages.Any(m => m.IsError)); // ... The batch callbacks should have been called once - Assert.Equal(1, batchStartCallbacksReceived); - Assert.Equal(1, batchCompletionCallbacksReceived); + Assert.AreEqual(1, batchStartCallbacksReceived); + Assert.AreEqual(1, batchCompletionCallbacksReceived); } private static void BatchCallbackHelper(Query q, Action startCallback, Action endCallback, diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/ResultSetTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/ResultSetTests.cs index 4f4186fc..bc821edb 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/ResultSetTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/ResultSetTests.cs @@ -17,13 +17,13 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution { public class ResultSetTests { - [Fact] + [Test] public void ResultCreation() { // If: @@ -33,32 +33,32 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... There should not be any data read yet Assert.Null(resultSet.Columns); - Assert.Equal(0, resultSet.RowCount); - Assert.Equal(Common.Ordinal, resultSet.Id); + Assert.AreEqual(0, resultSet.RowCount); + Assert.AreEqual(Common.Ordinal, resultSet.Id); // ... The summary should include the same info Assert.Null(resultSet.Summary.ColumnInfo); - Assert.Equal(0, resultSet.Summary.RowCount); - Assert.Equal(Common.Ordinal, resultSet.Summary.Id); - Assert.Equal(Common.Ordinal, resultSet.Summary.BatchId); + Assert.AreEqual(0, resultSet.Summary.RowCount); + Assert.AreEqual(Common.Ordinal, resultSet.Summary.Id); + Assert.AreEqual(Common.Ordinal, resultSet.Summary.BatchId); } - [Fact] + [Test] public async Task ReadToEndNullReader() { // If: I create a new result set with a null db data reader // Then: I should get an exception var fsf = MemoryFileSystem.GetFileStreamFactory(); ResultSet resultSet = new ResultSet(Common.Ordinal, Common.Ordinal, fsf); - await Assert.ThrowsAsync(() => resultSet.ReadResultToEnd(null, CancellationToken.None)); + Assert.ThrowsAsync(() => resultSet.ReadResultToEnd(null, CancellationToken.None)); } /// /// Read to End test /// /// - [Theory] - [MemberData(nameof(ReadToEndSuccessData), parameters: 6)] + [Test] + [TestCaseSource(nameof(ReadToEndSuccessData))] public async Task ReadToEndSuccess(TestResultSet[] testDataSet) { // Setup: Create a results Available callback for result set @@ -113,13 +113,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // ... The columns should be set // ... There should be rows to read back Assert.NotNull(resultSet.Columns); - Assert.Equal(Common.StandardColumns, resultSet.Columns.Length); - Assert.Equal(testDataSet[0].Rows.Count, resultSet.RowCount); + Assert.AreEqual(Common.StandardColumns, resultSet.Columns.Length); + Assert.AreEqual(testDataSet[0].Rows.Count, resultSet.RowCount); // ... The summary should have the same info Assert.NotNull(resultSet.Summary.ColumnInfo); - Assert.Equal(Common.StandardColumns, resultSet.Summary.ColumnInfo.Length); - Assert.Equal(testDataSet[0].Rows.Count, resultSet.Summary.RowCount); + Assert.AreEqual(Common.StandardColumns, resultSet.Summary.ColumnInfo.Length); + Assert.AreEqual(testDataSet[0].Rows.Count, resultSet.Summary.RowCount); // and: // @@ -130,11 +130,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution /// Read to End test /// /// - [Theory] - [MemberData(nameof(ReadToEndSuccessData), parameters: 3)] + [Test] + [TestCaseSource(nameof(ReadToEndSuccessDataParallel))] public async Task ReadToEndSuccessSeveralTimes(TestResultSet[] testDataSet) { - const int NumberOfInvocations = 5000; + const int NumberOfInvocations = 50; List allTasks = new List(); Parallel.ForEach(Partitioner.Create(0, NumberOfInvocations), (range) => { @@ -149,21 +149,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution await Task.WhenAll(allTasks); } - public static IEnumerable ReadToEndSuccessData(int numTests) => Common.TestResultSetsEnumeration.Select(r => new object[] { new TestResultSet[] { r } }).Take(numTests); + public static readonly IEnumerable ReadToEndSuccessData = Common.TestResultSetsEnumeration.Select(r => new object[] { new TestResultSet[] { r } }).Take(6); + // using all 6 sets with the parallel test can raise an OutOfMemoryException + public static readonly IEnumerable ReadToEndSuccessDataParallel = Common.TestResultSetsEnumeration.Select(r => new object[] { new TestResultSet[] { r } }).Take(3); - [Theory] - [MemberData(nameof(CallMethodWithoutReadingData))] + [Test] + [TestCaseSource(nameof(CallMethodWithoutReadingData))] public void CallMethodWithoutReading(Action testMethod) { // Setup: Create a new result set with valid db data reader var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); ResultSet resultSet = new ResultSet(Common.Ordinal, Common.Ordinal, fileStreamFactory); - - // If: - // ... I have a result set that has not been read - // ... and I attempt to call a method on it - // Then: It should throw an exception - Assert.ThrowsAny(() => testMethod(resultSet)); + Assert.That(() => testMethod(resultSet), Throws.InstanceOf(), "I have a result set that has not been read. I attempt to call a method on it. It should throw an exception"); } public static IEnumerable CallMethodWithoutReadingData @@ -239,10 +236,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution /// /// /// - [Theory] - [InlineData("JSON")] - [InlineData("XML")] - public async Task ReadToEndForXmlJson(string forType) + [Test] + public async Task ReadToEndForXmlJson([Values("JSON", "XML")] string forType) { // Setup: // ... Build a FOR XML or FOR JSON data set @@ -306,8 +301,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // ... There should only be one column // ... There should only be one row // - Assert.Equal(1, resultSet.Columns.Length); - Assert.Equal(1, resultSet.RowCount); + Assert.AreEqual(1, resultSet.Columns.Length); + Assert.AreEqual(1, resultSet.RowCount); // and: @@ -322,14 +317,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution var task = resultSet.GetSubset(0, 10); task.Wait(); var subset = task.Result; - Assert.Equal(1, subset.RowCount); + Assert.AreEqual(1, subset.RowCount); } - [Theory] - [InlineData(-1, 0)] // Too small start row - [InlineData(20, 0)] // Too large start row - [InlineData(0, -1)] // Negative row count - public async Task GetSubsetInvalidParameters(int startRow, int rowCount) + [Test, Sequential] + public async Task GetSubsetInvalidParameters([Values(-1,20,0)] int startRow, + [Values(0,0,-1)] int rowCount) { // If: // ... I create a new result set with a valid db data reader @@ -342,15 +335,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // ... And attempt to get a subset with invalid parameters // Then: // ... It should throw an exception for an invalid parameter - await Assert.ThrowsAsync(() => resultSet.GetSubset(startRow, rowCount)); + Assert.ThrowsAsync(() => resultSet.GetSubset(startRow, rowCount)); } - [Theory] - [InlineData(0, 3)] // Standard scenario, 3 rows should come back - [InlineData(0, 20)] // Asking for too many rows, 5 rows should come back - [InlineData(1, 3)] // Asking for proper subset of rows from non-zero start - [InlineData(1, 20)] // Asking for too many rows at a non-zero start - public async Task GetSubsetSuccess(int startRow, int rowCount) + [Test] + public async Task GetSubsetSuccess([Values(0,1)]int startRow, + [Values(3,20)] int rowCount) { // If: // ... I create a new result set with a valid db data reader @@ -365,20 +355,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... rows sub-array and RowCount field of the subset should match - Assert.Equal(subset.RowCount, subset.Rows.Length); + Assert.AreEqual(subset.RowCount, subset.Rows.Length); // Then: // ... There should be rows in the subset, either the number of rows or the number of // rows requested or the number of rows in the result set, whichever is lower long availableRowsFromStart = resultSet.RowCount - startRow; - Assert.Equal(Math.Min(availableRowsFromStart, rowCount), subset.RowCount); + Assert.AreEqual(Math.Min(availableRowsFromStart, rowCount), subset.RowCount); // ... The rows should have the same number of columns as the resultset - Assert.Equal(resultSet.Columns.Length, subset.Rows[0].Length); + Assert.AreEqual(resultSet.Columns.Length, subset.Rows[0].Length); } - [Theory] - [MemberData(nameof(RowInvalidParameterData))] + [Test] + [TestCaseSource(nameof(RowInvalidParameterData))] public async Task RowInvalidParameter(Action actionToPerform) { // If: I create a new result set and execute it @@ -387,8 +377,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution ResultSet resultSet = new ResultSet(Common.Ordinal, Common.Ordinal, fileStreamFactory); await resultSet.ReadResultToEnd(mockReader, CancellationToken.None); - // Then: Attempting to read an invalid row should fail - Assert.ThrowsAny(() => actionToPerform(resultSet)); + Assert.That(() => actionToPerform(resultSet), Throws.InstanceOf(), "Attempting to read an invalid row should fail"); } public static IEnumerable RowInvalidParameterData @@ -413,7 +402,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution } } - [Fact] + [Test] public async Task RemoveRowSuccess() { // Setup: Create a result set that has the standard data set on it @@ -428,11 +417,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... The row count should decrease // ... The last row should have moved up by 1 - Assert.Equal(Common.StandardRows - 1, resultSet.RowCount); + Assert.AreEqual(Common.StandardRows - 1, resultSet.RowCount); Assert.Throws(() => resultSet.GetRow(Common.StandardRows - 1)); } - [Fact] + [Test] public async Task AddRowNoRows() { // Setup: @@ -448,13 +437,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // If: I add a row with a reader that has no rows // Then: // ... I should get an exception - await Assert.ThrowsAsync(() => resultSet.AddRow(emptyReader)); + Assert.ThrowsAsync(() => resultSet.AddRow(emptyReader)); // ... The row count should not have changed - Assert.Equal(Common.StandardRows, resultSet.RowCount); + Assert.AreEqual(Common.StandardRows, resultSet.RowCount); } - [Fact] + [Test] public async Task AddRowThrowsOnRead() { // Setup: @@ -467,16 +456,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // ... Create a mock reader that will throw on read var throwingReader = GetReader(new[] {new TestResultSet(5, 0)}, true, Constants.StandardQuery); - // If: I add a row with a reader that throws on read - // Then: - // ... I should get an exception - await Assert.ThrowsAnyAsync(() => resultSet.AddRow(throwingReader)); - - // ... The row count should not have changed - Assert.Equal(Common.StandardRows, resultSet.RowCount); + Assert.ThrowsAsync(() => resultSet.AddRow(throwingReader), "I add a row with a reader that throws on read. I should get an exception"); + + // ... The row count should not have changed + Assert.AreEqual(Common.StandardRows, resultSet.RowCount); } - [Fact] + [Test] public async Task AddRowSuccess() { // Setup: @@ -497,13 +483,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... There should be a new row in the list of rows - Assert.Equal(Common.StandardRows + 1, resultSet.RowCount); + Assert.AreEqual(Common.StandardRows + 1, resultSet.RowCount); - // ... The new row should be readable and all cells contain the test value - Assert.All(resultSet.GetRow(Common.StandardRows), cell => Assert.Equal("QQQ", cell.RawObject)); + Assert.That(resultSet.GetRow(Common.StandardRows).Select(r => r.RawObject), Has.All.EqualTo("QQQ"), "The new row should be readable and all cells contain the test value"); } - [Fact] + [Test] public async Task UpdateRowNoRows() { // Setup: @@ -519,13 +504,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // If: I add a row with a reader that has no rows // Then: // ... I should get an exception - await Assert.ThrowsAsync(() => resultSet.UpdateRow(0, emptyReader)); + Assert.ThrowsAsync(() => resultSet.UpdateRow(0, emptyReader)); // ... The row count should not have changed - Assert.Equal(Common.StandardRows, resultSet.RowCount); + Assert.AreEqual(Common.StandardRows, resultSet.RowCount); } - [Fact] + [Test] public async Task UpdateRowSuccess() { // Setup: @@ -546,10 +531,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // Then: // ... There should be the same number of rows - Assert.Equal(Common.StandardRows, resultSet.RowCount); + Assert.AreEqual(Common.StandardRows, resultSet.RowCount); - // ... The new row should be readable and all cells contain the test value - Assert.All(resultSet.GetRow(0), cell => Assert.Equal("QQQ", cell.RawObject)); + Assert.That(resultSet.GetRow(0).Select(c => c.RawObject), Has.All.EqualTo("QQQ"), "The new row should be readable and all cells contain the test value"); } private static DbDataReader GetReader(TestResultSet[] dataSet, bool throwOnRead, string query) diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/ServiceIntegrationTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/ServiceIntegrationTests.cs index 9c8758f9..d2cc03e1 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/ServiceIntegrationTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/Execution/ServiceIntegrationTests.cs @@ -20,8 +20,6 @@ using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.Workspace; using Moq; using NUnit.Framework; -using Xunit; -using Assert = Xunit.Assert; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution { @@ -30,7 +28,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution #region Get SQL Tests - [Fact] + [Test] public void ExecuteDocumentStatementTest() { string query = string.Format("{0}{1}GO{1}{0}", Constants.StandardQuery, Environment.NewLine); @@ -41,10 +39,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution var queryText = queryService.GetSqlText(queryParams); // The text should match the standard query - Assert.Equal(queryText, Constants.StandardQuery); + Assert.AreEqual(queryText, Constants.StandardQuery); } - [Fact] + [Test] public void ExecuteDocumentStatementSameLine() { var statement1 = Constants.StandardQuery; @@ -72,10 +70,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution var queryText = queryService.GetSqlText(queryParams); // The query text should match the expected statement at the cursor - Assert.Equal(expectedQueryText, queryText); + Assert.AreEqual(expectedQueryText, queryText); } - [Fact] + [Test] public void GetSqlTextFromDocumentRequestFull() { // Setup: @@ -91,10 +89,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution var queryText = queryService.GetSqlText(queryParams); // Then: The text should match the constructed query - Assert.Equal(query, queryText); + Assert.AreEqual(query, queryText); } - [Fact] + [Test] public void GetSqlTextFromDocumentRequestPartial() { // Setup: @@ -107,11 +105,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.SubsectionDocument }; var queryText = queryService.GetSqlText(queryParams); - // Then: The text should be a subset of the constructed query - Assert.Contains(queryText, query); + Assert.That(query, Does.Contain(queryText), "The text should be a subset of the constructed query"); } - [Fact] + [Test] public void GetSqlTextFromStringRequest() { // Setup: @@ -124,10 +121,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution var queryText = queryService.GetSqlText(queryParams); // Then: The text should match the standard query - Assert.Equal(Constants.StandardQuery, queryText); + Assert.AreEqual(Constants.StandardQuery, queryText); } - [Fact] + [Test] public void GetSqlTextFromInvalidType() { // Setup: @@ -146,7 +143,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution #region Inter-Service API Tests - [Fact] + [Test] public async Task InterServiceExecuteNullExecuteParams() { // Setup: Create a query service @@ -156,11 +153,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // If: I call the inter-service API to execute with a null execute params // Then: It should throw - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => qes.InterServiceExecuteQuery(null, null, eventSender, null, null, null, null)); } - [Fact] + [Test] public async Task InterServiceExecuteNullEventSender() { // Setup: Create a query service, and execute params @@ -169,11 +166,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // If: I call the inter-service API to execute a query with a a null event sender // Then: It should throw - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => qes.InterServiceExecuteQuery(executeParams, null, null, null, null, null, null)); } - [Fact] + [Test] public async Task InterServiceDisposeNullSuccessFunc() { // Setup: Create a query service and dispose params @@ -182,11 +179,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // If: I call the inter-service API to dispose a query with a null success function // Then: It should throw - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => qes.InterServiceDisposeQuery(Constants.OwnerUri, null, failureFunc)); } - [Fact] + [Test] public async Task InterServiceDisposeNullFailureFunc() { // Setup: Create a query service and dispose params @@ -195,7 +192,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // If: I call the inter-service API to dispose a query with a null success function // Then: It should throw - await Assert.ThrowsAsync( + Assert.ThrowsAsync( () => qes.InterServiceDisposeQuery(Constants.OwnerUri, successFunc, null)); } @@ -205,8 +202,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution // NOTE: In order to limit test duplication, we're running the ExecuteDocumentSelection // version of execute query. The code paths are almost identical. - [Fact] - private async Task QueryExecuteAllBatchesNoOp() + [Test] + public async Task QueryExecuteAllBatchesNoOp() { // If: // ... I request to execute a valid query with all batches as no op @@ -225,10 +222,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution .AddEventValidation(QueryCompleteEvent.Type, p => { // Validate OwnerURI matches - Assert.Equal(Constants.OwnerUri, p.OwnerUri); + Assert.AreEqual(Constants.OwnerUri, p.OwnerUri); Assert.NotNull(p.BatchSummaries); - Assert.Equal(2, p.BatchSummaries.Length); - Assert.All(p.BatchSummaries, bs => Assert.Equal(0, bs.ResultSetSummaries.Length)); + Assert.AreEqual(2, p.BatchSummaries.Length); + Assert.That(p.BatchSummaries.Select(s => s.ResultSetSummaries.Length), Has.All.EqualTo(0)); }).Complete(); await Common.AwaitExecution(queryService, queryParams, efv.Object); @@ -237,10 +234,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.Validate(); // ... There should be one active query - Assert.Equal(1, queryService.ActiveQueries.Count); + Assert.AreEqual(1, queryService.ActiveQueries.Count); } - [Fact] + [Test] public async Task QueryExecuteSingleBatchNoResultsTest() { // If: @@ -264,13 +261,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.Validate(); // ... There should be one active query - Assert.Equal(1, queryService.ActiveQueries.Count); + Assert.AreEqual(1, queryService.ActiveQueries.Count); } - public static IEnumerable TestResultSetsData(int numTests) => Common.TestResultSetsEnumeration.Select(r => new object[] { r }).Take(numTests); + private static readonly IEnumerable TestResultSetsData = Common.TestResultSetsEnumeration.Select(r => new object[] { r }).Take(5); - [Xunit.Theory] - [MemberData(nameof(TestResultSetsData), parameters: 5)] + [Test] + [TestCaseSource(nameof(TestResultSetsData))] public async Task QueryExecuteSingleBatchSingleResultTest(TestResultSet testResultSet) { // If: @@ -298,11 +295,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.ValidateResultSetSummaries(collectedResultSetEventParams).Validate(); // ... There should be one active query - Assert.Equal(1, queryService.ActiveQueries.Count); + Assert.AreEqual(1, queryService.ActiveQueries.Count); } - [Xunit.Theory] - [MemberData(nameof(TestResultSetsData), parameters: 4)] + [Test] + [TestCaseSource(nameof(TestResultSetsData))] public async Task QueryExecuteSingleBatchMultipleResultTest(TestResultSet testResultSet) { // If: @@ -329,10 +326,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.ValidateResultSetSummaries(collectedResultSetEventParams).Validate(); // ... There should be one active query - Assert.Equal(1, queryService.ActiveQueries.Count); + Assert.AreEqual(1, queryService.ActiveQueries.Count); } - [Fact] + [Test] public async Task QueryExecuteMultipleBatchSingleResultTest() { // If: @@ -362,10 +359,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.ValidateResultSetSummaries(collectedResultSetEventParams).Validate(); // ... There should be one active query - Assert.Equal(1, queryService.ActiveQueries.Count); + Assert.AreEqual(1, queryService.ActiveQueries.Count); } - [Fact] + [Test] public async Task QueryExecuteUnconnectedUriTest() { // Given: @@ -385,10 +382,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.Validate(); // ... There should be no active queries - Assert.Empty(queryService.ActiveQueries); + Assert.That(queryService.ActiveQueries, Is.Empty); } - [Fact] + [Test] public async Task QueryExecuteInProgressTest() { // If: @@ -413,10 +410,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.Validate(); // ... There should only be one active query - Assert.Equal(1, queryService.ActiveQueries.Count); + Assert.AreEqual(1, queryService.ActiveQueries.Count); } - [Fact] + [Test] public async Task QueryExecuteCompletedTest() { // If: @@ -445,10 +442,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.Validate(); // ... There should only be one active query - Assert.Equal(1, queryService.ActiveQueries.Count); + Assert.AreEqual(1, queryService.ActiveQueries.Count); } - [Fact] + [Test] public async Task QueryExecuteInvalidQueryTest() { // If: @@ -471,11 +468,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.Validate(); // ... There should not be an active query - Assert.Equal(1, queryService.ActiveQueries.Count); + Assert.AreEqual(1, queryService.ActiveQueries.Count); } // TODO https://github.com/Microsoft/vscode-mssql/issues/1003 reenable and make non-flaky - // [Fact] + // [Test] public async Task SimpleExecuteErrorWithNoResultsTest() { var queryService = Common.GetPrimedExecutionService(null, true, false, false, null); @@ -493,12 +490,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.Validate(); - Assert.Equal(0, queryService.ActiveQueries.Count); + Assert.AreEqual(0, queryService.ActiveQueries.Count); } // TODO reenable and make non-flaky - // [Fact] + // [Test] public async Task SimpleExecuteVerifyResultsTest() { var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, null); @@ -519,10 +516,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv.Validate(); - Assert.Equal(0, queryService.ActiveQueries.Count); + Assert.AreEqual(0, queryService.ActiveQueries.Count); } - [Fact] + [Test] public async Task SimpleExecuteMultipleQueriesTest() { var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, false, null); @@ -548,7 +545,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution efv1.Validate(); efv2.Validate(); - Assert.Equal(0, queryService.ActiveQueries.Count); + Assert.AreEqual(0, queryService.ActiveQueries.Count); } #endregion @@ -569,7 +566,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution { return efv.AddResultValidation(p => { - Assert.Equal(p.RowCount, testData[0].Rows.Count); + Assert.AreEqual(p.RowCount, testData[0].Rows.Count); }); } @@ -578,7 +575,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution { return efv.AddSimpleErrorValidation((m, e) => { - Assert.Equal(m, expectedMessage); + Assert.AreEqual(m, expectedMessage); }); } @@ -595,7 +592,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution return efv.AddEventValidation(BatchStartEvent.Type, p => { // Validate OwnerURI and batch summary is returned - Assert.Equal(Constants.OwnerUri, p.OwnerUri); + Assert.AreEqual(Constants.OwnerUri, p.OwnerUri); Assert.NotNull(p.BatchSummary); }); } @@ -606,7 +603,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution return efv.AddEventValidation(BatchCompleteEvent.Type, p => { // Validate OwnerURI and result summary are returned - Assert.Equal(Constants.OwnerUri, p.OwnerUri); + Assert.AreEqual(Constants.OwnerUri, p.OwnerUri); Assert.NotNull(p.BatchSummary); }); } @@ -617,7 +614,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution return efv.AddEventValidation(MessageEvent.Type, p => { // Validate OwnerURI and message are returned - Assert.Equal(Constants.OwnerUri, p.OwnerUri); + Assert.AreEqual(Constants.OwnerUri, p.OwnerUri); Assert.NotNull(p.Message); }); } @@ -628,7 +625,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution return efv.SetupCallbackOnMethodSendEvent(expectedEvent, (p) => { // Validate OwnerURI and summary are returned - Assert.Equal(Constants.OwnerUri, p.OwnerUri); + Assert.AreEqual(Constants.OwnerUri, p.OwnerUri); Assert.NotNull(p.ResultSetSummary); resultSetEventParamList?.Add(p); }); @@ -768,9 +765,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution { return efv.AddEventValidation(QueryCompleteEvent.Type, p => { - Assert.Equal(Constants.OwnerUri, p.OwnerUri); + Assert.AreEqual(Constants.OwnerUri, p.OwnerUri); Assert.NotNull(p.BatchSummaries); - Assert.Equal(expectedBatches, p.BatchSummaries.Length); + Assert.AreEqual(expectedBatches, p.BatchSummaries.Length); }); } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/ExecutionPlanTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/ExecutionPlanTests.cs index d8f53a07..305d4022 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/ExecutionPlanTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/ExecutionPlanTests.cs @@ -13,7 +13,7 @@ using Microsoft.SqlTools.ServiceLayer.SqlContext; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution { @@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution { #region ResultSet Class Tests - [Fact] + [Test] public void ExecutionPlanValid() { // Setup: @@ -32,14 +32,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // ... I have a result set and I ask for a valid execution plan ResultSet planResultSet = b.ResultSets.First(); ExecutionPlan plan = planResultSet.GetExecutionPlan().Result; - - // Then: - // ... I should get the execution plan back - Assert.Equal("xml", plan.Format); - Assert.Contains("Execution Plan", plan.Content); + Assert.AreEqual("xml", plan.Format); + Assert.That(plan.Content, Does.Contain("Execution Plan"), "I should get the execution plan back"); } - [Fact] + [Test] public async Task ExecutionPlanInvalid() { // Setup: @@ -52,14 +49,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... It should throw an exception - await Assert.ThrowsAsync(() => planResultSet.GetExecutionPlan()); + Assert.ThrowsAsync(() => planResultSet.GetExecutionPlan()); } #endregion #region Batch Class Tests - [Fact] + [Test] public void BatchExecutionPlanValidTest() { // If I have an executed batch which has an execution plan @@ -68,13 +65,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // ... And I ask for a valid execution plan ExecutionPlan plan = b.GetExecutionPlan(0).Result; - // Then: - // ... I should get the execution plan back - Assert.Equal("xml", plan.Format); - Assert.Contains("Execution Plan", plan.Content); + Assert.AreEqual("xml", plan.Format); + Assert.That(plan.Content, Does.Contain("Execution Plan"), "I should get the execution plan back"); } - [Fact] + [Test] public async Task BatchExecutionPlanInvalidTest() { // Setup: @@ -83,13 +78,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // If: // ... I ask for an invalid execution plan - await Assert.ThrowsAsync(() => b.GetExecutionPlan(0)); + Assert.ThrowsAsync(() => b.GetExecutionPlan(0)); } - [Theory] - [InlineData(-1)] // Invalid result set, too low - [InlineData(2)] // Invalid result set, too high - public async Task BatchExecutionPlanInvalidParamsTest(int resultSetIndex) + [Test] + public async Task BatchExecutionPlanInvalidParamsTest([Values(-1,2)] int resultSetIndex) { // If I have an executed batch which has an execution plan Batch b = Common.GetExecutedBatchWithExecutionPlan(); @@ -97,17 +90,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // ... And I ask for an execution plan with an invalid result set index // Then: // ... It should throw an exception - await Assert.ThrowsAsync(() => b.GetExecutionPlan(resultSetIndex)); + Assert.ThrowsAsync(() => b.GetExecutionPlan(resultSetIndex)); } #endregion #region Query Class Tests - [Theory] - [InlineData(-1)] // Invalid batch, too low - [InlineData(2)] // Invalid batch, too high - public async Task QueryExecutionPlanInvalidParamsTest(int batchIndex) + [Test] + public async Task QueryExecutionPlanInvalidParamsTest([Values(-1,2)]int batchIndex) { // Setup query settings QueryExecutionSettings querySettings = new QueryExecutionSettings @@ -125,7 +116,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // ... And I ask for a subset with an invalid result set index // Then: // ... It should throw an exception - await Assert.ThrowsAsync(() => q.GetExecutionPlan(batchIndex, 0)); + Assert.ThrowsAsync(() => q.GetExecutionPlan(batchIndex, 0)); } #endregion @@ -133,7 +124,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution #region Service Intergration Tests - [Fact] + [Test] public async Task ExecutionPlanServiceValidTest() { // If: @@ -168,7 +159,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution } - [Fact] + [Test] public async Task ExecutionPlanServiceMissingQueryTest() { // If: @@ -183,7 +174,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution executionPlanRequest.Validate(); } - [Fact] + [Test] public async Task ExecutionPlanServiceUnexecutedQueryTest() { // If: @@ -215,7 +206,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution executionPlanRequest.Validate(); } - [Fact] + [Test] public async Task ExecutionPlanServiceOutOfRangeSubsetTest() { // If: diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/BatchTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/BatchTests.cs index 296b76d6..79670f1e 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/BatchTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/BatchTests.cs @@ -6,16 +6,14 @@ using System; using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults { public class BatchTests { - [Theory] - [InlineData(-1)] - [InlineData(100)] - public void SaveAsFailsOutOfRangeResultSet(int resultSetIndex) + [Test] + public void SaveAsFailsOutOfRangeResultSet([Values(-1,100)] int resultSetIndex) { // If: I attempt to save results for an invalid result set index // Then: I should get an ArgumentOutOfRange exception diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/QueryTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/QueryTests.cs index 2c254aa2..4c144bd6 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/QueryTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/QueryTests.cs @@ -6,16 +6,14 @@ using System; using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults { public class QueryTests { - [Theory] - [InlineData(-1)] - [InlineData(100)] - public void SaveAsFailsOutOfRangeBatch(int batchIndex) + [Test] + public void SaveAsFailsOutOfRangeBatch([Values(-1,100)] int batchIndex) { // If: I save a basic query's results with out of range batch index // Then: I should get an out of range exception diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/ResultSetTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/ResultSetTests.cs index bf7deb48..87b5737d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/ResultSetTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/ResultSetTests.cs @@ -15,13 +15,13 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults { public class ResultSetTests { - [Fact] + [Test] public void SaveAsNullParams() { // If: I attempt to save with a null set of params @@ -35,7 +35,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults null, null)); } - [Fact] + [Test] public void SaveAsNullFactory() { // If: I attempt to save with a null set of params @@ -48,7 +48,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults null, null, null)); } - [Fact] + [Test] public void SaveAsFailedIncomplete() { // If: I attempt to save a result set that hasn't completed execution @@ -62,7 +62,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults null, null)); } - [Fact] + [Test] public void SaveAsFailedExistingTaskInProgress() { // Setup: @@ -82,7 +82,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults null, null)); } - [Fact] + [Test] public async Task SaveAsWithoutRowSelection() { // Setup: @@ -106,7 +106,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults // Then: // ... The task should have completed successfully - Assert.Equal(TaskStatus.RanToCompletion, rs.SaveTasks[Constants.OwnerUri].Status); + Assert.AreEqual(TaskStatus.RanToCompletion, rs.SaveTasks[Constants.OwnerUri].Status); // ... All the rows should have been written successfully saveWriter.Verify( @@ -114,7 +114,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults Times.Exactly(Common.StandardRows)); } - [Fact] + [Test] public async Task SaveAsWithRowSelection() { // Setup: @@ -146,7 +146,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults // Then: // ... The task should have completed successfully - Assert.Equal(TaskStatus.RanToCompletion, rs.SaveTasks[Constants.OwnerUri].Status); + Assert.AreEqual(TaskStatus.RanToCompletion, rs.SaveTasks[Constants.OwnerUri].Status); // ... All the rows should have been written successfully saveWriter.Verify( diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/SerializationServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/SerializationServiceTests.cs index b156d2f2..980137c5 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/SerializationServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/SerializationServiceTests.cs @@ -17,7 +17,7 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Moq; using Newtonsoft.Json; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults { @@ -60,13 +60,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults protected Mock HostMock { get; private set; } protected SerializationService SerializationService { get; private set; } - [Fact] + [Test] public async Task SaveResultsAsCsvNoHeaderSuccess() { await TestSaveAsCsvSuccess(false); } - [Fact] + [Test] public async Task SaveResultsAsCsvWithHeaderSuccess() { await TestSaveAsCsvSuccess(true); @@ -102,13 +102,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults }); } - [Fact] + [Test] public async Task SaveResultsAsCsvNoHeaderMultiRequestSuccess() { await TestSaveAsCsvMultiRequestSuccess(false); } - [Fact] + [Test] public async Task SaveResultsAsCsvWithHeaderMultiRequestSuccess() { await TestSaveAsCsvMultiRequestSuccess(true); @@ -125,8 +125,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults await this.TestSerializeDataMultiRequestSuccess(setParams, validation); } - [Fact] - private async Task SaveAsJsonMultiRequestSuccess() + [Test] + public async Task SaveAsJsonMultiRequestSuccess() { Action setParams = (serializeParams) => { serializeParams.SaveFormat = "json"; @@ -137,8 +137,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults await this.TestSerializeDataMultiRequestSuccess(setParams, validation); } - [Fact] - private async Task SaveAsXmlMultiRequestSuccess() + [Test] + public async Task SaveAsXmlMultiRequestSuccess() { Action setParams = (serializeParams) => { serializeParams.SaveFormat = "xml"; @@ -239,7 +239,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults Assert.True(File.Exists(filePath), "Expected file to have been written"); string[] lines = File.ReadAllLines(filePath); int expectedLength = includeHeaders ? data.Length + 1 : data.Length; - Assert.Equal(expectedLength, lines.Length); + Assert.AreEqual(expectedLength, lines.Length); int lineIndex = 0; if (includeHeaders) { @@ -278,18 +278,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults // ... There should be 2 items in the array, // ... The item should have three fields, and three values, assigned appropriately // ... The deserialized values should match the display value - Assert.Equal(data.Length, outputObject.Length); + Assert.AreEqual(data.Length, outputObject.Length); for (int rowIndex = 0; rowIndex < outputObject.Length; rowIndex++) { Dictionary item = outputObject[rowIndex]; - Assert.Equal(columns.Length, item.Count); + Assert.AreEqual(columns.Length, item.Count); for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++) { var key = columns[columnIndex].Name; Assert.True(item.ContainsKey(key)); DbCellValue value = data[rowIndex][columnIndex]; object expectedValue = GetJsonExpectedValue(value, columns[columnIndex]); - Assert.Equal(expectedValue, item[key]); + Assert.AreEqual(expectedValue, item[key]); } } } @@ -325,12 +325,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults string xpath = "data/row"; var rows = xmlDoc.SelectNodes(xpath); - Assert.Equal(data.Length, rows.Count); + Assert.AreEqual(data.Length, rows.Count); for (int rowIndex = 0; rowIndex < rows.Count; rowIndex++) { var rowValue = rows.Item(rowIndex); var xmlCols = rowValue.ChildNodes.Cast().ToArray(); - Assert.Equal(columns.Length, xmlCols.Length); + Assert.AreEqual(columns.Length, xmlCols.Length); for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++) { var columnName = columns[columnIndex].Name; @@ -338,7 +338,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults Assert.NotNull(xmlColumn); DbCellValue value = data[rowIndex][columnIndex]; object expectedValue = GetXmlExpectedValue(value); - Assert.Equal(expectedValue, xmlColumn.InnerText); + Assert.AreEqual(expectedValue, xmlColumn.InnerText); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/ServiceIntegrationTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/ServiceIntegrationTests.cs index 8969ba58..50fe8bfe 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/ServiceIntegrationTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SaveResults/ServiceIntegrationTests.cs @@ -17,7 +17,7 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.Workspace; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults { @@ -25,7 +25,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults { #region CSV Tests - [Fact] + [Test] public async Task SaveResultsCsvNonExistentQuery() { // Given: A working query and workspace service @@ -48,7 +48,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults evf.Validate(); } - [Fact] + [Test] public async Task SaveResultAsCsvFailure() { // Given: @@ -94,7 +94,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults efv.Validate(); } - [Fact] + [Test] public async Task SaveResultsAsCsvSuccess() { // Given: @@ -139,7 +139,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults #region JSON tests - [Fact] + [Test] public async Task SaveResultsJsonNonExistentQuery() { // Given: A working query and workspace service @@ -162,7 +162,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults efv.Validate(); } - [Fact] + [Test] public async Task SaveResultAsJsonFailure() { // Given: @@ -206,7 +206,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults efv.Validate(); } - [Fact] + [Test] public async Task SaveResultsAsJsonSuccess() { // Given: @@ -250,7 +250,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults #region XML tests - [Fact] + [Test] public async Task SaveResultsXmlNonExistentQuery() { // Given: A working query and workspace service @@ -273,7 +273,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults efv.Validate(); } - [Fact] + [Test] public async Task SaveResultAsXmlFailure() { // Given: @@ -317,7 +317,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults efv.Validate(); } - [Fact] + [Test] public async Task SaveResultsAsXmlSuccess() { // Given: @@ -363,7 +363,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults #region Excel Tests - [Fact] + [Test] public async Task SaveResultsExcelNonExistentQuery() { // Given: A working query and workspace service @@ -386,7 +386,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults efv.Validate(); } - [Fact] + [Test] public async Task SaveResultAsExcelFailure() { // Given: @@ -430,7 +430,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults efv.Validate(); } - [Fact] + [Test] public async Task SaveResultsAsExcelSuccess() { // Given: diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SettingsTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SettingsTests.cs index e892ef64..9f6f15c4 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SettingsTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SettingsTests.cs @@ -8,28 +8,28 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.SqlContext; using Newtonsoft.Json.Linq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution { public class SettingsTests { - [Fact] + [Test] public void ValidateQueryExecuteDefaults() { // If: I create a new settings object var sqlToolsSettings = new SqlToolsSettings(); // Then: The default values should be as expected - Assert.Equal("GO", sqlToolsSettings.QueryExecutionSettings.BatchSeparator); - Assert.Equal(ushort.MaxValue, sqlToolsSettings.QueryExecutionSettings.MaxCharsToStore); - Assert.Equal(2*1024*1024, sqlToolsSettings.QueryExecutionSettings.MaxXmlCharsToStore); + Assert.AreEqual("GO", sqlToolsSettings.QueryExecutionSettings.BatchSeparator); + Assert.AreEqual(ushort.MaxValue, sqlToolsSettings.QueryExecutionSettings.MaxCharsToStore); + Assert.AreEqual(2*1024*1024, sqlToolsSettings.QueryExecutionSettings.MaxXmlCharsToStore); Assert.False(sqlToolsSettings.QueryExecutionSettings.ExecutionPlanOptions.IncludeActualExecutionPlanXml); Assert.False(sqlToolsSettings.QueryExecutionSettings.ExecutionPlanOptions.IncludeEstimatedExecutionPlanXml); Assert.True(sqlToolsSettings.QueryExecutionSettings.DisplayBitAsNumber); } - [Fact] + [Test] public void ValidateSettingsParsedFromJson() { ValidateSettings("mssql"); @@ -59,7 +59,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution Assert.False(sqlToolsSettings.QueryExecutionSettings.DisplayBitAsNumber); } - [Fact] + [Test] public void ValidateSettingsObjectUpdates() { // If: I update a settings object with a new settings object @@ -110,13 +110,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution Assert.False(qes.Settings.QueryExecutionSettings.DisplayBitAsNumber); Assert.True(qes.Settings.QueryExecutionSettings.ExecutionPlanOptions.IncludeActualExecutionPlanXml); Assert.True(qes.Settings.QueryExecutionSettings.ExecutionPlanOptions.IncludeEstimatedExecutionPlanXml); - Assert.Equal(1, qes.Settings.QueryExecutionSettings.MaxCharsToStore); - Assert.Equal(1, qes.Settings.QueryExecutionSettings.MaxXmlCharsToStore); - Assert.Equal("YO", qes.Settings.QueryExecutionSettings.BatchSeparator); - Assert.Equal(1, qes.Settings.QueryExecutionSettings.MaxCharsToStore); - Assert.Equal(0, qes.Settings.QueryExecutionSettings.RowCount); - Assert.Equal(1000, qes.Settings.QueryExecutionSettings.TextSize); - Assert.Equal(5000, qes.Settings.QueryExecutionSettings.ExecutionTimeout); + Assert.AreEqual(1, qes.Settings.QueryExecutionSettings.MaxCharsToStore); + Assert.AreEqual(1, qes.Settings.QueryExecutionSettings.MaxXmlCharsToStore); + Assert.AreEqual("YO", qes.Settings.QueryExecutionSettings.BatchSeparator); + Assert.AreEqual(1, qes.Settings.QueryExecutionSettings.MaxCharsToStore); + Assert.AreEqual(0, qes.Settings.QueryExecutionSettings.RowCount); + Assert.AreEqual(1000, qes.Settings.QueryExecutionSettings.TextSize); + Assert.AreEqual(5000, qes.Settings.QueryExecutionSettings.ExecutionTimeout); Assert.True(qes.Settings.QueryExecutionSettings.NoCount); Assert.True(qes.Settings.QueryExecutionSettings.NoExec); Assert.True(qes.Settings.QueryExecutionSettings.ParseOnly); @@ -124,10 +124,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution Assert.True(qes.Settings.QueryExecutionSettings.StatisticsTime); Assert.True(qes.Settings.QueryExecutionSettings.StatisticsIO); Assert.True(qes.Settings.QueryExecutionSettings.XactAbortOn); - Assert.Equal("REPEATABLE READ", qes.Settings.QueryExecutionSettings.TransactionIsolationLevel); - Assert.Equal("LOW", qes.Settings.QueryExecutionSettings.DeadlockPriority); - Assert.Equal(5000, qes.Settings.QueryExecutionSettings.LockTimeout); - Assert.Equal(2000, qes.Settings.QueryExecutionSettings.QueryGovernorCostLimit); + Assert.AreEqual("REPEATABLE READ", qes.Settings.QueryExecutionSettings.TransactionIsolationLevel); + Assert.AreEqual("LOW", qes.Settings.QueryExecutionSettings.DeadlockPriority); + Assert.AreEqual(5000, qes.Settings.QueryExecutionSettings.LockTimeout); + Assert.AreEqual(2000, qes.Settings.QueryExecutionSettings.QueryGovernorCostLimit); Assert.False(qes.Settings.QueryExecutionSettings.AnsiDefaults); Assert.True(qes.Settings.QueryExecutionSettings.QuotedIdentifier); Assert.True(qes.Settings.QueryExecutionSettings.AnsiNullDefaultOn); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SpecialActionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SpecialActionTests.cs index 156114b7..1ede3ca7 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SpecialActionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SpecialActionTests.cs @@ -4,14 +4,14 @@ // using Microsoft.SqlTools.ServiceLayer.QueryExecution; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution { public class SpecialActionTests { - [Fact] + [Test] public void SpecialActionInstantiation() { // If: @@ -20,11 +20,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... The special action should be set to none and only none - Assert.Equal(true, specialAction.None); - Assert.Equal(false, specialAction.ExpectYukonXMLShowPlan); + Assert.AreEqual(true, specialAction.None); + Assert.AreEqual(false, specialAction.ExpectYukonXMLShowPlan); } - [Fact] + [Test] public void SpecialActionNoneProperty() { // If: @@ -35,11 +35,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... The special action should be set to none and only none - Assert.Equal(true, specialAction.None); - Assert.Equal(false, specialAction.ExpectYukonXMLShowPlan); + Assert.AreEqual(true, specialAction.None); + Assert.AreEqual(false, specialAction.ExpectYukonXMLShowPlan); } - [Fact] + [Test] public void SpecialActionExpectYukonXmlShowPlanReset() { // If: @@ -50,11 +50,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... The special action should be set to none and only none - Assert.Equal(true, specialAction.None); - Assert.Equal(false, specialAction.ExpectYukonXMLShowPlan); + Assert.AreEqual(true, specialAction.None); + Assert.AreEqual(false, specialAction.ExpectYukonXMLShowPlan); } - [Fact] + [Test] public void SpecialActionCombiningProperties() { // If: @@ -69,8 +69,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... The special action should be set to none and only none - Assert.Equal(false, specialAction.None); - Assert.Equal(true, specialAction.ExpectYukonXMLShowPlan); + Assert.AreEqual(false, specialAction.None); + Assert.AreEqual(true, specialAction.ExpectYukonXMLShowPlan); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SubsetTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SubsetTests.cs index 587073fe..79ddc7bc 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SubsetTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/QueryExecution/SubsetTests.cs @@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution { @@ -20,10 +20,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution { #region ResultSet Class Tests - [Theory] - [InlineData(0, 2)] - [InlineData(0, 20)] - [InlineData(1, 2)] + static private readonly object[] validSet = + { + new object[] {0, 2 }, + new object[] {0, 20 }, + new object[] {1, 2 }, + }; + + [Test, TestCaseSource(nameof(validSet))] public void ResultSetValidTest(int startRow, int rowCount) { // Setup: @@ -39,15 +43,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... I should get the requested number of rows back - Assert.Equal(Math.Min(rowCount, Common.StandardRows), subset.RowCount); - Assert.Equal(Math.Min(rowCount, Common.StandardRows), subset.Rows.Length); + Assert.AreEqual(Math.Min(rowCount, Common.StandardRows), subset.RowCount); + Assert.AreEqual(Math.Min(rowCount, Common.StandardRows), subset.Rows.Length); } - [Theory] - [InlineData(-1, 2)] // Invalid start index, too low - [InlineData(10, 2)] // Invalid start index, too high - [InlineData(0, -1)] // Invalid row count, too low - [InlineData(0, 0)] // Invalid row count, zero + static private readonly object[] invalidSet = + { + new object[] {-1, 2}, // Invalid start index, too low + new object[] {10, 2}, // Invalid start index, too high + new object[] {0, -1}, // Invalid row count, too low + new object[] {0, 0 }, // Invalid row count, zero + }; + [Test, TestCaseSource(nameof(invalidSet))] public void ResultSetInvalidParmsTest(int rowStartIndex, int rowCount) { // If: @@ -57,28 +64,26 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // ... It should throw an exception - Assert.ThrowsAsync(() => rs.GetSubset(rowStartIndex, rowCount)).Wait(); + Assert.ThrowsAsync(() => rs.GetSubset(rowStartIndex, rowCount)); } - [Fact] - public async Task ResultSetNotReadTest() + [Test] + public void ResultSetNotReadTest() { // If: // ... I have a resultset that hasn't been executed and I request a valid result set from it // Then: // ... It should throw an exception for having not been read ResultSet rs = new ResultSet(Common.Ordinal, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory()); - await Assert.ThrowsAsync(() => rs.GetSubset(0, 1)); + Assert.ThrowsAsync(() => rs.GetSubset(0, 1)); } #endregion #region Batch Class Tests - [Theory] - [InlineData(2)] - [InlineData(20)] - public void BatchSubsetValidTest(int rowCount) + [Test] + public void BatchSubsetValidTest([Values(2,20)] int rowCount) { // If I have an executed batch Batch b = Common.GetBasicExecutedBatch(); @@ -90,14 +95,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // Then: // I should get the requested number of rows - Assert.Equal(Math.Min(rowCount, Common.StandardRows), subset.RowCount); - Assert.Equal(Math.Min(rowCount, Common.StandardRows), subset.Rows.Length); + Assert.AreEqual(Math.Min(rowCount, Common.StandardRows), subset.RowCount); + Assert.AreEqual(Math.Min(rowCount, Common.StandardRows), subset.Rows.Length); } - [Theory] - [InlineData(-1)] // Invalid result set, too low - [InlineData(2)] // Invalid result set, too high - public void BatchSubsetInvalidParamsTest(int resultSetIndex) + [Test] + public void BatchSubsetInvalidParamsTest([Values(-1,2)] int resultSetIndex) { // If I have an executed batch Batch b = Common.GetBasicExecutedBatch(); @@ -105,17 +108,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // ... And I ask for a subset with an invalid result set index // Then: // ... It should throw an exception - Assert.ThrowsAsync(() => b.GetSubset(resultSetIndex, 0, 2)).Wait(); + Assert.ThrowsAsync(() => b.GetSubset(resultSetIndex, 0, 2)); } #endregion #region Query Class Tests - [Theory] - [InlineData(-1)] // Invalid batch, too low - [InlineData(2)] // Invalid batch, too high - public void QuerySubsetInvalidParamsTest(int batchIndex) + [Test] + public void QuerySubsetInvalidParamsTest([Values(-1,2)] int batchIndex) { // If I have an executed query Query q = Common.GetBasicExecutedQuery(); @@ -123,14 +124,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution // ... And I ask for a subset with an invalid result set index // Then: // ... It should throw an exception - Assert.ThrowsAsync(() => q.GetSubset(batchIndex, 0, 0, 1)).Wait(); + Assert.ThrowsAsync(() => q.GetSubset(batchIndex, 0, 0, 1)); } #endregion #region Service Intergration Tests - [Fact] + [Test] public async Task SubsetServiceValidTest() { // If: @@ -155,7 +156,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution subsetRequest.Validate(); } - [Fact] + [Test] public async Task SubsetServiceMissingQueryTest() { // If: @@ -170,7 +171,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution subsetRequest.Validate(); } - [Fact] + [Test] public async Task SubsetServiceUnexecutedQueryTest() { // If: @@ -193,7 +194,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution subsetRequest.Validate(); } - [Fact] + [Test] public async Task SubsetServiceOutOfRangeSubsetTest() { // If: diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureAuthenticationManagerTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureAuthenticationManagerTest.cs index 9c0bf2a6..9a2bd147 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureAuthenticationManagerTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureAuthenticationManagerTest.cs @@ -13,7 +13,7 @@ using Microsoft.SqlTools.ResourceProvider.Core.Authentication; using Microsoft.SqlTools.ResourceProvider.Core.Contracts; using Microsoft.SqlTools.ResourceProvider.DefaultImpl; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure { @@ -29,14 +29,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure serviceProvider.RegisterSingleService(resourceManagerMock.Object); } - [Fact] + [Test] public async Task CurrentUserShouldBeNullWhenUserIsNotSignedIn() { IAzureAuthenticationManager accountManager = await CreateAccountManager(null, null); Assert.Null(await accountManager.GetCurrentAccountAsync()); } - [Fact] + [Test] public async Task GetSubscriptionShouldReturnEmptyWhenUserIsNotSignedIn() { IAzureAuthenticationManager accountManager = await CreateAccountManager(null, null); @@ -45,24 +45,24 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure Assert.False(result.Any()); } - [Fact] + [Test] public async Task GetSubscriptionShouldThrowWhenUserNeedsAuthentication() { var currentUserAccount = CreateAccount(); currentUserAccount.Account.IsStale = true; IAzureAuthenticationManager accountManager = await CreateAccountManager(currentUserAccount, null); - await Assert.ThrowsAsync(() => accountManager.GetSelectedSubscriptionsAsync()); + Assert.ThrowsAsync(() => accountManager.GetSelectedSubscriptionsAsync()); } - [Fact] + [Test] public async Task GetSubscriptionShouldThrowIfFailed() { var currentUserAccount = CreateAccount(); IAzureAuthenticationManager accountManager = await CreateAccountManager(currentUserAccount, null, true); - await Assert.ThrowsAsync(() => accountManager.GetSelectedSubscriptionsAsync()); + Assert.ThrowsAsync(() => accountManager.GetSelectedSubscriptionsAsync()); } - [Fact] + [Test] public async Task GetSubscriptionShouldReturnTheListSuccessfully() { List subscriptions = new List { diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureDatabaseDiscoveryProviderTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureDatabaseDiscoveryProviderTest.cs index 3baef9c4..2317a90b 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureDatabaseDiscoveryProviderTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureDatabaseDiscoveryProviderTest.cs @@ -10,7 +10,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.SqlTools.ResourceProvider.Core; using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure { @@ -19,7 +19,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure /// public class AzureDatabaseDiscoveryProviderTest { - [Fact] + [Test] public async Task GetShouldReturnDatabasesSuccessfully() { string databaseName1 = "server/db1"; @@ -51,7 +51,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure Assert.True(list.Count() == 2); } - [Fact] + [Test] public async Task GetShouldReturnDatabasesEvenIfFailsForOneServer() { string databaseName1 = "server1/db1"; @@ -85,7 +85,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure Assert.True(response.Errors.Count() == 1); } - [Fact] + [Test] public async Task GetShouldReturnDatabasesFromCacheIfGetCalledTwice() { Dictionary> subscriptionToDatabaseMap = CreateSubscriptonMap(2); @@ -107,7 +107,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure ValidateResult(subscriptionToDatabaseMap, list); } - [Fact] + [Test] public async Task GetShouldReturnDatabasesFromServiceIfGetCalledTwiceButRefreshed() { Dictionary> subscriptionToDatabaseMap = CreateSubscriptonMap(2); @@ -187,7 +187,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure return subscriptionToDatabaseMapCopy; } - [Fact] + [Test] public async Task GetShouldReturnEmptyGivenNotSubscriptionFound() { Dictionary> subscriptionToDatabaseMap = new Dictionary>(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureResourceWrapperTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureResourceWrapperTest.cs index 5b0df2a1..d623751e 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureResourceWrapperTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureResourceWrapperTest.cs @@ -5,13 +5,13 @@ using Microsoft.Azure.Management.Sql.Models; using Microsoft.SqlTools.ResourceProvider.DefaultImpl; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure { public class AzureResourceWrapperTest { - [Fact] + [Test] public void ShouldParseResourceGroupFromId() { // Given a resource with a known resource group @@ -25,10 +25,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure string rgName = resource.ResourceGroupName; // then I get it as expected - Assert.Equal("myresourcegroup", rgName); + Assert.AreEqual("myresourcegroup", rgName); } - [Fact] + [Test] public void ShouldHandleMissingResourceGroup() { // Given a resource without resource group in the ID @@ -42,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure string rgName = resource.ResourceGroupName; // then I get string.Empty - Assert.Equal(string.Empty, rgName); + Assert.AreEqual(string.Empty, rgName); } private TrackedResource CreateMockResource(string id = null, string name = null, string type = null) diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureSqlServerDiscoveryProviderTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureSqlServerDiscoveryProviderTest.cs index 83b993dd..f7cf7bf2 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureSqlServerDiscoveryProviderTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureSqlServerDiscoveryProviderTest.cs @@ -8,7 +8,7 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.SqlTools.ResourceProvider.Core; using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure { @@ -17,7 +17,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure /// public class AzureSqlServerDiscoveryProviderTest { - [Fact] + [Test] public async Task GetShouldReturnServersSuccessfully() { string serverName = "server"; @@ -44,7 +44,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure Assert.True(servers.Count() == 4); } - [Fact] + [Test] public async Task GetShouldReturnEmptyGivenNoSubscriptionFound() { Dictionary> subscriptionToDatabaseMap = new Dictionary>(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureSubscriptionContextTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureSubscriptionContextTest.cs index 3279e177..e2214642 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureSubscriptionContextTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/Azure/AzureSubscriptionContextTest.cs @@ -4,7 +4,7 @@ using System; using Microsoft.SqlTools.ResourceProvider.DefaultImpl; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure { @@ -13,7 +13,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure /// public class AzureSubscriptionContextTest { - [Fact] + [Test] public void SubscriptionNameShouldReturnNullGivenNullSubscription() { AzureSubscriptionContext subscriptionContext = new AzureSubscriptionContext(null); @@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure Assert.True(subscriptionContext.Subscription == null); } - [Fact] + [Test] public void SubscriptionNameShouldReturnCorrectValueGivenValidSubscription() { string name = Guid.NewGuid().ToString(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/DependencyManagerTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/DependencyManagerTest.cs index e7f71304..51dc62c0 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/DependencyManagerTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/DependencyManagerTest.cs @@ -12,7 +12,7 @@ //using Microsoft.SqlTools.ResourceProvider.Core.Extensibility; //using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes; //using Moq; -//using Xunit; +//using NUnit.Framework; //namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider //{ @@ -48,7 +48,7 @@ // _dependencyManager = new DependencyManager(_serviceProperties); // } -// [Fact] +// [Test] // public void GetShouldReturnProvidersFromTheCatalog() // { // IEnumerable> providers = @@ -56,19 +56,19 @@ // Assert.NotNull(providers); // } -// [Fact] +// [Test] // public void GetShouldReturnEmptyListGivenInvalidCategory() // { // Assert.False(_dependencyManager.GetServiceDescriptors(new ServerDefinition(null, "invalid category")).Any()); // } -// [Fact] +// [Test] // public void GetShouldReturnEmptyListGivenInvalidServerType() // { // Assert.False(_dependencyManager.GetServiceDescriptors(new ServerDefinition("invalid server type", null)).Any()); // } -// [Fact] +// [Test] // public void GetShouldReturnAllProvidersGivenNoParameter() // { // IEnumerable> providers = @@ -77,7 +77,7 @@ // Assert.True(providers.Count() == _providers.Count()); // } -// [Fact] +// [Test] // public void GetShouldReturnProvidersGivenServerType() // { // var serverType = "sqlServer"; @@ -88,7 +88,7 @@ // Assert.True(providers.Count() == _providers.Count(x => x.Metadata.ServerType.Equals(serverType, StringComparison.OrdinalIgnoreCase))); // } -// [Fact] +// [Test] // public void GetShouldReturnProvidersGivenCategory() // { // IEnumerable> providers = @@ -97,7 +97,7 @@ // Assert.True(providers.Count() == 1); // } -// [Fact] +// [Test] // public void GetShouldReturnProviderForEmptyCategoryGivenEmptyCategory() // { // // Given choice of 2 providers, one with empty category and other with specified one @@ -126,7 +126,7 @@ // Assert.True(foundProviders.Count() == 1); // } -// [Fact] +// [Test] // public void GetShouldReturnProviderGivenServerTypeAndLocationWithValidProvider() // { // IEnumerable> providers = @@ -135,7 +135,7 @@ // Assert.True(providers.Count() == 1); // } -// [Fact] +// [Test] // public void GetShouldReturnTheServiceWithTheHighestPriorityIdMultipleFound() // { @@ -162,7 +162,7 @@ // Assert.True(descriptor.Exportable == expectedProvider); // } -// [Fact] +// [Test] // public void GetShouldReturnTheServiceEvenIfTheServerTypeNotSet() // { // IServerDiscoveryProvider expectedProvider = new Mock(); @@ -188,7 +188,7 @@ // Assert.True(descriptor.Exportable == expectedProvider); // } -// [Fact] +// [Test] // public void GetShouldReturnTheServiceThatMatchedExactlyIfServerTypeSpecified() // { // IServerDiscoveryProvider expectedProvider = new Mock(); @@ -214,7 +214,7 @@ // Assert.True(descriptor.Exportable == expectedProvider); // } -// [Fact] +// [Test] // public void GetShouldReturnTheServiceThatMatchedExactlyIfCategorySpecified() // { // IServerDiscoveryProvider expectedProvider = new Mock(); @@ -240,7 +240,7 @@ // Assert.True(descriptor.Exportable == expectedProvider); // } -// [Fact] +// [Test] // public void GetShouldReturnTheServiceEvenIfTheCategoryNotSet() // { @@ -267,7 +267,7 @@ // Assert.True(descriptor.Exportable == expectedProvider); // } -// [Fact] +// [Test] // public void GetShouldReturnProvidersGivenServerTypeAndMoreThanOneLocation() // { // var serverType = "sqlServer"; @@ -277,7 +277,7 @@ // Assert.True(providers.Count() == _providers.Count(x => x.Metadata.ServerType.Equals(serverType, StringComparison.OrdinalIgnoreCase))); // } -// [Fact] +// [Test] // public async Task ProviderCreatedByFactoryShouldReturnServersSuccessfully() // { // List expectedServers = _localSqlServers; @@ -289,7 +289,7 @@ // ServiceResponse result = await provider.Exportable.GetServerInstancesAsync(); // var servers = result.Data; // Assert.NotNull(servers); -// Assert.Equal(expectedServers, servers); +// Assert.AreEqual(expectedServers, servers); // } // } //} diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ExceptionUtilTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ExceptionUtilTest.cs index f0896e31..f5ca1f56 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ExceptionUtilTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ExceptionUtilTest.cs @@ -6,7 +6,7 @@ using System; using System.Data.Common; using Microsoft.SqlTools.ResourceProvider.Core; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider { @@ -15,34 +15,34 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider /// public class ExceptionUtilTest { - [Fact] + [Test] public void IsSqlExceptionShouldReturnFalseGivenNullException() { Exception exception = null; bool expected = false; bool actual = exception.IsDbException(); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); } - [Fact] + [Test] public void IsSqlExceptionShouldReturnFalseGivenNonSqlException() { Exception exception = new ApplicationException(); bool expected = false; bool actual = exception.IsDbException(); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); } - [Fact] + [Test] public void IsSqlExceptionShouldReturnFalseGivenNonSqlExceptionWithInternalException() { Exception exception = new ApplicationException("Exception message", new ServiceFailedException()); bool expected = false; bool actual = exception.IsDbException(); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); } - [Fact] + [Test] public void IsSqlExceptionShouldReturnTrueGivenSqlException() { Exception exception = CreateDbException(); @@ -50,10 +50,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider bool expected = true; bool actual = exception.IsDbException(); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); } - [Fact] + [Test] public void IsSqlExceptionShouldReturnTrueGivenExceptionWithInnerSqlException() { Exception exception = new ApplicationException("", CreateDbException()); @@ -61,7 +61,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider bool expected = true; bool actual = exception.IsDbException(); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); } private Exception CreateDbException() diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/FirewallErrorParserTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/FirewallErrorParserTest.cs index 938e493a..23491ccf 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/FirewallErrorParserTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/FirewallErrorParserTest.cs @@ -4,7 +4,7 @@ using System; using Microsoft.SqlTools.ResourceProvider.Core.Firewall; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider { @@ -19,20 +19,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider private FirewallErrorParser _firewallErrorParser = new FirewallErrorParser(); - [Fact] + [Test] public void ParseExceptionShouldThrowExceptionGivenNullErrorMessage() { string errorMessage = null; int errorCode = SqlAzureFirewallBlockedErrorNumber; - Assert.Throws("errorMessage", () => + Assert.Throws(() => { FirewallParserResponse response = _firewallErrorParser.ParseErrorMessage(errorMessage, errorCode); - Assert.False(response.FirewallRuleErrorDetected); }); } - [Fact] + [Test] public void ParseExceptionShouldReturnFireWallRuleNotDetectedGivenDifferentError() { int errorCode = 123; @@ -41,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider Assert.False(response.FirewallRuleErrorDetected); } - [Fact] + [Test] public void ParseExceptionShouldReturnFireWallRuleNotDetectedGivenLoginFailedError() { int errorCode = SqlAzureLoginFailedErrorNumber; @@ -50,7 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider Assert.False(response.FirewallRuleErrorDetected); } - [Fact] + [Test] public void ParseExceptionShouldReturnFireWallRuleNotDetectedGivenInvalidErrorMessage() { int errorCode = SqlAzureFirewallBlockedErrorNumber; @@ -59,13 +58,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider Assert.False(response.FirewallRuleErrorDetected); } - [Fact] + [Test] public void ParseExceptionShouldReturnFireWallRuleDetectedGivenValidErrorMessage() { int errorCode = SqlAzureFirewallBlockedErrorNumber; FirewallParserResponse response = _firewallErrorParser.ParseErrorMessage(_errorMessage, errorCode); Assert.True(response.FirewallRuleErrorDetected); - Assert.Equal(response.BlockedIpAddress.ToString(), "1.2.3.4"); + Assert.AreEqual("1.2.3.4", response.BlockedIpAddress.ToString()); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/FirewallRuleServiceTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/FirewallRuleServiceTest.cs index 54157904..c0aa844c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/FirewallRuleServiceTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/FirewallRuleServiceTest.cs @@ -10,7 +10,7 @@ using Microsoft.SqlTools.ResourceProvider.Core; using Microsoft.SqlTools.ResourceProvider.Core.Authentication; using Microsoft.SqlTools.ResourceProvider.Core.Firewall; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider { @@ -19,55 +19,55 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider /// public class FirewallRuleServiceTest { - [Fact] + [Test] public async Task CreateShouldThrowExceptionGivenNullServerName() { string serverName = null; ServiceTestContext testContext = new ServiceTestContext(); - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, serverName)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, serverName)); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionGivenNullStartIp() { string serverName = "serverName"; ServiceTestContext testContext = new ServiceTestContext(); testContext.StartIpAddress = null; - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, serverName)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, serverName)); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionGivenInvalidEndIp() { string serverName = "serverName"; ServiceTestContext testContext = new ServiceTestContext(); testContext.EndIpAddress = "invalid ip"; - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, serverName)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, serverName)); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionGivenInvalidStartIp() { string serverName = "serverName"; ServiceTestContext testContext = new ServiceTestContext(); testContext.StartIpAddress = "invalid ip"; - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, serverName)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, serverName)); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionGivenNullEndIp() { ServiceTestContext testContext = new ServiceTestContext(); testContext.EndIpAddress = null; - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName)); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionIfUserIsNotLoggedIn() { var applicationAuthenticationManagerMock = new Mock(); @@ -78,13 +78,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider testContext.ApplicationAuthenticationManagerMock = applicationAuthenticationManagerMock; testContext.AzureResourceManagerMock = azureResourceManagerMock; - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName)); azureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync( It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionIfUserDoesNotHaveSubscriptions() { var applicationAuthenticationManagerMock = @@ -98,13 +98,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider testContext.ApplicationAuthenticationManagerMock = applicationAuthenticationManagerMock; testContext.AzureResourceManagerMock = azureResourceManagerMock; - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName)); azureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync( It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionIfAuthenticationManagerFailsToReturnSubscription() { var applicationAuthenticationManagerMock = new Mock(); @@ -115,23 +115,23 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider ServiceTestContext testContext = new ServiceTestContext(); testContext.ApplicationAuthenticationManagerMock = applicationAuthenticationManagerMock; testContext.AzureResourceManagerMock = azureResourceManagerMock; - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, "invalid server")); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, "invalid server")); azureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync( It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionGivenNoSubscriptionFound() { ServiceTestContext testContext = new ServiceTestContext(); testContext = CreateMocks(testContext); - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, "invalid server")); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, "invalid server")); } - [Fact] + [Test] public async Task CreateShouldCreateFirewallSuccessfullyGivenValidUserAccount() { ServiceTestContext testContext = new ServiceTestContext(); @@ -140,7 +140,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider await VerifyCreateAsync(testContext, testContext.ServerName); } - [Fact] + [Test] public async Task CreateShouldFindTheRightSubscriptionGivenValidSubscriptionInFirstPlace() { ServiceTestContext testContext = new ServiceTestContext(); @@ -156,7 +156,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider await VerifyCreateAsync(testContext, testContext.ServerName); } - [Fact] + [Test] public async Task CreateShouldFindTheRightSubscriptionGivenValidSubscriptionInSecondPlace() { ServiceTestContext testContext = new ServiceTestContext(); @@ -171,7 +171,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider await VerifyCreateAsync(testContext, testContext.ServerName); } - [Fact] + [Test] public async Task CreateShouldFindTheRightSubscriptionGivenValidSubscriptionInLastPlace() { ServiceTestContext testContext = new ServiceTestContext(); @@ -188,7 +188,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider await VerifyCreateAsync(testContext, testContext.ServerName); } - [Fact] + [Test] public async Task CreateShouldFindTheRightResourceGivenValidResourceInLastPlace() { ServiceTestContext testContext = new ServiceTestContext(); @@ -204,7 +204,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider await VerifyCreateAsync(testContext, testContext.ServerName); } - [Fact] + [Test] public async Task CreateShouldFindTheRightResourceGivenValidResourceInFirstPlace() { ServiceTestContext testContext = new ServiceTestContext(); @@ -220,7 +220,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider await VerifyCreateAsync(testContext, testContext.ServerName); } - [Fact] + [Test] public async Task CreateShouldFindTheRightResourceGivenValidResourceInMiddle() { ServiceTestContext testContext = new ServiceTestContext(); @@ -237,7 +237,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider await VerifyCreateAsync(testContext, testContext.ServerName); } - [Fact] + [Test] public async Task CreateThrowExceptionIfResourceNotFound() { ServiceTestContext testContext = new ServiceTestContext(); @@ -250,10 +250,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider testContext = CreateMocks(testContext); - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName)); } - [Fact] + [Test] public async Task CreateThrowExceptionIfResourcesIsEmpty() { ServiceTestContext testContext = new ServiceTestContext(); @@ -261,10 +261,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider testContext.SubscriptionToResourcesMap[testContext.ValidSubscription.Subscription.SubscriptionId] = new List(); testContext = CreateMocks(testContext); - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName, false)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName, false)); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionIfThereIsNoSubscriptionForUser() { ServiceTestContext testContext = new ServiceTestContext(); @@ -272,11 +272,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider testContext = CreateMocks(testContext); - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName, false)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName, false)); } - [Fact] + [Test] public async Task CreateShouldThrowExceptionIfSubscriptionIsInAnotherAccount() { ServiceTestContext testContext = new ServiceTestContext(); @@ -287,10 +287,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider }; testContext = CreateMocks(testContext); - await Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName, false)); + Assert.ThrowsAsync(() => VerifyCreateAsync(testContext, testContext.ServerName, false)); } - [Fact] + [Test] public async Task CreateShouldCreateFirewallForTheRightServerFullyQualifiedName() { ServiceTestContext testContext = new ServiceTestContext(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ResourceProviderServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ResourceProviderServiceTests.cs index 9876fa2f..1506bd5d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ResourceProviderServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ResourceProviderServiceTests.cs @@ -17,7 +17,7 @@ using Microsoft.SqlTools.ResourceProvider.Core.Firewall; using Microsoft.SqlTools.ResourceProvider.DefaultImpl; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { @@ -47,7 +47,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter protected ResourceProviderService ResourceProviderService { get; private set; } - [Fact] + [Test] public async Task TestHandleFirewallRuleIgnoresNonMssqlProvider() { // Given a non-MSSQL provider @@ -64,11 +64,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter Assert.NotNull(response); Assert.False(response.Result); Assert.Null(response.IpAddress); - Assert.Equal(Microsoft.SqlTools.ResourceProvider.Core.SR.FirewallRuleUnsupportedConnectionType, response.ErrorMessage); + Assert.AreEqual(Microsoft.SqlTools.ResourceProvider.Core.SR.FirewallRuleUnsupportedConnectionType, response.ErrorMessage); }); } - [Fact] + [Test] public async Task TestHandleFirewallRuleSupportsMssqlProvider() { // Given a firewall error for the MSSQL provider @@ -84,12 +84,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter // Then I expect the response to be true and the IP address to be extracted Assert.NotNull(response); Assert.True(response.Result); - Assert.Equal("1.2.3.4", response.IpAddress); + Assert.AreEqual("1.2.3.4", response.IpAddress); Assert.Null(response.ErrorMessage); }); } - [Fact] + [Test] public async Task TestHandleFirewallRuleIgnoresNonFirewallErrors() { // Given a login error for the MSSQL provider @@ -105,12 +105,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter // Then I expect the response to be false and no IP address to be defined Assert.NotNull(response); Assert.False(response.Result); - Assert.Equal(string.Empty, response.IpAddress); + Assert.AreEqual(string.Empty, response.IpAddress); Assert.Null(response.ErrorMessage); }); } - [Fact] + [Test] public async Task TestHandleFirewallRuleDoesntBreakWithoutIp() { // Given a firewall error with no IP address in the error message @@ -126,12 +126,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter // Then I expect the response to be OK as we require the known IP address to function Assert.NotNull(response); Assert.False(response.Result); - Assert.Equal(string.Empty, response.IpAddress); + Assert.AreEqual(string.Empty, response.IpAddress); Assert.Null(response.ErrorMessage); }); } - [Fact] + [Test] public async Task TestCreateFirewallRuleBasicRequest() { // Given a firewall request for a valid subscription @@ -176,7 +176,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter }); } - [Fact] + [Test] public async Task TestCreateFirewallRuleHandlesTokenExpiration() { // Given the token has expired @@ -201,7 +201,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter { // Then I expect the response to indicate that we failed due to token expiration Assert.NotNull(response); - Assert.Equal(expectedErrorMsg, response.ErrorMessage); + Assert.AreEqual(expectedErrorMsg, response.ErrorMessage); Assert.True(response.IsTokenExpiredFailure); Assert.False(response.Result); }); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ServiceManagerTest.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ServiceManagerTest.cs index c7e1d9ac..3ea38275 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ServiceManagerTest.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ResourceProvider/ServiceManagerTest.cs @@ -12,7 +12,7 @@ using Microsoft.SqlTools.ResourceProvider.Core.Extensibility; using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure; using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider { @@ -40,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider }; } - [Fact] + [Test] public void GetServiceShouldReturnTheServiceThatHasGivenMetadataCorrectly() { //given @@ -55,7 +55,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider Assert.True(service.GetType() == typeof(FakeSecureServerDiscoveryProvider)); } - [Fact] + [Test] public void GetServiceShouldReturnNullGivenInvalidMetadata() { //given @@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider Assert.Null(service); } - [Fact] + [Test] public void GetServiceShouldReturnNullGivenUnSupportedMetadata() { //given @@ -83,7 +83,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider Assert.Null(service); } - [Fact] + [Test] public void RequiresUserAccountShouldReturnFalseGivenNotSecuredService() { //given @@ -97,7 +97,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider Assert.NotNull(service); } - [Fact] + [Test] public void GetShouldReturnDefaultAzureServiceGivenDefaultCatalog() { // given @@ -127,7 +127,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider } - [Fact] + [Test] public void GetShouldReturnImplementedAzureServiceIfFoundInCatalog() { //given @@ -140,7 +140,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider Assert.True(serverDiscoveryProvider is FakeAzureServerDiscoveryProvider); } - [Fact] + [Test] public void GetGetServiceOfExportableShouldReturnNullGivenSameTypeAsExportable() { //given diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SchemaCompare/SchemaCompareTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SchemaCompare/SchemaCompareTests.cs index e6908bf4..9ba93eee 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SchemaCompare/SchemaCompareTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SchemaCompare/SchemaCompareTests.cs @@ -6,54 +6,51 @@ using System; using Microsoft.SqlTools.ServiceLayer.SchemaCompare; using Microsoft.SqlTools.ServiceLayer.SchemaCompare.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SchemaCompare { public class SchemaCompareTests { - [Fact] + [Test] public void FormatScriptAddsGo() { string script = "EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Primary key for AWBuildVersion records.', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'AWBuildVersion', @level2type = N'COLUMN', @level2name = N'SystemInformationID';"; - Assert.DoesNotContain("GO", script); + Assert.That(script, Does.Not.Contain("GO")); string result = SchemaCompareUtils.FormatScript(script); - Assert.EndsWith("GO", result); + Assert.That(result, Does.EndWith("GO")); } - [Fact] + [Test] public void FormatScriptDoesNotAddGoForNullScripts() { string script1 = null; string result1 = SchemaCompareUtils.FormatScript(script1); - Assert.DoesNotContain("GO", result1); - Assert.Equal(null, result1); + Assert.AreEqual(null, result1); string script2 = "null"; string result2 = SchemaCompareUtils.FormatScript(script2); - Assert.DoesNotContain("GO", result2); + Assert.That(result2, Does.Not.Contain("GO")); } - [Fact] + [Test] public void FormatScriptDoesNotAddGoForEmptyStringScripts() { string script = string.Empty; string result = SchemaCompareUtils.FormatScript(script); - Assert.DoesNotContain("GO", result); - Assert.Equal(string.Empty, result); + Assert.AreEqual(string.Empty, result); } - [Fact] + [Test] public void FormatScriptDoesNotAddGoForWhitespaceStringScripts() { string script = " \t\n"; Assert.True(string.IsNullOrWhiteSpace(script)); string result = SchemaCompareUtils.FormatScript(script); - Assert.DoesNotContain("GO", result); - Assert.Equal(string.Empty, result); + Assert.AreEqual(string.Empty, result); } - [Fact] + [Test] public void RemovesExcessWhitespace() { // leading whitespace @@ -87,7 +84,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SchemaCompare Assert.True(expected3.Equals(result3)); } - [Fact] + [Test] public void CreateExcludedObjects() { //successful creation @@ -124,12 +121,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SchemaCompare }; var validResult1 = SchemaCompareUtils.CreateExcludedObject(validObject1); Assert.NotNull(validResult1); - Assert.Equal(validObject1.SqlObjectType, validResult1.TypeName); - Assert.Equal(validObject1.NameParts.Length, validResult1.Identifier.Parts.Count); - Assert.Equal(validationString, string.Join(".", validResult1.Identifier.Parts)); + Assert.AreEqual(validObject1.SqlObjectType, validResult1.TypeName); + Assert.AreEqual(validObject1.NameParts.Length, validResult1.Identifier.Parts.Count); + Assert.AreEqual(validationString, string.Join(".", validResult1.Identifier.Parts)); for (int i = 0; i < validObject1.NameParts.Length; i++) { - Assert.Equal(validObject1.NameParts[i], validResult1.Identifier.Parts[i]); + Assert.AreEqual(validObject1.NameParts[i], validResult1.Identifier.Parts[i]); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Scripting/ScriptingExtensionMethodsTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Scripting/ScriptingExtensionMethodsTests.cs index f0441a9f..1a7ff2b0 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Scripting/ScriptingExtensionMethodsTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Scripting/ScriptingExtensionMethodsTests.cs @@ -14,7 +14,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting /// /// SQL sysname supports single quotes in object names, so URN attributes need to be properly escaped /// - [Xunit.Fact] + [Test] public void ToUrnEscapesAttributes() { var scriptingObject = new ScriptingObject() { Name = "quoted'Name", Schema = "quoted'Schema", Type = "Table" }; @@ -26,7 +26,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting Assert.That(urn.GetAttribute("Schema"), Is.EqualTo("quoted'Schema"), "GetAttribute('Schema')"); } - [Xunit.Fact] + [Test] public void ToObjectStringUnescapesAttributes() { var urn = new Urn(@"Server[@Name = 'SERVER']/Database[@Name = 'quoted''db']/Table[@Name = 'quoted''Name' and @Schema = 'quoted''Schema']"); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Scripting/ScriptingObjectMatcherTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Scripting/ScriptingObjectMatcherTests.cs index 0026bc21..1d9d187f 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Scripting/ScriptingObjectMatcherTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Scripting/ScriptingObjectMatcherTests.cs @@ -8,7 +8,7 @@ using System.Collections.Generic; using System.Linq; using Microsoft.SqlTools.ServiceLayer.Scripting; using Microsoft.SqlTools.ServiceLayer.Scripting.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting { @@ -66,7 +66,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting View_S1_View2, }; - [Fact] + [Test] public void ScriptingMatchIncludeAll() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -78,10 +78,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(6, results.Count()); + Assert.AreEqual(6, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeNone() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -93,10 +93,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(0, results.Count()); + Assert.AreEqual(0, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeName() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -108,10 +108,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(2, results.Count()); + Assert.AreEqual(2, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeNameWildcard() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -123,7 +123,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(6, results.Count()); + Assert.AreEqual(6, results.Count()); } public void ScriptingMatchIncludeNameWildcardPostfix() @@ -137,10 +137,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(4, results.Count()); + Assert.AreEqual(4, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeSchema() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -152,10 +152,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(2, results.Count()); + Assert.AreEqual(2, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeSchemaWildcard() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -167,10 +167,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(6, results.Count()); + Assert.AreEqual(6, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeSchemaWildcardPostfixCriteria() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -182,10 +182,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(6, results.Count()); + Assert.AreEqual(6, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeSchemaWildcardPostfix() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -197,10 +197,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: "View", candidates: TestData); - Assert.Equal(4, results.Count()); + Assert.AreEqual(4, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeType() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -212,10 +212,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(4, results.Count()); + Assert.AreEqual(4, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeNameAndSchema() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -227,10 +227,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(1, results.Count()); + Assert.AreEqual(1, results.Count()); } - [Fact] + [Test] public void ScriptingMatchIncludeSchemaAndType() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -242,10 +242,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(2, results.Count()); + Assert.AreEqual(2, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeName() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -257,10 +257,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(4, results.Count()); + Assert.AreEqual(4, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeNameWildcard() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -272,7 +272,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(0, results.Count()); + Assert.AreEqual(0, results.Count()); } public void ScriptingMatchExcludeNameWildcardPostfix() @@ -286,10 +286,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(4, results.Count()); + Assert.AreEqual(4, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeSchema() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -301,10 +301,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(4, results.Count()); + Assert.AreEqual(4, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeSchemaWildcard() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -316,10 +316,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(0, results.Count()); + Assert.AreEqual(0, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeSchemaWildcardPostfix() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -331,10 +331,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(0, results.Count()); + Assert.AreEqual(0, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeType() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -346,10 +346,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(2, results.Count()); + Assert.AreEqual(2, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeNameAndSchemaCriteria() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -361,10 +361,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(5, results.Count()); + Assert.AreEqual(5, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeNameAndSchema() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -376,10 +376,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(1, results.Count()); + Assert.AreEqual(1, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeSchemaAndTypeCriteria() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -391,10 +391,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: null, candidates: TestData); - Assert.Equal(4, results.Count()); + Assert.AreEqual(4, results.Count()); } - [Fact] + [Test] public void ScriptingMatchExcludeSchemaAndType() { IEnumerable results = ScriptingObjectMatcher.Match( @@ -406,10 +406,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting excludeTypes: "View", candidates: TestData); - Assert.Equal(2, results.Count()); + Assert.AreEqual(2, results.Count()); } - [Fact] + [Test] public void ScriptingObjectEquality() { ScriptingObject scriptingObject1 = new ScriptingObject { Type = "Table", Schema = "test", Name = "test_table" }; @@ -445,12 +445,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting }; - [Fact] + [Test] public void TestQuoteObjectName() { for (int i = 0; i < TestObjects.Length; i++) { - Assert.Equal(Scripter.ScriptingUtils.QuoteObjectName(TestObjects[i]), ExpectedObjects[i]); + Assert.AreEqual(Scripter.ScriptingUtils.QuoteObjectName(TestObjects[i]), ExpectedObjects[i]); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/AsyncLockTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/AsyncLockTests.cs index 3c08d060..38cbab9a 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/AsyncLockTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/AsyncLockTests.cs @@ -7,13 +7,13 @@ using System; using System.Threading; using System.Threading.Tasks; using Microsoft.SqlTools.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost { public class AsyncLockTests { - [Fact] + [Test] public async Task AsyncLockSynchronizesAccess() { AsyncLock asyncLock = new AsyncLock(); @@ -21,15 +21,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost Task lockOne = asyncLock.LockAsync(); Task 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 +42,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost 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); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/AsyncQueueTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/AsyncQueueTests.cs index 27c903b0..c9b50e18 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/AsyncQueueTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/AsyncQueueTests.cs @@ -9,13 +9,13 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.SqlTools.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost { public class AsyncQueueTests { - [Fact] + [Test] public async Task AsyncQueueSynchronizesAccess() { ConcurrentBag outputItems = new ConcurrentBag(); @@ -53,10 +53,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost // At this point, numbers 0 through 299 should be in the outputItems IEnumerable expectedItems = Enumerable.Range(0, 300); - Assert.Equal(0, expectedItems.Except(outputItems).Count()); + Assert.AreEqual(0, expectedItems.Except(outputItems).Count()); } - [Fact] + [Test] public async Task AsyncQueueSkipsCancelledTasks() { AsyncQueue inputQueue = new AsyncQueue(); @@ -71,9 +71,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost await inputQueue.EnqueueAsync(1); // Did the second task get the number? - Assert.Equal(TaskStatus.Canceled, taskOne.Status); - Assert.Equal(TaskStatus.RanToCompletion, taskTwo.Status); - Assert.Equal(1, taskTwo.Result); + Assert.AreEqual(TaskStatus.Canceled, taskOne.Status); + Assert.AreEqual(TaskStatus.RanToCompletion, taskTwo.Status); + Assert.AreEqual(1, taskTwo.Result); } private async Task ConsumeItems( diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/CapabilitiesTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/CapabilitiesTests.cs index 04cfb80a..98c5542d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/CapabilitiesTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/CapabilitiesTests.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; using Microsoft.SqlTools.Hosting.Contracts; using Microsoft.SqlTools.Hosting.Protocol; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Capabilities { @@ -16,7 +16,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Capabilities /// public class Capabilities { - [Fact] + [Test] public async Task TestCapabilities() { Hosting.ServiceHost host = Hosting.ServiceHost.Instance; diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/JsonRpcMessageSerializerTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/JsonRpcMessageSerializerTests.cs index 8579942a..71c70d63 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/JsonRpcMessageSerializerTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/JsonRpcMessageSerializerTests.cs @@ -5,7 +5,7 @@ using Microsoft.SqlTools.Hosting.Protocol.Serializers; using Newtonsoft.Json.Linq; -using Xunit; +using NUnit.Framework; using HostingMessage = Microsoft.SqlTools.Hosting.Protocol.Contracts.Message; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost @@ -39,7 +39,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost this.messageSerializer = new JsonRpcMessageSerializer(); } - [Fact] + [Test] public void SerializesRequestMessages() { var messageObj = @@ -56,7 +56,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost checkParams: true); } - [Fact] + [Test] public void SerializesEventMessages() { var messageObj = @@ -71,7 +71,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost checkParams: true); } - [Fact] + [Test] public void SerializesResponseMessages() { var messageObj = @@ -87,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost checkResult: true); } - [Fact] + [Test] public void SerializesResponseWithErrorMessages() { var messageObj = @@ -114,18 +114,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost JToken token = null; Assert.True(messageObj.TryGetValue("jsonrpc", out token)); - Assert.Equal("2.0", token.ToString()); + Assert.AreEqual("2.0", token.ToString()); if (checkId) { Assert.True(messageObj.TryGetValue("id", out token)); - Assert.Equal(MessageId, token.ToString()); + Assert.AreEqual(MessageId, token.ToString()); } if (checkMethod) { Assert.True(messageObj.TryGetValue("method", out token)); - Assert.Equal(MethodName, token.ToString()); + Assert.AreEqual(MethodName, token.ToString()); } if (checkError) diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/LoggerTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/LoggerTests.cs index 6a87ae78..870bb397 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/LoggerTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/LoggerTests.cs @@ -8,7 +8,7 @@ using System.Reflection; using System.Threading.Tasks; using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost { @@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// Test to verify that the logger initialization is generating a valid file /// Verifies that a test log entries is succesfully written to a default log file. /// - [Fact] + [Test] public void LoggerDefaultFile() { TestLogger test = new TestLogger() @@ -40,7 +40,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// /// Test to verify that the logger initialization works using various possibilities. /// - [Fact] + [Test] public void LoggerTestInitialization() { int? testNo = 1; @@ -172,7 +172,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// /// Test to verify that there is no log file created if TracingLevel is set to off. /// - [Fact] + [Test] public void LoggerTracingLevelOff() { TestLogger test = new TestLogger() @@ -194,7 +194,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// Verifies that a test log entries logged at Information level are not present in log when tracingLevel /// is set to 'Critical' /// - [Fact] + [Test] public void LoggerInformationalNotLoggedWithCriticalTracingLevel() { TestLogger test = new TestLogger() @@ -213,7 +213,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// /// Test to verify that WriteWithCallstack() method turns on the callstack logging /// - [Fact] + [Test] public void LoggerWithCallstack() { TestLogger test = new TestLogger() @@ -232,7 +232,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// /// Test to verify that callstack logging is turned on, it does not get logged because tracing level filters them out. /// - [Fact] + [Test] public void LoggerWithCallstackFilteredOut() { TestLogger test = new TestLogger() @@ -251,7 +251,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// /// No TraceSource test to verify that WriteWithCallstack() method turns on the callstack logging /// - [Fact] + [Test] public void LoggerNoTraceSourceWithCallstack() { TestLogger test = new TestLogger() @@ -271,7 +271,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// /// No TraceSrouce test to verify that callstack logging is turned on, it does not get logged because tracing level filters them out. /// - [Fact] + [Test] public void LoggerNoTraceSourceWithCallstackFilteredOut() { TestLogger test = new TestLogger() @@ -292,7 +292,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// Tests to verify that upon changing TracingLevel from Warning To Error, /// after the change, messages of Error type are present in the log and those logged with warning type are not present. /// - [Fact] + [Test] public void LoggerTracingLevelFromWarningToError() { // setup the test object @@ -307,7 +307,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// Tests to verify that upon changing TracingLevel from Error To Warning, /// after the change, messages of Warning as well as of Error type are present in the log. /// - [Fact] + [Test] public void LoggerTracingLevelFromErrorToWarning() { // setup the test object @@ -322,7 +322,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// When not use TraceSource, test to verify that upon changing TracingLevel from Warning To Error, /// after the change, messages of Error type are present in the log and those logged with warning type are not present. /// - [Fact] + [Test] public void LoggerNoTraceSourceTracingLevelFromWarningToError() { // setup the test object @@ -340,7 +340,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// 2nd that after a lot of log entries are written with AutoFlush on, explicitly flushing and closing the Tracing does not increase the file size /// thereby verifying that there was no leftover log entries being left behind to be flushed. /// - [Fact] + [Test] public void LoggerAutolFlush() { // setup the test object @@ -365,7 +365,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// When not use TraceSource, test to verify that upon changing TracingLevel from Error To Warning, /// after the change, messages of Warning as well as of Error type are present in the log. /// - [Fact] + [Test] public void LoggerNoTraceSourceTracingLevelFromErrorToWarning() { // setup the test object @@ -384,7 +384,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost string oldMessage = @"Old Message with Tracing Level set to Warning"; test.LogMessage = oldMessage; // Initially with TracingLevel at Warning, logging of Warning type does not get filtered out. - Assert.Equal(SourceLevels.Warning, Logger.TracingLevel); + Assert.AreEqual(SourceLevels.Warning, Logger.TracingLevel); { test.EventType = TraceEventType.Warning; test.Write(); @@ -405,7 +405,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost //Now Update the tracing level to Error. Now logging both of Warning type gets filtered and only Error type should succeed. Logger.TracingLevel = SourceLevels.Error; - Assert.Equal(SourceLevels.Error, Logger.TracingLevel); + Assert.AreEqual(SourceLevels.Error, Logger.TracingLevel); string newMessage = @"New Message After Tracing Level set to Error"; test.LogMessage = newMessage; @@ -439,7 +439,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost string oldMessage = @"Old Message with Tracing Level set to Error"; test.LogMessage = oldMessage; // Initially with TracingLevel at Error, logging of Warning type gets filtered out. - Assert.Equal(SourceLevels.Error, Logger.TracingLevel); + Assert.AreEqual(SourceLevels.Error, Logger.TracingLevel); { test.EventType = TraceEventType.Warning; test.Write(); @@ -460,7 +460,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost //Now Update the tracing level to Warning. Now logging both of Error type and Warning type should succeed. Logger.TracingLevel = SourceLevels.Warning; - Assert.Equal(SourceLevels.Warning, Logger.TracingLevel); + Assert.AreEqual(SourceLevels.Warning, Logger.TracingLevel); string newMessage = @"New Message After Tracing Level set to Warning"; test.LogMessage = newMessage; diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/ScriptFileTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/ScriptFileTests.cs index 89cd1aec..a5d5c194 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/ScriptFileTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/ScriptFileTests.cs @@ -6,7 +6,7 @@ using System; using System.Linq; using Microsoft.SqlTools.Utility; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost { @@ -43,7 +43,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// /// Validate GetLinesInRange with invalid range /// - [Fact] + [Test] public void GetLinesInRangeWithInvalidRangeTest() { ScriptFile scriptFile = GetTestScriptFile(); @@ -68,7 +68,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// /// Validate GetLinesInRange /// - [Fact] + [Test] public void GetLinesInRangeTest() { ScriptFile scriptFile = GetTestScriptFile(); @@ -93,7 +93,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost Assert.True(queryLines[1].StartsWith(line), "GetLine text is correct"); } - [Fact] + [Test] public void GetOffsetAtPositionTest() { ScriptFile scriptFile = GetTestScriptFile(); @@ -105,7 +105,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost Assert.True(position.Line == 2 && position.Column == 5, "Position is at expected location"); } - [Fact] + [Test] public void GetRangeBetweenOffsetsTest() { ScriptFile scriptFile = GetTestScriptFile(); @@ -115,7 +115,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost Assert.NotNull(range); } - [Fact] + [Test] public void CanApplySingleLineInsert() { AssertFileChange( @@ -131,7 +131,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost }); } - [Fact] + [Test] public void CanApplySingleLineReplace() { AssertFileChange( @@ -147,7 +147,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost }); } - [Fact] + [Test] public void CanApplySingleLineDelete() { AssertFileChange( @@ -163,7 +163,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost }); } - [Fact] + [Test] public void CanApplyMultiLineInsert() { AssertFileChange( @@ -179,7 +179,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost }); } - [Fact] + [Test] public void CanApplyMultiLineReplace() { AssertFileChange( @@ -195,7 +195,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost }); } - [Fact] + [Test] public void CanApplyMultiLineReplaceWithRemovedLines() { AssertFileChange( @@ -211,7 +211,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost }); } - [Fact] + [Test] public void CanApplyMultiLineDelete() { AssertFileChange( @@ -227,7 +227,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost }); } - [Fact] + [Test] public void ThrowsExceptionWithEditOutsideOfRange() { Assert.Throws( @@ -258,7 +258,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost // Apply the FileChange and assert the resulting contents fileToChange.ApplyChange(fileChange); - Assert.Equal(expectedString, fileToChange.Contents); + Assert.AreEqual(expectedString, fileToChange.Contents); } } @@ -279,50 +279,50 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost "Line One\r\nLine Two\r\nLine Three\r\nLine Four\r\nLine Five\r\n"); } - [Fact] + [Test] public void CanGetWholeLine() { string[] lines = scriptFile.GetLinesInRange( new BufferRange(5, 1, 5, 10)); - Assert.Equal(1, lines.Length); - Assert.Equal("Line Five", lines[0]); + Assert.AreEqual(1, lines.Length); + Assert.AreEqual("Line Five", lines[0]); } - [Fact] + [Test] public void CanGetMultipleWholeLines() { string[] lines = scriptFile.GetLinesInRange( new BufferRange(2, 1, 4, 10)); - Assert.Equal(TestStringLines.Skip(1).Take(3), lines); + Assert.AreEqual(TestStringLines.Skip(1).Take(3), lines); } - [Fact] + [Test] public void CanGetSubstringInSingleLine() { string[] lines = scriptFile.GetLinesInRange( new BufferRange(4, 3, 4, 8)); - Assert.Equal(1, lines.Length); - Assert.Equal("ne Fo", lines[0]); + Assert.AreEqual(1, lines.Length); + Assert.AreEqual("ne Fo", lines[0]); } - [Fact] + [Test] public void CanGetEmptySubstringRange() { string[] lines = scriptFile.GetLinesInRange( new BufferRange(4, 3, 4, 3)); - Assert.Equal(1, lines.Length); - Assert.Equal("", lines[0]); + Assert.AreEqual(1, lines.Length); + Assert.AreEqual("", lines[0]); } - [Fact] + [Test] public void CanGetSubstringInMultipleLines() { string[] expectedLines = new string[] @@ -336,10 +336,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost scriptFile.GetLinesInRange( new BufferRange(2, 6, 4, 9)); - Assert.Equal(expectedLines, lines); + Assert.AreEqual(expectedLines, lines); } - [Fact] + [Test] public void CanGetRangeAtLineBoundaries() { string[] expectedLines = new string[] @@ -353,7 +353,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost scriptFile.GetLinesInRange( new BufferRange(2, 9, 4, 1)); - Assert.Equal(expectedLines, lines); + Assert.AreEqual(expectedLines, lines); } } @@ -371,7 +371,7 @@ First line "); } - [Fact] + [Test] public void CanOffsetByLine() { AssertNewPosition( @@ -385,7 +385,7 @@ First line 1, 1); } - [Fact] + [Test] public void CanOffsetByColumn() { AssertNewPosition( @@ -399,7 +399,7 @@ First line 2, 2); } - [Fact] + [Test] public void ThrowsWhenPositionOutOfRange() { // Less than line range @@ -443,7 +443,7 @@ First line }); } - [Fact] + [Test] public void CanFindBeginningOfLine() { AssertNewPosition( @@ -452,7 +452,7 @@ First line 4, 5); } - [Fact] + [Test] public void CanFindEndOfLine() { AssertNewPosition( @@ -461,7 +461,7 @@ First line 4, 15); } - [Fact] + [Test] public void CanComposePositionOperations() { AssertNewPosition( @@ -493,8 +493,8 @@ First line originalLine, originalColumn)); - Assert.Equal(expectedLine, newPosition.Line); - Assert.Equal(expectedColumn, newPosition.Column); + Assert.AreEqual(expectedLine, newPosition.Line); + Assert.AreEqual(expectedColumn, newPosition.Column); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/ServiceHostTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/ServiceHostTests.cs index d9707740..e4756613 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/ServiceHostTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/ServiceHostTests.cs @@ -8,13 +8,13 @@ using System.Threading.Tasks; using Microsoft.SqlTools.Hosting.Contracts; using Microsoft.SqlTools.Hosting.Protocol; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost { public class ServiceHostTests { - [Fact] + [Test] public async Task InitializeResultShouldIncludeTheCharactersThatWouldTriggerTheCompletion() { Hosting.ServiceHost host = Hosting.ServiceHost.Instance; diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/SrTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/SrTests.cs index c60c0add..217b93ca 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/SrTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/SrTests.cs @@ -3,7 +3,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.SqlTools.ServiceLayer.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost { @@ -17,7 +17,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost /// The purpose of this test is for code coverage. It's probably better to just /// exclude string resources in the code coverage report than maintain this test. /// - [Fact] + [Test] public void SrStringsTest() { var culture = SR.Culture; @@ -208,46 +208,46 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost var schemaHierarchyColumnEncryptionKeys = SR.SchemaHierarchy_ColumnEncryptionKeys; } - [Fact] + [Test] public void SrStringsTestWithEnLocalization() { string locale = "en"; var args = new string[] { "--locale", locale }; ServiceLayerCommandOptions options = new ServiceLayerCommandOptions(args); - Assert.Equal(SR.Culture.Name, options.Locale); - Assert.Equal(options.Locale, locale); + Assert.AreEqual(SR.Culture.Name, options.Locale); + Assert.AreEqual(options.Locale, locale); var TestLocalizationConstant = SR.TestLocalizationConstant; - Assert.Equal(TestLocalizationConstant, "test"); + Assert.AreEqual("test", TestLocalizationConstant); } - // [Fact] + // [Test] public void SrStringsTestWithEsLocalization() { string locale = "es"; var args = new string[] { "--locale", locale }; ServiceLayerCommandOptions options = new ServiceLayerCommandOptions(args); - Assert.Equal(SR.Culture.Name, options.Locale); - Assert.Equal(options.Locale, locale); + Assert.AreEqual(SR.Culture.Name, options.Locale); + Assert.AreEqual(options.Locale, locale); var TestLocalizationConstant = SR.TestLocalizationConstant; - Assert.Equal(TestLocalizationConstant, "prueba"); + Assert.AreEqual("prueba", TestLocalizationConstant); // Reset the locale SrStringsTestWithEnLocalization(); } - [Fact] + [Test] public void SrStringsTestWithNullLocalization() { SR.Culture = null; var args = new string[] { "" }; ServiceLayerCommandOptions options = new ServiceLayerCommandOptions(args); Assert.Null(SR.Culture); - Assert.Equal(options.Locale, ""); + Assert.AreEqual("", options.Locale); var TestLocalizationConstant = SR.TestLocalizationConstant; - Assert.Equal(TestLocalizationConstant, "test"); + Assert.AreEqual("test", TestLocalizationConstant); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SqlAssessment/GenerateScriptOperationTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SqlAssessment/GenerateScriptOperationTests.cs index 77ab90f3..b70c9198 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SqlAssessment/GenerateScriptOperationTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SqlAssessment/GenerateScriptOperationTests.cs @@ -13,8 +13,6 @@ using Microsoft.SqlTools.ServiceLayer.SqlAssessment.Contracts; using Microsoft.SqlTools.ServiceLayer.TaskServices; using Moq; using NUnit.Framework; -using Xunit; -using Assert = Xunit.Assert; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlAssessment { @@ -125,14 +123,14 @@ VALUES ('D N2','C-2','Microsoft Ruleset','1.3','Warning','Msg''1','proj[*]_dev','Database','http://HL2','2001-05-25 01:42:00.000 +03:00'), ('D''N1','C''3','Microsoft Ruleset','1.3','Critical','Msg''1','proj[*]_dev','Server','HL''1','2001-05-25 01:42:00.000 -01:30')"; - [Fact] + [Test] public void GenerateScriptTest() { var scriptText = GenerateScriptOperation.GenerateScript(SampleParams, CancellationToken.None); - Assert.Equal(SampleScript, scriptText); + Assert.AreEqual(SampleScript, scriptText); } - [Fact] + [Test] public void ExecuteTest() { var subject = new GenerateScriptOperation(SampleParams); @@ -147,8 +145,8 @@ VALUES private void ValidateScriptAdded(object sender, TaskEventArgs e) { - Assert.Equal(SqlTaskStatus.Succeeded, e.TaskData.Status); - Assert.Equal(SampleScript, e.TaskData.Script); + Assert.AreEqual(SqlTaskStatus.Succeeded, e.TaskData.Status); + Assert.AreEqual(SampleScript, e.TaskData.Script); } private static Task DummyOpFunction(SqlTask _) diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SqlContext/SettingsTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SqlContext/SettingsTests.cs index f76ac8e5..addfcca0 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SqlContext/SettingsTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/SqlContext/SettingsTests.cs @@ -4,7 +4,7 @@ // using Microsoft.SqlTools.ServiceLayer.SqlContext; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlContext { @@ -16,7 +16,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlContext /// /// Validate that the Language Service default settings are as expected /// - [Fact] + [Test] public void ValidateLanguageServiceDefaults() { var sqlToolsSettings = new SqlToolsSettings(); @@ -32,7 +32,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlContext /// /// Validate that the IsDiagnosticsEnabled flag behavior /// - [Fact] + [Test] public void ValidateIsDiagnosticsEnabled() { var sqlToolsSettings = new SqlToolsSettings(); @@ -55,7 +55,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlContext /// /// Validate that the IsSuggestionsEnabled flag behavior /// - [Fact] + [Test] public void ValidateIsSuggestionsEnabled() { var sqlToolsSettings = new SqlToolsSettings(); @@ -78,7 +78,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlContext /// /// Validate that the IsQuickInfoEnabled flag behavior /// - [Fact] + [Test] public void ValidateIsQuickInfoEnabled() { var sqlToolsSettings = new SqlToolsSettings(); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/SqlTaskTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/SqlTaskTests.cs index 12c1eb84..d7b6a1a3 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/SqlTaskTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/SqlTaskTests.cs @@ -7,13 +7,13 @@ using System; using System.Threading; using System.Threading.Tasks; using Microsoft.SqlTools.ServiceLayer.TaskServices; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices { public class SqlTaskTests { - [Fact] + [Test] public void CreateSqlTaskGivenInvalidArgumentShouldThrowException() { DatabaseOperationStub operation = new DatabaseOperationStub(); @@ -22,7 +22,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices Assert.Throws(() => new SqlTask(new TaskMetadata(), null, null)); } - [Fact] + [Test] public void CreateSqlTaskShouldGenerateANewId() { SqlTask sqlTask = new SqlTask(new TaskMetadata(), new DatabaseOperationStub().FunctionToRun, null); @@ -33,7 +33,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices Assert.False(sqlTask.TaskId.CompareTo(sqlTask2.TaskId) == 0); } - [Fact] + [Test] public async Task RunShouldRunTheFunctionAndGetTheResult() { SqlTaskStatus expectedStatus = SqlTaskStatus.Succeeded; @@ -43,20 +43,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices TaskStatus = expectedStatus }; SqlTask sqlTask = new SqlTask(new TaskMetadata(), operation.FunctionToRun, null); - Assert.Equal(sqlTask.TaskStatus, SqlTaskStatus.NotStarted); + Assert.AreEqual(SqlTaskStatus.NotStarted, sqlTask.TaskStatus); Task taskToVerify = sqlTask.RunAsync().ContinueWith(task => { - Assert.Equal(sqlTask.TaskStatus, expectedStatus); - Assert.Equal(sqlTask.IsCompleted, true); + Assert.AreEqual(sqlTask.TaskStatus, expectedStatus); + Assert.AreEqual(true, sqlTask.IsCompleted); Assert.True(sqlTask.Duration > 0); }); - Assert.Equal(sqlTask.TaskStatus, SqlTaskStatus.InProgress); + Assert.AreEqual(SqlTaskStatus.InProgress, sqlTask.TaskStatus); Thread.Sleep(1000); operation.Stop(); await taskToVerify; } - [Fact] + [Test] public async Task ToTaskInfoShouldReturnTaskInfo() { SqlTaskStatus expectedStatus = SqlTaskStatus.Succeeded; @@ -74,15 +74,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices Task taskToVerify = sqlTask.RunAsync().ContinueWith(task => { var taskInfo = sqlTask.ToTaskInfo(); - Assert.Equal(taskInfo.TaskId, sqlTask.TaskId.ToString()); - Assert.Equal(taskInfo.ServerName, "server name"); - Assert.Equal(taskInfo.DatabaseName, "database name"); + Assert.AreEqual(taskInfo.TaskId, sqlTask.TaskId.ToString()); + Assert.AreEqual("server name", taskInfo.ServerName); + Assert.AreEqual("database name", taskInfo.DatabaseName); }); operation.Stop(); await taskToVerify; } - [Fact] + [Test] public async Task FailedOperationShouldReturnTheFailedResult() { SqlTaskStatus expectedStatus = SqlTaskStatus.Failed; @@ -92,20 +92,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices TaskStatus = expectedStatus }; SqlTask sqlTask = new SqlTask(new TaskMetadata(), operation.FunctionToRun, operation.FunctionToCancel); - Assert.Equal(sqlTask.TaskStatus, SqlTaskStatus.NotStarted); + Assert.AreEqual(SqlTaskStatus.NotStarted, sqlTask.TaskStatus); Task taskToVerify = sqlTask.RunAsync().ContinueWith(task => { - Assert.Equal(sqlTask.TaskStatus, expectedStatus); - Assert.Equal(sqlTask.IsCompleted, true); + Assert.AreEqual(sqlTask.TaskStatus, expectedStatus); + Assert.AreEqual(true, sqlTask.IsCompleted); // Assert.True(sqlTask.Duration > 0); }); - Assert.Equal(sqlTask.TaskStatus, SqlTaskStatus.InProgress); + Assert.AreEqual(SqlTaskStatus.InProgress, sqlTask.TaskStatus); Thread.Sleep(1000); operation.Stop(); await taskToVerify; } - [Fact] + [Test] public async Task CancelingTheTaskShouldCancelTheOperation() { SqlTaskStatus expectedStatus = SqlTaskStatus.Canceled; @@ -114,20 +114,20 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices { }; SqlTask sqlTask = new SqlTask(new TaskMetadata(), operation.FunctionToRun, operation.FunctionToCancel); - Assert.Equal(sqlTask.TaskStatus, SqlTaskStatus.NotStarted); + Assert.AreEqual(SqlTaskStatus.NotStarted, sqlTask.TaskStatus); Task taskToVerify = sqlTask.RunAsync().ContinueWith(task => { - Assert.Equal(sqlTask.TaskStatus, expectedStatus); - Assert.Equal(sqlTask.IsCancelRequested, true); + Assert.AreEqual(sqlTask.TaskStatus, expectedStatus); + Assert.AreEqual(true, sqlTask.IsCancelRequested); Assert.True(sqlTask.Duration > 0); }); - Assert.Equal(sqlTask.TaskStatus, SqlTaskStatus.InProgress); + Assert.AreEqual(SqlTaskStatus.InProgress, sqlTask.TaskStatus); Thread.Sleep(1000); sqlTask.Cancel(); await taskToVerify; } - [Fact] + [Test] public async Task FailedOperationShouldFailTheTask() { SqlTaskStatus expectedStatus = SqlTaskStatus.Failed; @@ -136,19 +136,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices { }; SqlTask sqlTask = new SqlTask(new TaskMetadata(), operation.FunctionToRun, operation.FunctionToCancel); - Assert.Equal(sqlTask.TaskStatus, SqlTaskStatus.NotStarted); + Assert.AreEqual(SqlTaskStatus.NotStarted, sqlTask.TaskStatus); Task taskToVerify = sqlTask.RunAsync().ContinueWith(task => { - Assert.Equal(sqlTask.TaskStatus, expectedStatus); + Assert.AreEqual(sqlTask.TaskStatus, expectedStatus); Assert.True(sqlTask.Duration > 0); }); - Assert.Equal(sqlTask.TaskStatus, SqlTaskStatus.InProgress); + Assert.AreEqual(SqlTaskStatus.InProgress, sqlTask.TaskStatus); Thread.Sleep(1000); operation.FailTheOperation(); await taskToVerify; } - [Fact] + [Test] public async Task RunScriptShouldReturnScriptContent() { SqlTaskStatus expectedStatus = SqlTaskStatus.Succeeded; @@ -158,11 +158,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices TaskStatus = expectedStatus }; SqlTask sqlTask = new SqlTask(new TaskMetadata(), operation.FunctionToScript, null); - Assert.Equal(sqlTask.TaskStatus, SqlTaskStatus.NotStarted); + Assert.AreEqual(SqlTaskStatus.NotStarted, sqlTask.TaskStatus); Task taskToVerify = sqlTask.RunAsync().ContinueWith(task => { - Assert.Equal(sqlTask.TaskStatus, expectedStatus); - Assert.Equal(sqlTask.IsCompleted, true); + Assert.AreEqual(sqlTask.TaskStatus, expectedStatus); + Assert.AreEqual(true, sqlTask.IsCompleted); Assert.NotNull(operation.TaskScript); Assert.True(!string.IsNullOrEmpty(operation.TaskScript.Script)); }); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/TaskManagerTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/TaskManagerTests.cs index 4e164360..50cea99d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/TaskManagerTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/TaskManagerTests.cs @@ -6,7 +6,7 @@ using System; using System.Threading.Tasks; using Microsoft.SqlTools.ServiceLayer.TaskServices; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices { @@ -19,7 +19,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices DatabaseName = "database name" }; - [Fact] + [Test] public void ManagerInstanceWithNoTaskShouldNotBreakOnCancelTask() { SqlTaskManager manager = new SqlTaskManager(); @@ -27,7 +27,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices manager.CancelTask(Guid.NewGuid()); } - [Fact] + [Test] public async Task VerifyCreateAndRunningTask() { using (SqlTaskManager manager = new SqlTaskManager()) @@ -60,7 +60,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices } - [Fact] + [Test] public async Task CancelTaskShouldCancelTheOperation() { using (SqlTaskManager manager = new SqlTaskManager()) @@ -76,8 +76,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices Task taskToVerify = sqlTask.RunAsync().ContinueWith(task => { - Assert.Equal(expectedStatus, sqlTask.TaskStatus); - Assert.Equal(sqlTask.IsCancelRequested, true); + Assert.AreEqual(expectedStatus, sqlTask.TaskStatus); + Assert.AreEqual(true, sqlTask.IsCancelRequested); manager.Reset(); }); @@ -87,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices } - [Fact] + [Test] public async Task VerifyScriptTask() { using (SqlTaskManager manager = new SqlTaskManager()) diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/TaskServiceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/TaskServiceTests.cs index 92d147b5..c4caa50b 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/TaskServiceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/TaskServices/TaskServiceTests.cs @@ -13,7 +13,7 @@ using Microsoft.SqlTools.ServiceLayer.TaskServices.Contracts; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices { @@ -34,7 +34,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices service.InitializeService(serviceHostMock.Object); } - [Fact] + [Test] public async Task TaskListRequestErrorsIfParameterIsNull() { object errorResponse = null; @@ -46,7 +46,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices Assert.True(((string)errorResponse).Contains("ArgumentNullException")); } - [Fact] + [Test] public void NewTaskShouldSendNotification() { serviceHostMock.AddEventHandling(TaskCreatedNotification.Type, null); @@ -64,7 +64,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices It.Is(t => t.TaskId == sqlTask.TaskId.ToString())), Times.AtLeastOnce()); } - [Fact] + [Test] public async Task CancelTaskShouldCancelTheOperationAndSendNotification() { serviceHostMock.AddEventHandling(TaskCreatedNotification.Type, null); @@ -93,7 +93,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.TaskServices } - [Fact] + [Test] public async Task TaskListTaskShouldReturnAllTasks() { serviceHostMock.AddEventHandling(TaskCreatedNotification.Type, null); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/CommandOptionsTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/CommandOptionsTests.cs index f75309d3..c1258d3b 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/CommandOptionsTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/CommandOptionsTests.cs @@ -5,7 +5,7 @@ using System.IO; using Microsoft.SqlTools.ServiceLayer.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility { @@ -15,7 +15,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility public class CommandOptionsTests { - [Fact] + [Test] public void UsageIsShownWhenHelpFlagProvided() { var args = new string[] {"--help"}; @@ -23,10 +23,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility Assert.NotNull(options); Assert.True(options.ShouldExit); - Assert.Equal(options.Locale, string.Empty); + Assert.AreEqual(options.Locale, string.Empty); } - [Fact] + [Test] public void UsageIsShownWhenBadArgumentsProvided() { var args = new string[] {"--unknown-argument", "/bad-argument"}; @@ -34,10 +34,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility Assert.NotNull(options); Assert.True(options.ShouldExit); - Assert.Equal(options.Locale, string.Empty); + Assert.AreEqual(options.Locale, string.Empty); } - [Fact] + [Test] public void DefaultValuesAreUsedWhenNoArgumentsAreProvided() { int? testNo = 1; @@ -97,10 +97,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility Assert.True(options.Locale == locale, $"{MsgPrefix} options:{nameof(locale)} should be '{locale}'"); } - [Theory] - [InlineData("en")] - [InlineData("es")] - public void LocaleSetWhenProvided(string locale) + [Test] + public void LocaleSetWhenProvided([Values("en", "es")] string locale) { var args = new string[] {"--locale", locale}; ServiceLayerCommandOptions options = new ServiceLayerCommandOptions(args); ; @@ -108,10 +106,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Asserting all options were properly set Assert.NotNull(options); Assert.False(options.ShouldExit); - Assert.Equal(options.Locale, locale); + Assert.AreEqual(options.Locale, locale); } - [Fact] + [Test] public void ShouldExitNotSetWhenInvalidLocale() { string locale = "invalid"; @@ -123,7 +121,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility Assert.False(options.ShouldExit); } - [Fact] + [Test] public void LocaleNotSetWhenNotProvided() { var args = new string[] {}; @@ -132,11 +130,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Asserting all options were properly set Assert.NotNull(options); Assert.False(options.ShouldExit); - Assert.Equal(options.Locale, string.Empty); + Assert.AreEqual(options.Locale, string.Empty); } - [Fact] + [Test] public void TracingLevelSet() { string expectedLevel = "Information"; @@ -146,10 +144,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Asserting all options were properly set Assert.NotNull(options); Assert.False(options.ShouldExit); - Assert.Equal(options.TracingLevel, expectedLevel); + Assert.AreEqual(options.TracingLevel, expectedLevel); } - [Fact] + [Test] public void AutoFlushLogSet() { bool expectedAutoFlush = true; @@ -159,10 +157,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Asserting all options were properly set Assert.NotNull(options); Assert.False(options.ShouldExit); - Assert.Equal(options.AutoFlushLog, expectedAutoFlush); + Assert.AreEqual(options.AutoFlushLog, expectedAutoFlush); } - [Fact] + [Test] public void LogFilePathSet() { string expectedFilePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); @@ -172,7 +170,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Asserting all options were properly set Assert.NotNull(options); Assert.False(options.ShouldExit); - Assert.Equal(options.LogFilePath, expectedFilePath); + Assert.AreEqual(options.LogFilePath, expectedFilePath); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/LongListTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/LongListTests.cs index e165507f..99f6766c 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/LongListTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/LongListTests.cs @@ -6,7 +6,7 @@ using System; using System.Linq; using Microsoft.SqlTools.ServiceLayer.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility { @@ -15,7 +15,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility /// public class LongListTests { - [Fact] + [Test] public void LongListConstruction() { // If: I construct a new long list @@ -23,42 +23,36 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Then: // ... There should be no values in the list - Assert.Equal(0, ll.Count); + Assert.AreEqual(0, ll.Count); } #region GetItem / Add Tests - [Theory] - [InlineData(-1L)] // Negative index - [InlineData(0L)] // Index equal to count of elements - [InlineData(100L)] // Index larger than elements - public void GetItemOutOfRange(long index) + [Test] + public void GetItemOutOfRange([Values(-1L, 0L, 100L)] long index) { // If: I construct a new long list LongList ll = new LongList(); // Then: // ... There should be no values in the list - Assert.Throws(() => ll[index]); + Assert.Throws(() => { var x = ll[index]; }) ; Assert.Throws(() => ll.GetItem(index)); } - [Theory] - [InlineData(0)] // Element at beginning - [InlineData(1)] // Element in middle - [InlineData(2)] // Element at end - public void GetItemNotExpanded(long index) + [Test] + public void GetItemNotExpanded([Values(0,1,2)] long index) { // If: I construct a new long list with a couple items in it LongList ll = new LongList {0, 1, 2}; // Then: I can read back the value from the list - Assert.Equal(3, ll.Count); - Assert.Equal(index, ll[index]); - Assert.Equal(index, ll.GetItem(index)); + Assert.AreEqual(3, ll.Count); + Assert.AreEqual(index, ll[index]); + Assert.AreEqual(index, ll.GetItem(index)); } - [Fact] + [Test] public void GetItemExanded() { // If: I construct a new long list that is guaranteed to have been expanded @@ -70,11 +64,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Then: // ... All the added values should be accessible - Assert.Equal(10, ll.Count); + Assert.AreEqual(10, ll.Count); for (int i = 0; i < 10; i++) { - Assert.Equal(i, ll[i]); - Assert.Equal(i, ll.GetItem(i)); + Assert.AreEqual(i, ll[i]); + Assert.AreEqual(i, ll.GetItem(i)); } } @@ -82,11 +76,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility #region SetItem Tests - [Theory] - [InlineData(-1L)] // Negative index - [InlineData(0L)] // Index equal to count of elements - [InlineData(100L)] // Index larger than elements - public void SetItemOutOfRange(long index) + [Test] + public void SetItemOutOfRange([Values(-1L, 0L, 100L)] long index) { // If: I construct a new long list LongList ll = new LongList(); @@ -97,7 +88,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility Assert.Throws(() => ll.SetItem(index, 8)); } - [Fact] + [Test] public void SetItemNotExpanded() { // If: @@ -109,11 +100,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility ll.SetItem(i, 8); } - // Then: All values in the list should be 8 - Assert.All(ll, i => Assert.Equal(8, i)); + Assert.That(ll, Has.All.EqualTo(8), "All values in the list should be 8"); } - [Fact] + [Test] public void SetItemIndexerNotExpanded() { // If: @@ -125,11 +115,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility ll[i] = 8; } - // Then: All values in the list should be 8 - Assert.All(ll, i => Assert.Equal(8, i)); + Assert.That(ll, Has.All.EqualTo(8), "All values in the list should be 8"); } - [Fact] + [Test] public void SetItemExpanded() { // If: @@ -146,11 +135,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility ll.SetItem(i, 8); } - // Then: All values in the list should be 8 - Assert.All(ll, i => Assert.Equal(8, i)); + Assert.That(ll, Has.All.EqualTo(8), "All values in the list should be 8"); } - [Fact] + [Test] public void SetItemIndexerExpanded() { // If: @@ -167,19 +155,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility ll[i] = 8; } - // Then: All values in the list should be 8 - Assert.All(ll, i => Assert.Equal(8, i)); + Assert.That(ll, Has.All.EqualTo(8), "All values in the list should be 8"); } #endregion #region RemoveAt Tests - [Theory] - [InlineData(-1L)] // Negative index - [InlineData(0L)] // Index equal to count of elements - [InlineData(100L)] // Index larger than elements - public void RemoveOutOfRange(long index) + [Test] + public void RemoveOutOfRange([Values(-1L, 0L, 100L)] long index) { // If: I construct a new long list LongList ll = new LongList(); @@ -189,11 +173,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility Assert.Throws(() => ll.RemoveAt(index)); } - [Theory] - [InlineData(0)] // Remove at beginning of list - [InlineData(2)] // Remove from middle of list - [InlineData(4)] // Remove at end of list - public void RemoveAtNotExpanded(long index) + [Test] + public void RemoveAtNotExpanded([Values(0,2,4)] long index) { // If: // ... I create a long list with a few elements in it (and one element that will be removed) @@ -208,13 +189,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Then: // ... The count should have subtracted - Assert.Equal(4, ll.Count); + Assert.AreEqual(4, ll.Count); - // ... All values should be 8 since we removed the 1 - Assert.All(ll, i => Assert.Equal(8, i)); + Assert.That(ll, Has.All.EqualTo(8), "All values in the list should be 8 since we removed the 1"); } - [Fact] + [Test] public void RemoveAtExpanded() { // If: @@ -240,7 +220,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // ... The second half of the values should still remain for (int i = 0; i < 10; i++) { - Assert.Equal(i, ll[i]); + Assert.AreEqual(i, ll[i]); } // If: @@ -256,7 +236,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility for (int i = 0; i < 10; i++) { int index = j * 10 + i; - Assert.Equal(i, ll[index]); + Assert.AreEqual(i, ll[index]); } } } @@ -265,7 +245,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility #region IEnumerable Tests - [Fact] + [Test] public void GetEnumerator() { // Setup: Create a long list with a handful of elements @@ -280,11 +260,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility int val = 0; foreach (int element in ll) { - Assert.Equal(val++, element); + Assert.AreEqual(val++, element); } } - [Fact] + [Test] public void GetEnumeratorExpanded() { // Setup: Create a long list with a handful of elements @@ -299,15 +279,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility int val = 0; foreach (int element in ll) { - Assert.Equal(val++, element); + Assert.AreEqual(val++, element); } } - [Theory] - [InlineData(-1)] // Negative - [InlineData(5)] // Equal to count - [InlineData(100)] // Far too large - public void LongSkipOutOfRange(long index) + [Test] + public void LongSkipOutOfRange([Values(-1,5,100)] long index) { // Setup: Create a long list with a handful of elements LongList ll = new LongList {ExpandListSize = 2}; @@ -323,10 +300,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility Assert.Throws(() => ll.LongSkip(index).ToArray()); } - [Theory] - [InlineData(0)] // Don't actually skip anything - [InlineData(2)] // Skip within the short list - public void LongSkip(long index) + [Test] + public void LongSkip([Values(0,2)] long index) { // Setup: Create a long list with a handful of elements LongList ll = new LongList(); @@ -341,15 +316,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Then: The elements including the skip start index should be in the output for (int i = 0; i < values.Length; i++) { - Assert.Equal(ll[i+index], values[i]); + Assert.AreEqual(ll[i+index], values[i]); } } - [Theory] - [InlineData(0)] // Don't actually skip anything - [InlineData(1)] // Skip within the short list - [InlineData(3)] // Skip across expanded lists - public void LongSkipExpanded(long index) + [Test] + public void LongSkipExpanded([Values(0,1,3)] long index) { // Setup: Create a long list with a handful of elements LongList ll = new LongList {ExpandListSize = 2}; @@ -364,7 +336,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Then: The elements including the skip start index should be in the output for (int i = 0; i < values.Length; i++) { - Assert.Equal(ll[i+index], values[i]); + Assert.AreEqual(ll[i+index], values[i]); } } @@ -373,7 +345,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility /// /// Add and remove and item in a LongList causing an expansion /// - [Fact] + [Test] public void LongListExpandTest() { var longList = new LongList {ExpandListSize = 3}; @@ -381,7 +353,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility { longList.Add(i); } - Assert.Equal(longList.Count, 6); + Assert.AreEqual(6, longList.Count); Assert.NotNull(longList.GetItem(4)); bool didEnum = false; @@ -394,7 +366,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility Assert.True(didEnum); longList.RemoveAt(4); - Assert.Equal(longList.Count, 5); + Assert.AreEqual(5, longList.Count); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/SrTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/SrTests.cs index 0d5a1829..7a6a7a85 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/SrTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/SrTests.cs @@ -4,7 +4,7 @@ // using System.Globalization; -using Xunit; +using NUnit.Framework; using ServiceLayerSr = Microsoft.SqlTools.ServiceLayer.SR; @@ -15,7 +15,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility /// /// Add and remove and item in a LongList /// - [Fact] + [Test] public void SrPropertiesTest() { ServiceLayerSr.Culture = CultureInfo.CurrentCulture; diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TaskExtensionTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TaskExtensionTests.cs index fc95253d..79747643 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TaskExtensionTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TaskExtensionTests.cs @@ -6,7 +6,7 @@ using System; using System.Threading.Tasks; using Microsoft.SqlTools.ServiceLayer.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility { @@ -14,7 +14,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility { #region Continue with Action - [Fact] + [Test] public async Task ContinueWithOnFaultedActionNullContinuation() { // Setup: Create a task that will definitely fault @@ -26,10 +26,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility await continuationTask; // Then: The task should have completed without fault - Assert.Equal(TaskStatus.RanToCompletion, continuationTask.Status); + Assert.AreEqual(TaskStatus.RanToCompletion, continuationTask.Status); } - [Fact] + [Test] public async Task ContinueWithOnFaultedActionContinuatation() { // Setup: @@ -46,13 +46,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Then: // ... The task should have completed without fault - Assert.Equal(TaskStatus.RanToCompletion, continuationTask.Status); + Assert.AreEqual(TaskStatus.RanToCompletion, continuationTask.Status); // ... The continuation action should have been called with the original failure task - Assert.Equal(failureTask, providedTask); + Assert.AreEqual(failureTask, providedTask); } - [Fact] + [Test] public async Task ContinueWithOnFaultedActionExceptionInContinuation() { // Setup: @@ -74,17 +74,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Then: // ... The task should have completed without fault - Assert.Equal(TaskStatus.RanToCompletion, continuationTask.Status); + Assert.AreEqual(TaskStatus.RanToCompletion, continuationTask.Status); // ... The continuation action should have been called with the original failure task - Assert.Equal(failureTask, providedTask); + Assert.AreEqual(failureTask, providedTask); } #endregion #region Continue with Task - [Fact] + [Test] public async Task ContinueWithOnFaultedFuncNullContinuation() { // Setup: Create a task that will definitely fault @@ -97,10 +97,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility await continuationTask; // Then: The task should have completed without fault - Assert.Equal(TaskStatus.RanToCompletion, continuationTask.Status); + Assert.AreEqual(TaskStatus.RanToCompletion, continuationTask.Status); } - [Fact] + [Test] public async Task ContinueWithOnFaultedFuncContinuatation() { // Setup: @@ -122,13 +122,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Then: // ... The task should have completed without fault - Assert.Equal(TaskStatus.RanToCompletion, continuationTask.Status); + Assert.AreEqual(TaskStatus.RanToCompletion, continuationTask.Status); // ... The continuation action should have been called with the original failure task - Assert.Equal(failureTask, providedTask); + Assert.AreEqual(failureTask, providedTask); } - [Fact] + [Test] public async Task ContinueWithOnFaultedFuncExceptionInContinuation() { // Setup: @@ -150,10 +150,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility // Then: // ... The task should have completed without fault - Assert.Equal(TaskStatus.RanToCompletion, continuationTask.Status); + Assert.AreEqual(TaskStatus.RanToCompletion, continuationTask.Status); // ... The continuation action should have been called with the original failure task - Assert.Equal(failureTask, providedTask); + Assert.AreEqual(failureTask, providedTask); } #endregion diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TestUtils.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TestUtils.cs index a46ad8e2..c7ed4ac4 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TestUtils.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TestUtils.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using Microsoft.SqlTools.Hosting.Protocol; using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility { @@ -47,7 +47,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility public static void VerifyResult(Mock> contextMock, U expected, U actual) { contextMock.Verify(c => c.SendResult(It.IsAny()), Times.Once); - Assert.Equal(expected, actual); + Assert.AreEqual(expected, actual); contextMock.Verify(c => c.SendError(It.IsAny(), It.IsAny()), Times.Never); } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TextUtilitiesTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TextUtilitiesTests.cs index 1e649d32..8984570a 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TextUtilitiesTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/TextUtilitiesTests.cs @@ -4,7 +4,7 @@ // using Microsoft.SqlTools.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility { @@ -13,7 +13,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility /// public class TextUtilitiesTests { - [Fact] + [Test] public void PositionOfCursorFirstLine() { string sql = "EXEC sys.fn_isrolemember "; @@ -21,11 +21,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility int prevNewLine; int cursorPosition = TextUtilities.PositionOfCursor(sql, 0, sql.Length, out prevNewLine); - Assert.Equal(prevNewLine, 0); - Assert.Equal(cursorPosition, sql.Length); + Assert.AreEqual(0, prevNewLine); + Assert.AreEqual(cursorPosition, sql.Length); } - [Fact] + [Test] public void PositionOfCursorSecondLine() { string sql = "--lineone\nEXEC sys.fn_isrolemember "; @@ -33,8 +33,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility int prevNewLine; int cursorPosition = TextUtilities.PositionOfCursor(sql, 1, 15, out prevNewLine); - Assert.Equal(prevNewLine, 10); - Assert.Equal(cursorPosition, 25); + Assert.AreEqual(10, prevNewLine); + Assert.AreEqual(25, cursorPosition); } } } diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/ValidateTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/ValidateTests.cs index 4440520a..de621e79 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/ValidateTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Utility/ValidateTests.cs @@ -5,31 +5,31 @@ using System; using Microsoft.SqlTools.Utility; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility { public class ValidateTests { - [Fact] + [Test] public void IsWithinRangeTest() { Assert.Throws(() => Validate.IsWithinRange("parameterName", 1, 2, 3)); } - [Fact] + [Test] public void IsLessThanTest() { Assert.Throws(() => Validate.IsLessThan("parameterName", 2, 1)); } - [Fact] + [Test] public void IsNotEqualTest() { Assert.Throws(() => Validate.IsNotEqual("parameterName", 1, 1)); } - [Fact] + [Test] public void IsNullOrWhiteSpaceTest() { Assert.Throws(() => Validate.IsNotNullOrWhitespaceString("parameterName", null)); diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/UtilityTests/FromSqlScriptTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/UtilityTests/FromSqlScriptTests.cs index 5db176b9..5f18bc65 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/UtilityTests/FromSqlScriptTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/UtilityTests/FromSqlScriptTests.cs @@ -5,8 +5,9 @@ using System; using System.Collections.Generic; +using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlTools.ServiceLayer.Utility.SqlScriptFormatters; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests { @@ -18,78 +19,88 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests { get { - yield return new object[] {"identifier", new[] {"identifier"}}; - yield return new object[] {"simple.split", new[] {"simple", "split"}}; - yield return new object[] {"multi.simple.split", new[] {"multi", "simple", "split"}}; - yield return new object[] {"[escaped]", new[] {"escaped"}}; - yield return new object[] {"[escaped].[split]", new[] {"escaped", "split"}}; - yield return new object[] {"[multi].[escaped].[split]", new[] {"multi", "escaped", "split"}}; - yield return new object[] {"[escaped]]characters]", new[] {"escaped]characters"}}; - yield return new object[] {"[multi]]escaped]]chars]", new[] {"multi]escaped]chars"}}; - yield return new object[] {"[multi]]]]chars]", new[] {"multi]]chars"}}; - yield return new object[] {"unescaped]chars", new[] {"unescaped]chars"}}; - yield return new object[] {"multi]unescaped]chars", new[] {"multi]unescaped]chars"}}; - yield return new object[] {"multi]]chars", new[] {"multi]]chars"}}; - yield return new object[] {"[escaped.dot]", new[] {"escaped.dot"}}; - yield return new object[] {"mixed.[escaped]", new[] {"mixed", "escaped"}}; - yield return new object[] {"[escaped].mixed", new[] {"escaped", "mixed"}}; - yield return new object[] {"dbo.[[].weird", new[] {"dbo", "[", "weird"}}; + yield return new object[] { "identifier", new[] { "identifier" } }; + yield return new object[] { "simple.split", new[] { "simple", "split" } }; + yield return new object[] { "multi.simple.split", new[] { "multi", "simple", "split" } }; + yield return new object[] { "[escaped]", new[] { "escaped" } }; + yield return new object[] { "[escaped].[split]", new[] { "escaped", "split" } }; + yield return new object[] { "[multi].[escaped].[split]", new[] { "multi", "escaped", "split" } }; + yield return new object[] { "[escaped]]characters]", new[] { "escaped]characters" } }; + yield return new object[] { "[multi]]escaped]]chars]", new[] { "multi]escaped]chars" } }; + yield return new object[] { "[multi]]]]chars]", new[] { "multi]]chars" } }; + yield return new object[] { "unescaped]chars", new[] { "unescaped]chars" } }; + yield return new object[] { "multi]unescaped]chars", new[] { "multi]unescaped]chars" } }; + yield return new object[] { "multi]]chars", new[] { "multi]]chars" } }; + yield return new object[] { "[escaped.dot]", new[] { "escaped.dot" } }; + yield return new object[] { "mixed.[escaped]", new[] { "mixed", "escaped" } }; + yield return new object[] { "[escaped].mixed", new[] { "escaped", "mixed" } }; + yield return new object[] { "dbo.[[].weird", new[] { "dbo", "[", "weird" } }; } - } - - [Theory] - [MemberData(nameof(DecodeMultipartIdentifierTestData))] + } + + [Test] + [TestCaseSource(nameof(DecodeMultipartIdentifierTestData))] public void DecodeMultipartIdentifierTest(string input, string[] output) { // If: I decode the input string[] decoded = FromSqlScript.DecodeMultipartIdentifier(input); // Then: The output should match what was expected - Assert.Equal(output, decoded); + Assert.AreEqual(output, decoded); } - [Theory] - [InlineData("[bracket]closed")] - [InlineData("[bracket][closed")] - [InlineData(".stuff")] - [InlineData(".")] - public void DecodeMultipartIdentifierFailTest(string input) + [Test] + + public void DecodeMultipartIdentifierFailTest([Values( + "[bracket]closed", + "[bracket][closed", + ".stuff", + "." + )] string input) { // If: I decode an invalid input // Then: It should throw an exception Assert.Throws(() => FromSqlScript.DecodeMultipartIdentifier(input)); - } - + } + #endregion - - [Theory] - [InlineData("(0)", "0")] - [InlineData("((0))", "0")] - [InlineData("('')", "")] - [InlineData("('stuff')", "stuff")] - [InlineData("(N'')", "")] - [InlineData("(N'stuff')", "stuff")] - [InlineData("('''stuff')", "'stuff")] - [InlineData("(N'stu''''ff')", "stu''ff")] + + private static readonly object[] unescaped = + { + new object[] {"(0)", "0" }, + new object[] {"((0))", "0" }, + new object[] {"('')", "" }, + new object[] {"('stuff')", "stuff" }, + new object[] {"(N'')", "" }, + new object[] {"(N'stuff')", "stuff" }, + new object[] {"('''stuff')", "'stuff" }, + new object[] {"(N'stu''''ff')", "stu''ff" }, + }; + + [Test, TestCaseSource(nameof(unescaped))] public void UnescapeTest(string input, string output) { - Assert.Equal(output, FromSqlScript.UnwrapLiteral(input)); + Assert.AreEqual(output, FromSqlScript.UnwrapLiteral(input)); } - [Theory] - [InlineData("[name]", true)] - [InlineData("[ name ]", true)] - [InlineData("[na[[]me]", true)] - [InlineData("[]", true)] - [InlineData("name", false)] - [InlineData("[name", false)] - [InlineData("name]", false)] - [InlineData("[]name", false)] - [InlineData("name[]", false)] - [InlineData("[na]me", false)] + private static readonly object[] bracketed = + { + new object[] {"[name]", true }, + new object[] {"[ name ]", true }, + new object[] {"[na[[]me]", true }, + new object[] {"[]", true }, + new object[] {"name", false }, + new object[] {"[name", false}, + new object[] {"name]", false }, + new object[] {"[]name", false}, + new object[] {"name[]", false}, + new object[] {"[na]me", false }, + }; + + [Test, TestCaseSource(nameof(bracketed))] public void BracketedIdentifierTest(string input, bool output) { - Assert.Equal(output, FromSqlScript.IsIdentifierBracketed(input)); + Assert.AreEqual(output, FromSqlScript.IsIdentifierBracketed(input)); } } } \ No newline at end of file diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/UtilityTests/ToSqlScriptTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/UtilityTests/ToSqlScriptTests.cs index bf011230..cca5da6d 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/UtilityTests/ToSqlScriptTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/UtilityTests/ToSqlScriptTests.cs @@ -2,10 +2,11 @@ using System.Collections.Generic; using System.Data.Common; using System.Text.RegularExpressions; +using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts; using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.Utility.SqlScriptFormatters; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests { @@ -13,7 +14,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests { #region FormatValue Tests - [Fact] + [Test] public void NullDbCellTest() { // If: I attempt to format a null db cell @@ -22,7 +23,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests Assert.Throws(() => ToSqlScript.FormatValue(null, column)); } - [Fact] + [Test] public void NullDbColumnTest() { // If: I attempt to format a null db column @@ -38,23 +39,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests Assert.Throws(() => ToSqlScript.FormatValue(new DbCellValue(), column)); } - [Fact] + [Test] public void NullTest() { // If: I attempt to format a db cell that contains null // Then: I should get the null string back DbColumn column = new FormatterTestDbColumn(null); string formattedString = ToSqlScript.FormatValue(new DbCellValue(), new FormatterTestDbColumn(null)); - Assert.Equal(ToSqlScript.NullString, formattedString); + Assert.AreEqual(ToSqlScript.NullString, formattedString); } - [Theory] - [InlineData("BIGINT")] - [InlineData("INT")] - [InlineData("SMALLINT")] - [InlineData("TINYINT")] - public void IntegerNumericTest(string dataType) + [Test] + public void IntegerNumericTest([Values("BIGINT", "INT", "SMALLINT", "TINYINT")] string dataType) { // Setup: Build a column and cell for the integer type column DbColumn column = new FormatterTestDbColumn(dataType); @@ -64,14 +61,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests string output = ToSqlScript.FormatValue(cell, column); // Then: The output string should be able to be converted back into a long - Assert.Equal(cell.RawObject, long.Parse(output)); + Assert.AreEqual(cell.RawObject, long.Parse(output)); } - [Theory] - [InlineData("MONEY", "MONEY", null, null)] - [InlineData("SMALLMONEY", "SMALLMONEY", null, null)] - [InlineData("NUMERIC", @"NUMERIC\(\d+, \d+\)", 18, 0)] - [InlineData("DECIMAL", @"DECIMAL\(\d+, \d+\)", 18, 0)] + private static readonly object[] decimalTypes = + { + new object[] {"MONEY", "MONEY", null, null }, + new object[] {"SMALLMONEY", "SMALLMONEY", null, null }, + new object[] {"NUMERIC", @"NUMERIC\(\d+, \d+\)", 18, 0}, + new object[] {"DECIMAL", @"DECIMAL\(\d+, \d+\)", 18, 0 }, + }; + + [Test, TestCaseSource(nameof(decimalTypes))] public void DecimalTest(string dataType, string regex, int? precision, int? scale) { // Setup: Build a column and cell for the decimal type column @@ -86,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests Assert.True(castRegex.IsMatch(output)); } - [Fact] + [Test] public void DoubleTest() { // Setup: Build a column and cell for the approx numeric type column @@ -97,10 +98,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests string output = ToSqlScript.FormatValue(cell, column); // Then: The output string should be able to be converted back into a double - Assert.Equal(cell.RawObject, double.Parse(output)); + Assert.AreEqual(cell.RawObject, double.Parse(output)); } - [Fact] + [Test] public void FloatTest() { // Setup: Build a column and cell for the approx numeric type column @@ -111,15 +112,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests string output = ToSqlScript.FormatValue(cell, column); // Then: The output string should be able to be converted back into a double - Assert.Equal(cell.RawObject, float.Parse(output)); + Assert.AreEqual(cell.RawObject, float.Parse(output)); } - [Theory] - [InlineData("SMALLDATETIME")] - [InlineData("DATETIME")] - [InlineData("DATETIME2")] - [InlineData("DATE")] - public void DateTimeTest(string dataType) + [Test] + public void DateTimeTest([Values( + "SMALLDATETIME", + "DATETIME", + "DATETIME2", + "DATE")] string dataType) { // Setup: Build a column and cell for the datetime type column DbColumn column = new FormatterTestDbColumn(dataType); @@ -134,7 +135,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests Assert.True(DateTime.TryParse(dateTimeRegex.Match(output).Groups[1].Value, out outputDateTime)); } - [Fact] + [Test] public void DateTimeOffsetTest() { // Setup: Build a column and cell for the datetime offset type column @@ -150,7 +151,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests Assert.True(DateTimeOffset.TryParse(dateTimeRegex.Match(output).Groups[1].Value, out outputDateTime)); } - [Fact] + [Test] public void TimeTest() { // Setup: Build a column and cell for the time type column @@ -166,11 +167,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests Assert.True(TimeSpan.TryParse(dateTimeRegex.Match(output).Groups[1].Value, out outputDateTime)); } - [Theory] - [InlineData("", "N''")] // Make sure empty string works - [InlineData(" \t\r\n", "N' \t\r\n'")] // Test for whitespace - [InlineData("some text \x9152", "N'some text \x9152'")] // Test unicode (UTF-8 and UTF-16) - [InlineData("'", "N''''")] // Test with escaped character + private static readonly object[] stringFormats = + { + new object[] {"", "N''"}, // Make sure empty string works + new object[] {" \t\r\n", "N' \t\r\n'"}, // Test for whitespace + new object[] {"some text \x9152", "N'some text \x9152'"}, // Test unicode (UTF-8 and UTF-16) + new object[] {"'", "N''''"}, // Test with escaped character + }; + + [Test, TestCaseSource(nameof(stringFormats))] public void StringFormattingTest(string input, string expectedOutput) { // Setup: Build a column and cell for the string type column @@ -182,17 +187,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests string output = ToSqlScript.FormatValue(cell, column); // Then: The output string should be quoted and escaped properly - Assert.Equal(expectedOutput, output); + Assert.AreEqual(expectedOutput, output); } - [Theory] - [InlineData("CHAR")] - [InlineData("NCHAR")] - [InlineData("VARCHAR")] - [InlineData("TEXT")] - [InlineData("NTEXT")] - [InlineData("XML")] - public void StringTypeTest(string datatype) + [Test] + + public void StringTypeTest([Values( + "CHAR", + "NCHAR", + "VARCHAR", + "TEXT", + "NTEXT", + "XML" + )]string datatype) { // Setup: Build a column and cell for the string type column DbColumn column = new FormatterTestDbColumn(datatype); @@ -202,14 +209,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests string output = ToSqlScript.FormatValue(cell, column); // Then: The output string should match the output string - Assert.Equal("N'test string'", output); + Assert.AreEqual("N'test string'", output); } - [Theory] - [InlineData("BINARY")] - [InlineData("VARBINARY")] - [InlineData("IMAGE")] - public void BinaryTest(string datatype) + [Test] + public void BinaryTest([Values("BINARY", "VARBINARY", "IMAGE")] string datatype) { // Setup: Build a column and cell for the string type column DbColumn column = new FormatterTestDbColumn(datatype); @@ -226,7 +230,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests Assert.True(regex.IsMatch(output)); } - [Fact] + [Test] public void GuidTest() { // Setup: Build a column and cell for the string type column @@ -245,7 +249,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests #region Format Identifier Tests - [Fact] + [Test] public void FormatIdentifierNull() { // If: I attempt to format null as an identifier @@ -253,33 +257,41 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests Assert.Throws(() => ToSqlScript.FormatIdentifier(null)); } - [Theory] - [InlineData("test", "[test]")] // No escape characters - [InlineData("]test", "[]]test]")] // Escape character at beginning - [InlineData("te]st", "[te]]st]")] // Escape character in middle - [InlineData("test]", "[test]]]")] // Escape character at end - [InlineData("t]]est", "[t]]]]est]")] // Multiple escape characters + private static readonly object[] bracketEscapes = + { + new object[] {"test", "[test]" }, // No escape characters + new object[] {"]test", "[]]test]" }, // Escape character at beginning + new object[] {"te]st", "[te]]st]" }, // Escape character in middle + new object[] {"test]", "[test]]]" }, // Escape character at end + new object[] {"t]]est", "[t]]]]est]" }, // Multiple escape characters + }; + + [Test, TestCaseSource(nameof(bracketEscapes))] public void FormatIdentifierTest(string value, string expectedOutput) { // If: I attempt to format a value as an identifier string output = ToSqlScript.FormatIdentifier(value); // Then: The output should match the expected output - Assert.Equal(expectedOutput, output); + Assert.AreEqual(expectedOutput, output); } - [Theory] - [InlineData("test", "[test]")] // No splits, no escape characters - [InlineData("test.test", "[test].[test]")] // One split, no escape characters - [InlineData("test.te]st", "[test].[te]]st]")] // One split, one escape character - [InlineData("test.test.test", "[test].[test].[test]")] // Two splits, no escape characters + private static readonly object[] multiParts = + { + new object[] {"test", "[test]" }, // No splits, no escape characters + new object[] {"test.test", "[test].[test]" }, // One split, no escape characters + new object[] {"test.te]st", "[test].[te]]st]" }, // One split, one escape character + new object[] {"test.test.test", "[test].[test].[test]" }, // Two splits, no escape characters + }; + + [Test, TestCaseSource(nameof(multiParts))] public void FormatMultipartIdentifierTest(string value, string expectedOutput) { // If: I attempt to format a value as a multipart identifier string output = ToSqlScript.FormatMultipartIdentifier(value); // Then: The output should match the expected output - Assert.Equal(expectedOutput, output); + Assert.AreEqual(expectedOutput, output); } public static IEnumerable GetMultipartIdentifierArrays @@ -293,15 +305,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests } } - [Theory] - [MemberData(nameof(GetMultipartIdentifierArrays))] + [Test] + [TestCaseSource(nameof(GetMultipartIdentifierArrays))] public void FormatMultipartIdentifierArrayTest(string expectedOutput, string[] splits) { // If: I attempt to format a value as a multipart identifier string output = ToSqlScript.FormatMultipartIdentifier(splits); // Then: The output should match the expected output - Assert.Equal(expectedOutput, output); + Assert.AreEqual(expectedOutput, output); } #endregion @@ -361,15 +373,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests } } - [Theory] - [MemberData(nameof(FormatColumnTypeData))] + [Test] + [TestCaseSource(nameof(FormatColumnTypeData))] public void FormatColumnType(bool useSemanticEquivalent, DbColumn input, string expectedOutput) { // If: I supply the input columns string output = ToSqlScript.FormatColumnType(input, useSemanticEquivalent); // Then: The output should match the expected output - Assert.Equal(expectedOutput, output); + Assert.AreEqual(expectedOutput, output); } #endregion diff --git a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Workspace/WorkspaceTests.cs b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Workspace/WorkspaceTests.cs index 6d58a5d0..861f56c2 100644 --- a/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Workspace/WorkspaceTests.cs +++ b/test/Microsoft.SqlTools.ServiceLayer.UnitTests/Workspace/WorkspaceTests.cs @@ -13,13 +13,13 @@ using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility; using Microsoft.SqlTools.ServiceLayer.Workspace; using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts; using Moq; -using Xunit; +using NUnit.Framework; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace { public class WorkspaceTests { - [Fact] + [Test] public async Task FileClosedSuccessfully() { // Given: @@ -28,7 +28,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace var workspaceService = new WorkspaceService {Workspace = workspace}; var openedFile = workspace.GetFileBuffer(TestObjects.ScriptUri, string.Empty); Assert.NotNull(openedFile); - Assert.NotEmpty(workspace.GetOpenedFiles()); + Assert.That(workspace.GetOpenedFiles(), Is.Not.Empty); // ... And there is a callback registered for the file closed event ScriptFile closedFile = null; @@ -51,23 +51,23 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace // Then: // ... The file should no longer be in the open files - Assert.Empty(workspace.GetOpenedFiles()); + Assert.That(workspace.GetOpenedFiles(), Is.Empty); // ... The callback should have been called // ... The provided script file should be the one we created Assert.NotNull(closedFile); - Assert.Equal(openedFile, closedFile); - Assert.Equal(TestObjects.ScriptUri, closedUri); + Assert.AreEqual(openedFile, closedFile); + Assert.AreEqual(TestObjects.ScriptUri, closedUri); } - [Fact] + [Test] public async Task FileClosedNotOpen() { // Given: // ... A workspace that has no files open var workspace = new ServiceLayer.Workspace.Workspace(); var workspaceService = new WorkspaceService {Workspace = workspace}; - Assert.Empty(workspace.GetOpenedFiles()); + Assert.That(workspace.GetOpenedFiles(), Is.Empty); // ... And there is a callback registered for the file closed event bool callbackCalled = false; @@ -89,24 +89,24 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace // ... There should still be no open files // ... The callback should not have been called - Assert.Empty(workspace.GetOpenedFiles()); + Assert.That(workspace.GetOpenedFiles(), Is.Empty); Assert.False(callbackCalled); } - [Fact] + [Test] public void BufferRangeNoneNotNull() { Assert.NotNull(BufferRange.None); } - [Fact] + [Test] public void BufferRangeStartGreaterThanEnd() { Assert.Throws(() => new BufferRange(new BufferPosition(2, 2), new BufferPosition(1, 1))); } - [Fact] + [Test] public void BufferRangeEquals() { var range = new BufferRange(new BufferPosition(1, 1), new BufferPosition(2, 2)); @@ -115,13 +115,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace Assert.NotNull(range.GetHashCode()); } - [Fact] + [Test] public void UnescapePath() { Assert.NotNull(Microsoft.SqlTools.ServiceLayer.Workspace.Workspace.UnescapePath("`/path/`")); } - [Fact] + [Test] public void GetBaseFilePath() { RunIfWrapper.RunIfWindows(() => @@ -130,12 +130,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace { Assert.Throws(() => workspace.GetBaseFilePath("path")); Assert.NotNull(workspace.GetBaseFilePath(@"c:\path\file.sql")); - Assert.Equal(workspace.GetBaseFilePath("tsqloutput://c:/path/file.sql"), workspace.WorkspacePath); + Assert.AreEqual(workspace.GetBaseFilePath("tsqloutput://c:/path/file.sql"), workspace.WorkspacePath); } }); } - [Fact] + [Test] public void ResolveRelativeScriptPath() { RunIfWrapper.RunIfWindows(() => @@ -146,13 +146,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace }); } - [Fact] + [Test] public async Task DontProcessGitFileEvents() { await VerifyFileIsNotAddedOnDocOpened("git:/myfile.sql"); } - [Fact] + [Test] public async Task DontProcessPerforceFileEvents() { await VerifyFileIsNotAddedOnDocOpened("perforce:/myfile.sql"); @@ -188,7 +188,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace Assert.False(workspaceService.Workspace.ContainsFile(filePath)); } - [Fact] + [Test] public void GetFileReturnsNullForPerforceFile() { // when I ask for a non-file object in the workspace, it should return null @@ -197,7 +197,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace Assert.Null(file); } - [Fact] + [Test] public async Task WorkspaceContainsFile() { var workspace = new ServiceLayer.Workspace.Workspace(); @@ -216,7 +216,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace Assert.True(workspaceService.Workspace.ContainsFile(TestObjects.ScriptUri)); } - [Fact] + [Test] public void DontBindToObjectExplorerConnectEvents() { // when I ask for a non-file object in the workspace, it should return null @@ -230,17 +230,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Workspace File.WriteAllText(tempFile, fileContents); file = workspace.GetFile(tempFile); - Assert.Equal(fileContents, file.Contents); + Assert.AreEqual(fileContents, file.Contents); if (tempFile.StartsWith("/")) { tempFile = tempFile.Substring(1); } file = workspace.GetFile("file://" + tempFile); - Assert.Equal(fileContents, file.Contents); + Assert.AreEqual(fileContents, file.Contents); file = workspace.GetFileBuffer("untitled://"+ tempFile, fileContents); - Assert.Equal(fileContents, file.Contents); + Assert.AreEqual(fileContents, file.Contents); // For windows files, just check scheme is null since it's hard to mock file contents in these Assert.Null(ServiceLayer.Workspace.Workspace.GetScheme(@"C:\myfile.sql"));