Convert most tools service tests to nunit (#1037)

* Remove xunit dependency from testdriver

* swap expected/actual as needed

* Convert Test.Common to nunit

* port hosting unit tests to nunit

* port batchparser integration tests to nunit

* port testdriver.tests to nunit

* fix target to copy dependency

* port servicelayer unittests to nunit

* more unit test fixes

* port integration tests to nunit

* fix test method type

* try using latest windows build for PRs

* reduce test memory use
This commit is contained in:
David Shiflet
2020-08-05 13:43:14 -04:00
committed by GitHub
parent bf4911795f
commit 839acf67cd
205 changed files with 4146 additions and 4329 deletions

View File

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

View File

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

View File

@@ -12,12 +12,13 @@ using Microsoft.Data.SqlClient;
using Microsoft.SqlTools.ServiceLayer.AutoParameterizaition;
using Microsoft.SqlTools.ServiceLayer.AutoParameterizaition.Exceptions;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
using NUnit.Framework;
using static System.Linq.Enumerable;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
{
[TestFixture]
/// <summary>
/// Parameterization for Always Encrypted is a feature that automatically converts Transact-SQL variables
/// into query parameters (instances of <c>SqlParameter</c> Class). This allows the underlying .NET Framework
@@ -38,7 +39,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// - Are declared and initialized in the same statement(inline initialization).
/// - Are initialized using a single literal.
/// </summary>
[Fact]
[Test]
public void SqlParameterizerShouldParameterizeValidVariables()
{
const string ssn = "795-73-9838";
@@ -56,7 +57,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
DbCommand command = new SqlCommand { CommandText = sql };
command.Parameterize();
Assert.Equal(expected: 3, actual: command.Parameters.Count);
Assert.AreEqual(expected: 3, actual: command.Parameters.Count);
}
/// <summary>
@@ -67,7 +68,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// The second is using a function used instead of a literal and so should not be parameterized.
/// The third is using an expression used instead of a literal and so should not be parameterized.
/// </summary>
[Fact]
[Test]
public void SqlParameterizerShouldNotParameterizeInvalidVariables()
{
string sql = $@"
@@ -82,7 +83,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
DbCommand command = new SqlCommand { CommandText = sql };
command.Parameterize();
Assert.Equal(expected: 0, actual: command.Parameters.Count);
Assert.AreEqual(expected: 0, actual: command.Parameters.Count);
}
/// <summary>
@@ -90,7 +91,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// Batch statements larger than 300000 characters (Approximately 600 Kb) should
/// throw <c>ParameterizationScriptTooLargeException</c>.
/// </summary>
[Fact]
[Test]
public void SqlParameterizerShouldThrowWhenSqlIsTooLong()
{
@@ -118,7 +119,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// During parameterization, if we could not parse the SQL we will throw an <c>ParameterizationParsingException</c>.
/// Better to catch the error here than on the server.
/// </summary>
[Fact]
[Test]
public void SqlParameterizerShouldThrowWhenSqlIsInvalid()
{
string invalidSql = "THIS IS INVALID SQL";
@@ -135,7 +136,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// literal used for the initialization of the variable must also match the type in the variable declaration.
/// If not, a <c>ParameterizationFormatException</c> should get thrown.
/// </summary>
[Fact]
[Test]
public void SqlParameterizerShouldThrowWhenLiteralHasTypeMismatch()
{
// variable is declared an int but is getting set to character data
@@ -157,7 +158,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// the DbCommand object will throw an exception with the following message:
/// BeginExecuteReader: CommandText property has not been initialized
/// </summary>
[Fact]
[Test]
public void CommentOnlyBatchesShouldNotBeErasedFromCommandText()
{
string sql = $@"
@@ -169,7 +170,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
command.Parameterize();
Assert.False(string.IsNullOrEmpty(command.CommandText));
Assert.Equal(expected: sql, actual: command.CommandText);
Assert.AreEqual(expected: sql, actual: command.CommandText);
}
#endregion
@@ -180,21 +181,21 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// When requesting a collection of <c>ScriptFileMarker</c> by calling the <c>SqlParameterizer.CodeSense</c>
/// method, if a null script is passed in, the reuslt should be an empty collection.
/// </summary>
[Fact]
[Test]
public void CodeSenseShouldReturnEmptyListWhenGivenANullScript()
{
string sql = null;
IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql);
Assert.NotNull(result);
Assert.Empty(result);
Assert.That(result, Is.Empty);
}
/// <summary>
/// When requesting a collection of <c>ScriptFileMarker</c> by calling the <c>SqlParameterizer.CodeSense</c>
/// method, if a script is passed in that contains no valid parameters, the reuslt should be an empty collection.
/// </summary>
[Fact]
[Test]
public void CodeSenseShouldReturnEmptyListWhenGivenAParameterlessScript()
{
// SQL with no parameters
@@ -206,7 +207,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql);
Assert.NotNull(result);
Assert.Empty(result);
Assert.That(result, Is.Empty);
}
/// <summary>
@@ -214,7 +215,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// SQL statements larger than 300000 characters (Approximately 600 Kb) should
/// return a max string sength code sense item. These will be returned to ADS to display to the user as intelli-sense.
/// </summary>
[Fact]
[Test]
public void CodeSenseShouldReturnMaxStringLengthScriptFileMarkerErrorItemWhenScriptIsTooLong()
{
// SQL length of 300 characters
@@ -235,10 +236,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
Console.WriteLine(result[0].Message);
Assert.NotEmpty(result);
Assert.Equal(expected: 1, actual: result.Count);
Assert.Equal(expected: ScriptFileMarkerLevel.Error, actual: result[0].Level);
Assert.Equal(expected: expectedMessage, actual: result[0].Message);
Assert.That(result, Is.Not.Empty);
Assert.AreEqual(expected: 1, actual: result.Count);
Assert.AreEqual(expected: ScriptFileMarkerLevel.Error, actual: result[0].Level);
Assert.AreEqual(expected: expectedMessage, actual: result[0].Message);
}
/// <summary>
@@ -246,7 +247,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
/// method, if a script is passed in that contains 3 valid parameters, the reuslt should be a collection of
/// three informational code sense items. These will be returned to ADS to display to the user as intelli-sense.
/// </summary>
[Fact]
[Test]
public void CodeSenseShouldReturnInformationalCodeSenseItemsForValidParameters()
{
const string ssn = "795-73-9838";
@@ -263,8 +264,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
IList<ScriptFileMarker> result = SqlParameterizer.CodeSense(sql);
Assert.NotEmpty(result);
Assert.Equal(expected: 3, actual: result.Count);
Assert.That(result, Is.Not.Empty);
Assert.AreEqual(expected: 3, actual: result.Count);
Assert.True(Enumerable.All(result, i => i.Level == ScriptFileMarkerLevel.Information));
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -12,16 +12,17 @@ using Microsoft.SqlTools.Credentials.Contracts;
using Microsoft.SqlTools.Credentials.Linux;
using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
{
[TestFixture]
/// <summary>
/// Credential Service tests that should pass on all platforms, regardless of backing store.
/// These tests run E2E, storing values in the native credential store for whichever platform
/// tests are being run on
/// </summary>
public class CredentialServiceTests : IDisposable
public class CredentialServiceTests
{
private static readonly StoreConfig Config = new StoreConfig
{
@@ -39,18 +40,18 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
// Test-owned credential store used to clean up before/after tests to ensure code works as expected
// even if previous runs stopped midway through
private readonly ICredentialStore credStore;
private readonly CredentialService service;
/// <summary>
/// Constructor called once for every test
/// </summary>
public CredentialServiceTests()
private ICredentialStore credStore;
private CredentialService service;
[SetUp]
public void SetupCredentialServiceTests()
{
credStore = CredentialService.GetStoreForOS(Config);
service = new CredentialService(credStore, Config);
DeleteDefaultCreds();
}
[TearDown]
public void Dispose()
{
DeleteDefaultCreds();
@@ -73,7 +74,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
#endif
}
[Fact]
[Test]
public async Task SaveCredentialThrowsIfCredentialIdMissing()
{
string errorResponse = null;
@@ -81,10 +82,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
await service.HandleSaveCredentialRequest(new Credential(null), contextMock.Object);
TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentException", errorResponse);
Assert.That(errorResponse, Does.Contain("ArgumentException"));
}
[Fact]
[Test]
public async Task SaveCredentialThrowsIfPasswordMissing()
{
string errorResponse = null;
@@ -95,7 +96,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
Assert.True(errorResponse.Contains("ArgumentException") || errorResponse.Contains("ArgumentNullException"));
}
[Fact]
[Test]
public async Task SaveCredentialWorksForSingleCredential()
{
await TestUtils.RunAndVerify<bool>(
@@ -103,7 +104,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: Assert.True);
}
[Fact]
[Test]
public async Task SaveCredentialWorksForEmptyPassword()
{
await TestUtils.RunAndVerify<bool>(
@@ -111,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: Assert.True);
}
[Fact]
[Test]
public async Task SaveCredentialSupportsSavingCredentialMultipleTimes()
{
await TestUtils.RunAndVerify<bool>(
@@ -123,7 +124,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: Assert.True);
}
[Fact]
[Test]
public async Task ReadCredentialWorksForSingleCredential()
{
// Given we have saved the credential
@@ -137,11 +138,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId, null), requestContext),
verify: (actual =>
{
Assert.Equal(Password1, actual.Password);
Assert.AreEqual(Password1, actual.Password);
}));
}
[Fact]
[Test]
public async Task ReadCredentialWorksForMultipleCredentials()
{
@@ -159,17 +160,17 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId, null), requestContext),
verify: (actual =>
{
Assert.Equal(Password1, actual.Password);
Assert.AreEqual(Password1, actual.Password);
}));
await TestUtils.RunAndVerify<Credential>(
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(OtherCredId, null), requestContext),
verify: (actual =>
{
Assert.Equal(OtherPassword, actual.Password);
Assert.AreEqual(OtherPassword, actual.Password);
}));
}
[Fact]
[Test]
public async Task ReadCredentialHandlesPasswordUpdate()
{
// Given we have saved twice with a different password
@@ -187,11 +188,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
test: (requestContext) => service.HandleReadCredentialRequest(new Credential(CredentialId), requestContext),
verify: (actual =>
{
Assert.Equal(Password2, actual.Password);
Assert.AreEqual(Password2, actual.Password);
}));
}
[Fact]
[Test]
public async Task ReadCredentialThrowsIfCredentialIsNull()
{
string errorResponse = null;
@@ -200,10 +201,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
// Verify throws on null, and this is sent as an error
await service.HandleReadCredentialRequest(null, contextMock.Object);
TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentNullException", errorResponse);
Assert.That(errorResponse, Does.Contain("ArgumentNullException"));
}
[Fact]
[Test]
public async Task ReadCredentialThrowsIfIdMissing()
{
string errorResponse = null;
@@ -212,10 +213,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
// Verify throws with no ID
await service.HandleReadCredentialRequest(new Credential(), contextMock.Object);
TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentException", errorResponse);
Assert.That(errorResponse, Does.Contain("ArgumentException"));
}
[Fact]
[Test]
public async Task ReadCredentialReturnsNullPasswordForMissingCredential()
{
// Given a credential whose password doesn't exist
@@ -228,12 +229,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
verify: (actual =>
{
Assert.NotNull(actual);
Assert.Equal(credWithNoPassword, actual.CredentialId);
Assert.AreEqual(credWithNoPassword, actual.CredentialId);
Assert.Null(actual.Password);
}));
}
[Fact]
[Test]
public async Task DeleteCredentialThrowsIfIdMissing()
{
object errorResponse = null;
@@ -245,7 +246,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
Assert.True(((string)errorResponse).Contains("ArgumentException"));
}
[Fact]
[Test]
public async Task DeleteCredentialReturnsTrueOnlyIfCredentialExisted()
{
// Save should be true

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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);
}
}
}

View File

@@ -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<string, RestorePlanDetailInfo> optionInResponse, GeneralRequestDetails optionValues)
{
RestorePlanDetailInfo planDetailInfo = optionInResponse[RestoreOptionsHelper.DataFileFolder];
Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.DataFileFolder);
Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>(RestoreOptionsHelper.RelocateDbFiles));
Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue<string>(RestoreOptionsHelper.DataFileFolder));
Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue<string>("DefaultDataFileFolder"));
Assert.Equal(planDetailInfo.IsVisiable, true);
Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.DataFileFolder);
Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>(RestoreOptionsHelper.RelocateDbFiles));
Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue<string>(RestoreOptionsHelper.DataFileFolder));
Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue<string>("DefaultDataFileFolder"));
Assert.AreEqual(true, planDetailInfo.IsVisiable);
planDetailInfo = optionInResponse[RestoreOptionsHelper.LogFileFolder];
Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.LogFileFolder);
Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>(RestoreOptionsHelper.RelocateDbFiles));
Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue<string>(RestoreOptionsHelper.LogFileFolder));
Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue<string>("DefaultLogFileFolder"));
Assert.Equal(planDetailInfo.IsVisiable, true);
Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.LogFileFolder);
Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>(RestoreOptionsHelper.RelocateDbFiles));
Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue<string>(RestoreOptionsHelper.LogFileFolder));
Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue<string>("DefaultLogFileFolder"));
Assert.AreEqual(true, planDetailInfo.IsVisiable);
planDetailInfo = optionInResponse[RestoreOptionsHelper.RelocateDbFiles];
Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.RelocateDbFiles);
Assert.Equal(planDetailInfo.IsReadOnly, (optionValues.GetOptionValue<List<DbFile>>("DbFiles").Count == 0));
Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue<bool>(RestoreOptionsHelper.RelocateDbFiles));
Assert.Equal(planDetailInfo.DefaultValue, false);
Assert.Equal(planDetailInfo.IsVisiable, true);
Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.RelocateDbFiles);
Assert.AreEqual(planDetailInfo.IsReadOnly, (optionValues.GetOptionValue<List<DbFile>>("DbFiles").Count == 0));
Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue<bool>(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<bool>(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<bool>(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<DatabaseRecoveryState>(RestoreOptionsHelper.RecoveryState) == DatabaseRecoveryState.WithNoRecovery);
Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue<bool>(RestoreOptionsHelper.KeepReplication));
Assert.Equal(planDetailInfo.DefaultValue, false);
Assert.Equal(planDetailInfo.IsVisiable, true);
Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.KeepReplication);
Assert.AreEqual(planDetailInfo.IsReadOnly, optionValues.GetOptionValue<DatabaseRecoveryState>(RestoreOptionsHelper.RecoveryState) == DatabaseRecoveryState.WithNoRecovery);
Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue<bool>(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<bool>(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<bool>(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<DatabaseRecoveryState>(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<DatabaseRecoveryState>(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<DatabaseRecoveryState>(RestoreOptionsHelper.RecoveryState) != DatabaseRecoveryState.WithStandBy);
Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue<string>(RestoreOptionsHelper.StandbyFile));
Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue<string>("GetDefaultStandbyFile"));
Assert.Equal(planDetailInfo.IsVisiable, true);
Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.StandbyFile);
Assert.AreEqual(planDetailInfo.IsReadOnly, optionValues.GetOptionValue<DatabaseRecoveryState>(RestoreOptionsHelper.RecoveryState) != DatabaseRecoveryState.WithStandBy);
Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue<string>(RestoreOptionsHelper.StandbyFile));
Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue<string>("GetDefaultStandbyFile"));
Assert.AreEqual(true, planDetailInfo.IsVisiable);
planDetailInfo = optionInResponse[RestoreOptionsHelper.BackupTailLog];
Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.BackupTailLog);
Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>("IsTailLogBackupPossible"));
Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue<bool>(RestoreOptionsHelper.BackupTailLog));
Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue<bool>("IsTailLogBackupPossible"));
Assert.Equal(planDetailInfo.IsVisiable, true);
Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.BackupTailLog);
Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>("IsTailLogBackupPossible"));
Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue<bool>(RestoreOptionsHelper.BackupTailLog));
Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue<bool>("IsTailLogBackupPossible"));
Assert.AreEqual(true, planDetailInfo.IsVisiable);
planDetailInfo = optionInResponse[RestoreOptionsHelper.TailLogBackupFile];
Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.TailLogBackupFile);
Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>("IsTailLogBackupPossible")
Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.TailLogBackupFile);
Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>("IsTailLogBackupPossible")
| !optionValues.GetOptionValue<bool>(RestoreOptionsHelper.BackupTailLog));
Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue<string>("TailLogBackupFile"));
Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue<string>("GetDefaultTailLogbackupFile"));
Assert.Equal(planDetailInfo.IsVisiable, true);
Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue<string>("TailLogBackupFile"));
Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue<string>("GetDefaultTailLogbackupFile"));
Assert.AreEqual(true, planDetailInfo.IsVisiable);
planDetailInfo = optionInResponse[RestoreOptionsHelper.TailLogWithNoRecovery];
Assert.Equal(planDetailInfo.Name, RestoreOptionsHelper.TailLogWithNoRecovery);
Assert.Equal(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>("IsTailLogBackupWithNoRecoveryPossible")
Assert.AreEqual(planDetailInfo.Name, RestoreOptionsHelper.TailLogWithNoRecovery);
Assert.AreEqual(planDetailInfo.IsReadOnly, !optionValues.GetOptionValue<bool>("IsTailLogBackupWithNoRecoveryPossible")
| !optionValues.GetOptionValue<bool>(RestoreOptionsHelper.BackupTailLog));
Assert.Equal(planDetailInfo.CurrentValue, optionValues.GetOptionValue<bool>("TailLogWithNoRecovery"));
Assert.Equal(planDetailInfo.DefaultValue, optionValues.GetOptionValue<bool>("IsTailLogBackupWithNoRecoveryPossible"));
Assert.Equal(planDetailInfo.IsVisiable, true);
Assert.AreEqual(planDetailInfo.CurrentValue, optionValues.GetOptionValue<bool>("TailLogWithNoRecovery"));
Assert.AreEqual(planDetailInfo.DefaultValue, optionValues.GetOptionValue<bool>("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<bool>(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<bool>(RestoreOptionsHelper.CloseExistingConnections));
Assert.AreEqual(false, planDetailInfo.DefaultValue);
Assert.AreEqual(true, planDetailInfo.IsVisiable);
}
}

View File

@@ -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<ArgumentNullException>(() => 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<ArgumentNullException>(() => new CellUpdate(GetWrapper<string>("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<DBNull>(cu.Value);
Assert.Equal(DBNull.Value, cu.Value);
Assert.Equal(nullString, cu.ValueAsString);
Assert.Equal(col, cu.Column);
Assert.That(cu.Value, Is.InstanceOf<DBNull>());
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<InvalidOperationException>(() => new CellUpdate(GetWrapper<string>("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<string>(cu.Value);
Assert.Equal("NULL", cu.Value);
Assert.Equal("'NULL'", cu.ValueAsString);
Assert.Equal(col, cu.Column);
Assert.That(cu.Value, Is.InstanceOf<string>());
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<InvalidOperationException>(() => 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<byte[]>(cu.Value);
Assert.Equal(expectedValue, cu.Value);
Assert.Equal(expectedString, cu.ValueAsString);
Assert.Equal(col, cu.Column);
Assert.That(cu.Value, Is.InstanceOf<byte[]>());
Assert.AreEqual(expectedValue, cu.Value);
Assert.AreEqual(expectedString, cu.ValueAsString);
Assert.AreEqual(col, cu.Column);
}
public static IEnumerable<object[]> 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<InvalidOperationException>(() => 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<bool>(cu.Value);
Assert.Equal(output, cu.Value);
Assert.Equal(outputString, cu.ValueAsString);
Assert.Equal(col, cu.Column);
Assert.That(cu.Value, Is.InstanceOf<bool>());
Assert.AreEqual(output, cu.Value);
Assert.AreEqual(outputString, cu.ValueAsString);
Assert.AreEqual(col, cu.Column);
}
public static IEnumerable<object[]> BoolTestParams
private static IEnumerable<object[]> 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => new CellUpdate(col, value));
}
[Theory]
[MemberData(nameof(RoundTripTestParams))]
public void RoundTripTest(DbColumnWrapper col, object obj)
/// <summary>
/// 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.
/// </summary>
/// <param name="col"></param>
/// <param name="obj"></param>
[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<object[]> 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);

View File

@@ -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<ArgumentNullException>(() => 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);

View File

@@ -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
/// </summary>
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);
}
}
}

View File

@@ -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<ArgumentOutOfRangeException>(() => 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<ArgumentOutOfRangeException>(() => 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

View File

@@ -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<ArgumentNullException>(() => 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<ArgumentNullException>(() => 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<InvalidOperationException>(() => rd.SetCell(0, null));
}
[Fact]
[Test]
public async Task RevertCell()
{
// Setup: Create a row delete

View File

@@ -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<ArgumentException>(() => 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<ArgumentOutOfRangeException>(() => 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<InvalidOperationException>(() => 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<RowDelete>(rowEdits.Last());
Assert.That(rowEdits.Last(), Is.InstanceOf<RowDelete>(), "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<ResultSet> 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

View File

@@ -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<ArgumentOutOfRangeException>(() => 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<ArgumentNullException>(() => ru.ApplyChanges(null));
Assert.ThrowsAsync<ArgumentNullException>(() => 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<ArgumentOutOfRangeException>(() => 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

View File

@@ -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<int>(), It.IsAny<string>()), 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<EditSession> GetDefaultSession()

View File

@@ -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<ArgumentNullException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<RowCreate>(s.EditCache[result.NewRowId]);
Assert.That(s.EditCache.Keys, Has.Member(result.NewRowId));
Assert.That(s.EditCache[result.NewRowId], Is.InstanceOf<RowCreate>());
// ... 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<EditSession, long> 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<Task> sh, Func<Exception, Task> fh)
{
@@ -321,9 +321,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
EditSession s = new EditSession(emf.Object);
// If: I initialize it with a missing parameter
// Then: It should throw an exception
Assert.ThrowsAny<ArgumentException>(() => s.Initialize(initParams, c, qr, sh, fh));
Assert.That(() => s.Initialize(initParams, c, qr, sh, fh), Throws.InstanceOf<ArgumentException>(), "I initialize it with a missing parameter. It should throw an exception");
}
public static IEnumerable<object[]> 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<InvalidOperationException>(() => s.DeleteRow(0));
}
[Fact]
[Test]
public async Task DeleteRowAddFailure()
{
// Setup:
@@ -560,10 +556,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
Assert.Throws<InvalidOperationException>(() => 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<RowDelete>(s.EditCache[0]);
Assert.That(s.EditCache.Keys, Has.Member(0));
Assert.That(s.EditCache[0], Is.InstanceOf<RowDelete>(), "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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<RowUpdate>(s.EditCache[0]);
Assert.Multiple(() =>
{
Assert.That(s.EditCache.Keys, Has.Member(0));
Assert.That(s.EditCache[0], Is.InstanceOf<RowUpdate>(), "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<InvalidOperationException>(() => s.GetRows(0, 100));
Assert.ThrowsAsync<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<ArgumentNullException>(() => 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<InvalidOperationException>(() => 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<ArgumentNullException>(() => 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<ArgumentNullException>(() => 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<DbDataReader>()), 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<ArgumentOutOfRangeException>(() => 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

View File

@@ -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<MyExportType>(GetType().GetTypeInfo().Assembly);
// Then should get any export for this type and subtypes
Assert.Equal(2, store.GetExports<MyExportType>().Count());
Assert.AreEqual(2, store.GetExports<MyExportType>().Count());
// But for a different type, expect throw as the store only contains MyExportType
Assert.Throws<InvalidCastException>(() => store.GetExports<MyOtherType>().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<MyExportType>();
Assert.Equal(0, store.GetExports<MyExportType>().Count());
Assert.AreEqual(0, store.GetExports<MyExportType>().Count());
// And should not find exports that are defined in the ServiceLayer assembly
store = ExtensionStore.CreateDefaultLoader<ASTNodeFormatterFactory>();
Assert.Empty(store.GetExports<ASTNodeFormatterFactory>());
Assert.That(store.GetExports<ASTNodeFormatterFactory>(), 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<MyExportType>());
Assert.That(serviceProvider.GetServices<MyExportType>(), Is.Empty);
// But should find exports that are defined in the main assembly
Assert.NotEmpty(serviceProvider.GetServices<ASTNodeFormatterFactory>());
Assert.That(serviceProvider.GetServices<ASTNodeFormatterFactory>(), 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<MyExportType>().Count());
Assert.NotEmpty(querierStore.GetExports<ASTNodeFormatterFactory>());
Assert.AreEqual(2, myStore.GetExports<MyExportType>().Count());
Assert.That(querierStore.GetExports<ASTNodeFormatterFactory>(), Is.Not.Empty);
}
}

View File

@@ -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<InvalidOperationException>(() => provider.GetService<MyProviderService>());
}
[Fact]
[Test]
public void GetServicesShouldReturnEmptyIfNoServicesRegistered()
{
// Given no service regisstered
@@ -47,36 +49,36 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility
var services = provider.GetServices<MyProviderService>();
// 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<MyProviderService>();
Assert.Equal(service, returnedService);
Assert.AreEqual(service, returnedService);
}
[Fact]
[Test]
public void GetServicesShouldReturnRegisteredServiceWhenMultipleServicesRegistered()
{
MyProviderService service = new MyProviderService();
provider.RegisterSingleService(service);
var returnedServices = provider.GetServices<MyProviderService>();
Assert.Equal(service, returnedServices.Single());
Assert.AreEqual(service, returnedServices.Single());
}
[Fact]
[Test]
public void RegisterServiceProviderShouldThrowIfServiceIsIncompatible()
{
MyProviderService service = new MyProviderService();
Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(typeof(OtherService), service));
}
[Fact]
[Test]
public void RegisterServiceProviderShouldThrowIfServiceAlreadyRegistered()
{
MyProviderService service = new MyProviderService();
@@ -85,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility
Assert.Throws<InvalidOperationException>(() => provider.RegisterSingleService(service));
}
[Fact]
[Test]
public void RegisterShouldThrowIfServiceAlreadyRegistered()
{
MyProviderService service = new MyProviderService();
@@ -94,7 +96,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility
Assert.Throws<InvalidOperationException>(() => provider.Register(() => service.SingleItemAsEnumerable()));
}
[Fact]
[Test]
public void RegisterShouldThrowIfServicesAlreadyRegistered()
{
provider.Register<MyProviderService>(() => new [] { new MyProviderService(), new MyProviderService() });

View File

@@ -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
/// </summary>
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();

View File

@@ -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();

View File

@@ -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();

View File

@@ -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"),

View File

@@ -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();

View File

@@ -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"),

View File

@@ -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<SqlToolsSettings>();
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);
}
}
}

View File

@@ -18,7 +18,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class FormatterUnitTestsBase
{
public FormatterUnitTestsBase()
protected void InitFormatterUnitTestsBase()
{
HostMock = new Mock<IProtocolEndpoint>();
WorkspaceServiceMock = new Mock<WorkspaceService<SqlToolsSettings>>();

View File

@@ -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",

View File

@@ -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"),

View File

@@ -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"),

View File

@@ -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<ServiceLayer.Workspace.Workspace> workspaceMock = new Mock<ServiceLayer.Workspace.Workspace>();
private Mock<ServiceLayer.Workspace.Workspace> workspaceMock;
private TextDocumentIdentifier textDocument;
DocumentFormattingParams docFormatParams;
DocumentRangeFormattingParams rangeFormatParams;
public TSqlFormatterServiceTests()
[SetUp]
public void InitTSqlFormatterServiceTests()
{
InitFormatterUnitTestsBase();
workspaceMock = new Mock<ServiceLayer.Workspace.Workspace>();
textDocument = new TextDocumentIdentifier
{
Uri = "script file"
@@ -64,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
LanguageServiceMock.Setup(x => x.ShouldSkipNonMssqlFile(It.IsAny<string>())).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);
});
}

View File

@@ -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();

View File

@@ -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<CompletionItem>
{
[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<string>(), It.IsAny<int>()), 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));
}
/// <summary>
/// Tests the primary completion list event handler
/// </summary>
[Fact]
[Test]
public void GetCompletionsHandlerTest()
{
InitializeTestObjects();

View File

@@ -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
/// <summary>
/// Queues a single task
/// </summary>
[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);
}
/// <summary>
/// Queues a single task
/// </summary>
[Fact]
[Test]
public void QueueWithUnhandledExceptionTest()
{
InitializeTestSettings();
@@ -158,14 +158,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
Assert.True(isExceptionHandled);
var result = queueItem.GetResultAsT<object>();
Assert.Equal(defaultReturnObject, result);
Assert.AreEqual(defaultReturnObject, result);
}
/// <summary>
/// Queue a 100 short tasks
/// </summary>
// 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);
}
/// <summary>
/// Queue an task with a long operation causing a timeout
/// </summary>
[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
/// </summary>
[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);
}

View File

@@ -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());
}

View File

@@ -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<int> interactionMetrics = new InteractionMetrics<int>(metrics);
Assert.Equal(interactionMetrics.Metrics, expected);
Assert.AreEqual(interactionMetrics.Metrics, expected);
}
[Fact]
[Test]
public void MetricsShouldThrowExceptionGivenNullInput()
{
int[] metrics = null;
Assert.Throws<ArgumentNullException>(() => new InteractionMetrics<int>(metrics));
}
[Fact]
[Test]
public void MetricsShouldThrowExceptionGivenEmptyInput()
{
int[] metrics = new int[] { };
Assert.Throws<ArgumentOutOfRangeException>(() => new InteractionMetrics<int>(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<int> interactionMetrics = new InteractionMetrics<int>(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<int> interactionMetrics = new InteractionMetrics<int>(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<string, double> 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"]);
}
}

View File

@@ -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
{

View File

@@ -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
/// <summary>
/// Verify that the latest SqlParser (2016 as of this writing) is used by default
/// </summary>
[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);
}
/// <summary>
/// Verify that the SQL parser correctly detects errors in text
/// </summary>
[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);
}
/// <summary>
/// Verify that the SQL parser correctly detects errors in text
/// </summary>
[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);
}
/// <summary>
/// Verify that the SQL parser correctly detects errors in text
/// </summary>
[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);
}
/// <summary>
/// Verify that GetSignatureHelp returns null when the provided TextDocumentPosition
/// has no associated ScriptParseInfo.
/// </summary>
[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);
}
}

View File

@@ -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
/// <summary>
/// Tests the definition event handler. When called with no active connection, an error is sent
/// </summary>
[Fact]
[Test]
public async Task DefinitionsHandlerWithNoConnectionTest()
{
InitializeTestObjects();
@@ -54,7 +54,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
/// <summary>
/// Tests creating location objects on windows and non-windows systems
/// </summary>
[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);
}
/// <summary>
/// Test PeekDefinition.GetSchemaFromDatabaseQualifiedName with a valid database name
/// </summary>
[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);
}
/// <summary>
/// Test PeekDefinition.GetSchemaFromDatabaseQualifiedName with a valid object name and no schema
/// </summary>
[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);
}
/// <summary>
/// Test PeekDefinition.GetSchemaFromDatabaseQualifiedName with a invalid database name
/// </summary>
[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);
}
/// <summary>
/// Test deletion of peek definition scripts for a valid temp folder that exists
/// </summary>
[Fact]
[Test]
public void DeletePeekDefinitionScriptsTest()
{
Scripter peekDefinition = new Scripter(null, null);
@@ -126,7 +126,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
/// <summary>
/// Test deletion of peek definition scripts for a temp folder that does not exist
/// </summary>
[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)
/// </summary>
[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);
}
/// <summary>
@@ -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)
/// </summary>
[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);
}
/// <summary>
@@ -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
/// </summary>
[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);
}
/// <summary>
@@ -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
/// </summary>
[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);
}
/// <summary>
@@ -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
/// </summary>
[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
/// </summary>
[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);
}
/// <summary>
@@ -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
/// </summary>
[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);
}
/// <summary>
@@ -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
/// </summary>
[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);
}
/// <summary>
/// Test getting definition using quickInfo text without a live connection
/// Expect an error result (because you cannot script without a live connection)
/// </summary>
[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)
/// </summary>
[Fact]
[Test]
public void GetDefinitionUsingDeclarationItemWithoutConnectionTest()
{
Scripter peekDefinition = new Scripter(null, null);

View File

@@ -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<ArgumentException>(() => new SqlCompletionItem(declarationTitle, declarationType, tokenText));
}
[Fact]
[Test]
public void ConstructorShouldThrowExceptionGivenNullDeclarion()
{
string tokenText = "";
Assert.Throws<ArgumentException>(() => 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);
}
}
}

View File

@@ -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<int, int> requestType = RequestType<int, int>.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<int> eventType = EventType<int>.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<int> eventType = EventType<int>.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;

View File

@@ -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<ArgumentException>(() => messageReader.ReadMessage()).Wait();
Assert.ThrowsAsync<ArgumentException>(() => 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<MessageParseException>(() => messageReader.ReadMessage()).Wait();
Assert.ThrowsAsync<MessageParseException>(() => 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<MessageParseException>(() => messageReader.ReadMessage()).Wait();
Assert.ThrowsAsync<MessageParseException>(() => 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<JsonReaderException>(() => messageReader.ReadMessage()).Wait();
Assert.ThrowsAsync<JsonReaderException>(() => 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<MessageParseException>(() => messageReader.ReadMessage()).Wait();
Assert.ThrowsAsync<MessageParseException>(() => 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<ArgumentException>(() => messageReader.ReadMessage()).Wait();
Assert.ThrowsAsync<ArgumentException>(() => 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<string>("someString"));
Assert.AreEqual(dateString, messageResult.Contents.Value<string>("someString"));
inputStream.Dispose();
}

View File

@@ -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();

View File

@@ -12,9 +12,9 @@
<PackageReference Include="System.Text.Encoding.CodePages" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Moq" />
<PackageReference Include="NUnit" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="nunit" />
<PackageReference Include="nunit3testadapter" />
<PackageReference Include="nunit.console" />
<PackageReference Include="Microsoft.Data.SqlClient" />
</ItemGroup>
<ItemGroup>

View File

@@ -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<string> { "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<string> { "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);
}
}
}

View File

@@ -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<ArgumentNullException>(() => new ServerNode(null, ServiceProvider, serverConnection));
Assert.Throws<ArgumentNullException>(() => 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<NotSupportedException>(() => 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<TreeNode> 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<Server>()), 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<TreeNode> 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<FolderNode>(children[0], "Folder", SR.SchemaHierarchy_Databases);
VerifyTreeNode<FolderNode>(children[1], "Folder", SR.SchemaHierarchy_Security);
VerifyTreeNode<FolderNode>(children[2], "Folder", SR.SchemaHierarchy_ServerObjects);
// And the database is contained under it
TreeNode databases = children[0];
IList<TreeNode> 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);
}
}
}

View File

@@ -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<SqlConnectionOpener> mockConnectionOpener;
public ObjectExplorerServiceTests()
[SetUp]
public void InitObjectExplorerServiceTests()
{
connectionServiceMock = new Mock<ConnectionService>();
serviceHostMock = new Mock<IProtocolEndpoint>();
@@ -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<DisconnectParams>()));
}
[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<TreeNode>();
@@ -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);
}

View File

@@ -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);
}
}
}

View File

@@ -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<SmoQuerier>(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

View File

@@ -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);
}
}
}

View File

@@ -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]
/// <summary>
/// Unit tests for ProfilerService
/// </summary>
@@ -29,7 +30,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler
/// </summary>
/// <returns></returns>
// 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
/// </summary>
/// <returns></returns>
[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
/// </summary>
/// <returns></returns>
[Fact]
[Test]
public async Task TestPauseProfilingRequest()
{
bool success = false;
@@ -238,7 +239,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Profiler
/// <summary>
/// Test notifications for stopped sessions
/// </summary>
[Fact]
[Test]
public async Task TestStoppedSessionNotification()
{
bool sessionStopped = false;

View File

@@ -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
/// <summary>
/// Test the FilterOldEvents method
/// </summary>
[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);
}
/// <summary>
/// Test the FilterProfilerEvents method
/// </summary>
[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);
}
/// <summary>
/// Test notifications for lost events
/// </summary>
[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
/// <summary>
/// Test the TryEnterPolling method
/// </summary>
[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;

View File

@@ -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
{

View File

@@ -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);
}
}
}

View File

@@ -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);
}

View File

@@ -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<InvalidOperationException>(
() => 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<InvalidOperationException>(
() => manager.AssureColumnReference());
Assert.Contains("AddRow must be called before AddCell", ex.Message);
Assert.That(ex.Message, Does.Contain("AddRow must be called before AddCell"));
}
}

View File

@@ -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<object[]>(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]);
}
}
}

View File

@@ -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<ArgumentNullException>(() => 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<ArgumentNullException>(() => 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<ArgumentNullException>(() => 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<ArgumentNullException>(() => 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<object[]> GuidTestParameters
private static IEnumerable<Guid> 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

View File

@@ -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<ArgumentNullException>(() => 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);
}
}
}

View File

@@ -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<string>()), 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);
}
}

View File

@@ -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<InvalidOperationException>(
Assert.ThrowsAsync<InvalidOperationException>(
() => 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<ArgumentException>(() => 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<ArgumentNullException>(() => 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<ArgumentOutOfRangeException>(() => 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<ResultMessage> 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<Batch> startCallback, Action<Batch> endCallback,

View File

@@ -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
/// <summary>
/// Basic data type and properties test
/// </summary>
[Fact]
[Test]
public void DataTypeAndPropertiesTest()
{
// check default constructor doesn't throw
@@ -89,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
/// <summary>
/// constructor test
/// </summary>
[Fact]
[Test]
public void DbColumnConstructorTests()
{
// check that various constructor parameters initial the wrapper correctly

View File

@@ -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<InvalidOperationException>(() => query.BatchSummaries);
Assert.Throws<InvalidOperationException>(() => { var x = query.BatchSummaries; });
}
[Fact]
[Test]
public void QueryExecuteNoConnectionInfo()
{
// If:
@@ -45,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
Assert.Throws<ArgumentNullException>(() => 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<Batch> startCallback, Action<Batch> endCallback,

View File

@@ -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<ArgumentNullException>(() => resultSet.ReadResultToEnd(null, CancellationToken.None));
Assert.ThrowsAsync<ArgumentNullException>(() => resultSet.ReadResultToEnd(null, CancellationToken.None));
}
/// <summary>
/// Read to End test
/// </summary>
/// <param name="testDataSet"></param>
[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
/// </summary>
/// <param name="testDataSet"></param>
[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<Task> allTasks = new List<Task>();
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<object[]> ReadToEndSuccessData(int numTests) => Common.TestResultSetsEnumeration.Select(r => new object[] { new TestResultSet[] { r } }).Take(numTests);
public static readonly IEnumerable<object[]> 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<object[]> ReadToEndSuccessDataParallel = Common.TestResultSetsEnumeration.Select(r => new object[] { new TestResultSet[] { r } }).Take(3);
[Theory]
[MemberData(nameof(CallMethodWithoutReadingData))]
[Test]
[TestCaseSource(nameof(CallMethodWithoutReadingData))]
public void CallMethodWithoutReading(Action<ResultSet> 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<Exception>(() => testMethod(resultSet));
Assert.That(() => testMethod(resultSet), Throws.InstanceOf<Exception>(), "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<object[]> CallMethodWithoutReadingData
@@ -239,10 +236,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
/// </summary>
/// <param name="forType"></param>
/// <returns></returns>
[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<ArgumentOutOfRangeException>(() => resultSet.GetSubset(startRow, rowCount));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => 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<ResultSet> 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<Exception>(() => actionToPerform(resultSet));
Assert.That(() => actionToPerform(resultSet), Throws.InstanceOf<Exception>(), "Attempting to read an invalid row should fail");
}
public static IEnumerable<object[]> 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<ArgumentOutOfRangeException>(() => 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<InvalidOperationException>(() => resultSet.AddRow(emptyReader));
Assert.ThrowsAsync<InvalidOperationException>(() => 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<DbException>(() => resultSet.AddRow(throwingReader));
// ... The row count should not have changed
Assert.Equal(Common.StandardRows, resultSet.RowCount);
Assert.ThrowsAsync<TestDbException>(() => 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<InvalidOperationException>(() => resultSet.UpdateRow(0, emptyReader));
Assert.ThrowsAsync<InvalidOperationException>(() => 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)

View File

@@ -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<ArgumentNullException>(
Assert.ThrowsAsync<ArgumentNullException>(
() => 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<ArgumentNullException>(
Assert.ThrowsAsync<ArgumentNullException>(
() => 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<ArgumentNullException>(
Assert.ThrowsAsync<ArgumentNullException>(
() => 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<ArgumentNullException>(
Assert.ThrowsAsync<ArgumentNullException>(
() => 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<object[]> TestResultSetsData(int numTests) => Common.TestResultSetsEnumeration.Select(r => new object[] { r }).Take(numTests);
private static readonly IEnumerable<object[]> 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);
});
}
}

View File

@@ -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<Exception>(() => planResultSet.GetExecutionPlan());
Assert.ThrowsAsync<Exception>(() => 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<Exception>(() => b.GetExecutionPlan(0));
Assert.ThrowsAsync<Exception>(() => 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<ArgumentOutOfRangeException>(() => b.GetExecutionPlan(resultSetIndex));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => 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<ArgumentOutOfRangeException>(() => q.GetExecutionPlan(batchIndex, 0));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => 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:

View File

@@ -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

View File

@@ -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

View File

@@ -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(

View File

@@ -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<IProtocolEndpoint> 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<SerializeDataStartRequestParams> 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<SerializeDataStartRequestParams> 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<string,object> 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<XmlNode>().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);
}
}
}

View File

@@ -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:

View File

@@ -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);

View File

@@ -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);
}

View File

@@ -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<ArgumentOutOfRangeException>(() => rs.GetSubset(rowStartIndex, rowCount)).Wait();
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => 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<InvalidOperationException>(() => rs.GetSubset(0, 1));
Assert.ThrowsAsync<InvalidOperationException>(() => 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<ArgumentOutOfRangeException>(() => b.GetSubset(resultSetIndex, 0, 2)).Wait();
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => 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<ArgumentOutOfRangeException>(() => q.GetSubset(batchIndex, 0, 0, 1)).Wait();
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => 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:

View File

@@ -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<IAzureResourceManager>(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<ExpiredTokenException>(() => accountManager.GetSelectedSubscriptionsAsync());
Assert.ThrowsAsync<ExpiredTokenException>(() => accountManager.GetSelectedSubscriptionsAsync());
}
[Fact]
[Test]
public async Task GetSubscriptionShouldThrowIfFailed()
{
var currentUserAccount = CreateAccount();
IAzureAuthenticationManager accountManager = await CreateAccountManager(currentUserAccount, null, true);
await Assert.ThrowsAsync<ServiceFailedException>(() => accountManager.GetSelectedSubscriptionsAsync());
Assert.ThrowsAsync<ServiceFailedException>(() => accountManager.GetSelectedSubscriptionsAsync());
}
[Fact]
[Test]
public async Task GetSubscriptionShouldReturnTheListSuccessfully()
{
List<IAzureUserAccountSubscriptionContext> subscriptions = new List<IAzureUserAccountSubscriptionContext> {

View File

@@ -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
/// </summary>
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<string, List<string>> subscriptionToDatabaseMap = CreateSubscriptonMap(2);
@@ -107,7 +107,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
ValidateResult(subscriptionToDatabaseMap, list);
}
[Fact]
[Test]
public async Task GetShouldReturnDatabasesFromServiceIfGetCalledTwiceButRefreshed()
{
Dictionary<string, List<string>> subscriptionToDatabaseMap = CreateSubscriptonMap(2);
@@ -187,7 +187,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
return subscriptionToDatabaseMapCopy;
}
[Fact]
[Test]
public async Task GetShouldReturnEmptyGivenNotSubscriptionFound()
{
Dictionary<string, List<string>> subscriptionToDatabaseMap = new Dictionary<string, List<string>>();

View File

@@ -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)

View File

@@ -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
/// </summary>
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<string, List<string>> subscriptionToDatabaseMap = new Dictionary<string, List<string>>();

View File

@@ -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
/// </summary>
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();

View File

@@ -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<ExportableDescriptor<IServerDiscoveryProvider>> providers =
@@ -56,19 +56,19 @@
// Assert.NotNull(providers);
// }
// [Fact]
// [Test]
// public void GetShouldReturnEmptyListGivenInvalidCategory()
// {
// Assert.False(_dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition(null, "invalid category")).Any());
// }
// [Fact]
// [Test]
// public void GetShouldReturnEmptyListGivenInvalidServerType()
// {
// Assert.False(_dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition("invalid server type", null)).Any());
// }
// [Fact]
// [Test]
// public void GetShouldReturnAllProvidersGivenNoParameter()
// {
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> 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<ExportableDescriptor<IServerDiscoveryProvider>> 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<ExportableDescriptor<IServerDiscoveryProvider>> 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<IServerDiscoveryProvider>();
@@ -188,7 +188,7 @@
// Assert.True(descriptor.Exportable == expectedProvider);
// }
// [Fact]
// [Test]
// public void GetShouldReturnTheServiceThatMatchedExactlyIfServerTypeSpecified()
// {
// IServerDiscoveryProvider expectedProvider = new Mock<IServerDiscoveryProvider>();
@@ -214,7 +214,7 @@
// Assert.True(descriptor.Exportable == expectedProvider);
// }
// [Fact]
// [Test]
// public void GetShouldReturnTheServiceThatMatchedExactlyIfCategorySpecified()
// {
// IServerDiscoveryProvider expectedProvider = new Mock<IServerDiscoveryProvider>();
@@ -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<ServerInstanceInfo> expectedServers = _localSqlServers;
@@ -289,7 +289,7 @@
// ServiceResponse<ServerInstanceInfo> result = await provider.Exportable.GetServerInstancesAsync();
// var servers = result.Data;
// Assert.NotNull(servers);
// Assert.Equal(expectedServers, servers);
// Assert.AreEqual(expectedServers, servers);
// }
// }
//}

View File

@@ -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
/// </summary>
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()

View File

@@ -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<ArgumentNullException>("errorMessage", () =>
Assert.Throws<ArgumentNullException>(() =>
{
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());
}
}
}

View File

@@ -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
/// </summary>
public class FirewallRuleServiceTest
{
[Fact]
[Test]
public async Task CreateShouldThrowExceptionGivenNullServerName()
{
string serverName = null;
ServiceTestContext testContext = new ServiceTestContext();
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
}
[Fact]
[Test]
public async Task CreateShouldThrowExceptionGivenNullStartIp()
{
string serverName = "serverName";
ServiceTestContext testContext = new ServiceTestContext();
testContext.StartIpAddress = null;
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
}
[Fact]
[Test]
public async Task CreateShouldThrowExceptionGivenInvalidEndIp()
{
string serverName = "serverName";
ServiceTestContext testContext = new ServiceTestContext();
testContext.EndIpAddress = "invalid ip";
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
}
[Fact]
[Test]
public async Task CreateShouldThrowExceptionGivenInvalidStartIp()
{
string serverName = "serverName";
ServiceTestContext testContext = new ServiceTestContext();
testContext.StartIpAddress = "invalid ip";
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
}
[Fact]
[Test]
public async Task CreateShouldThrowExceptionGivenNullEndIp()
{
ServiceTestContext testContext = new ServiceTestContext();
testContext.EndIpAddress = null;
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
}
[Fact]
[Test]
public async Task CreateShouldThrowExceptionIfUserIsNotLoggedIn()
{
var applicationAuthenticationManagerMock = new Mock<IAzureAuthenticationManager>();
@@ -78,13 +78,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider
testContext.ApplicationAuthenticationManagerMock = applicationAuthenticationManagerMock;
testContext.AzureResourceManagerMock = azureResourceManagerMock;
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
azureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync(
It.IsAny<IAzureResourceManagementSession>(), It.IsAny<IAzureSqlServerResource>(), It.IsAny<FirewallRuleRequest>()),
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<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
azureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync(
It.IsAny<IAzureResourceManagementSession>(), It.IsAny<IAzureSqlServerResource>(), It.IsAny<FirewallRuleRequest>()),
Times.Never);
}
[Fact]
[Test]
public async Task CreateShouldThrowExceptionIfAuthenticationManagerFailsToReturnSubscription()
{
var applicationAuthenticationManagerMock = new Mock<IAzureAuthenticationManager>();
@@ -115,23 +115,23 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider
ServiceTestContext testContext = new ServiceTestContext();
testContext.ApplicationAuthenticationManagerMock = applicationAuthenticationManagerMock;
testContext.AzureResourceManagerMock = azureResourceManagerMock;
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, "invalid server"));
Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, "invalid server"));
azureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync(
It.IsAny<IAzureResourceManagementSession>(), It.IsAny<IAzureSqlServerResource>(), It.IsAny<FirewallRuleRequest>()),
Times.Never);
}
[Fact]
[Test]
public async Task CreateShouldThrowExceptionGivenNoSubscriptionFound()
{
ServiceTestContext testContext = new ServiceTestContext();
testContext = CreateMocks(testContext);
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, "invalid server"));
Assert.ThrowsAsync<FirewallRuleException>(() => 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<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
Assert.ThrowsAsync<FirewallRuleException>(() => 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<IAzureSqlServerResource>();
testContext = CreateMocks(testContext);
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName, false));
Assert.ThrowsAsync<FirewallRuleException>(() => 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<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName, false));
Assert.ThrowsAsync<FirewallRuleException>(() => 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<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName, false));
Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName, false));
}
[Fact]
[Test]
public async Task CreateShouldCreateFirewallForTheRightServerFullyQualifiedName()
{
ServiceTestContext testContext = new ServiceTestContext();

View File

@@ -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);
});

View File

@@ -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

View File

@@ -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]);
}
}
}

View File

@@ -14,7 +14,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
/// <summary>
/// SQL sysname supports single quotes in object names, so URN attributes need to be properly escaped
/// </summary>
[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']");

View File

@@ -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<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -78,10 +78,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(6, results.Count());
Assert.AreEqual(6, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeNone()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -93,10 +93,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(0, results.Count());
Assert.AreEqual(0, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeName()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -108,10 +108,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(2, results.Count());
Assert.AreEqual(2, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeNameWildcard()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -123,7 +123,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(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<int>(4, results.Count());
Assert.AreEqual(4, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeSchema()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -152,10 +152,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(2, results.Count());
Assert.AreEqual(2, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeSchemaWildcard()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -167,10 +167,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(6, results.Count());
Assert.AreEqual(6, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeSchemaWildcardPostfixCriteria()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -182,10 +182,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(6, results.Count());
Assert.AreEqual(6, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeSchemaWildcardPostfix()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -197,10 +197,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: "View",
candidates: TestData);
Assert.Equal<int>(4, results.Count());
Assert.AreEqual(4, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeType()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -212,10 +212,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(4, results.Count());
Assert.AreEqual(4, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeNameAndSchema()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -227,10 +227,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(1, results.Count());
Assert.AreEqual(1, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchIncludeSchemaAndType()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -242,10 +242,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(2, results.Count());
Assert.AreEqual(2, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeName()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -257,10 +257,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(4, results.Count());
Assert.AreEqual(4, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeNameWildcard()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -272,7 +272,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(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<int>(4, results.Count());
Assert.AreEqual(4, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeSchema()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -301,10 +301,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(4, results.Count());
Assert.AreEqual(4, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeSchemaWildcard()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -316,10 +316,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(0, results.Count());
Assert.AreEqual(0, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeSchemaWildcardPostfix()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -331,10 +331,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(0, results.Count());
Assert.AreEqual(0, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeType()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -346,10 +346,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(2, results.Count());
Assert.AreEqual(2, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeNameAndSchemaCriteria()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -361,10 +361,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(5, results.Count());
Assert.AreEqual(5, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeNameAndSchema()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -376,10 +376,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(1, results.Count());
Assert.AreEqual(1, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeSchemaAndTypeCriteria()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -391,10 +391,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: null,
candidates: TestData);
Assert.Equal<int>(4, results.Count());
Assert.AreEqual(4, results.Count());
}
[Fact]
[Test]
public void ScriptingMatchExcludeSchemaAndType()
{
IEnumerable<ScriptingObject> results = ScriptingObjectMatcher.Match(
@@ -406,10 +406,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Scripting
excludeTypes: "View",
candidates: TestData);
Assert.Equal<int>(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]);
}
}
}

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