mirror of
https://github.com/ckaczor/sqltoolsservice.git
synced 2026-01-14 01:25:40 -05:00
Address warnings and (some) nullables (#2013)
This commit is contained in:
@@ -15,7 +15,7 @@ using System.IO;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.AzureFunctions
|
||||
{
|
||||
class AzureFunctionsServiceTests
|
||||
internal sealed class AzureFunctionsServiceTests
|
||||
{
|
||||
private string testAzureFunctionsFolder = Path.Combine("..", "..", "..", "AzureFunctions", "AzureFunctionTestFiles");
|
||||
|
||||
|
||||
@@ -29,14 +29,14 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
|
||||
/// </summary>
|
||||
public class ReliableConnectionTests
|
||||
{
|
||||
internal class TestDataTransferErrorDetectionStrategy : DataTransferErrorDetectionStrategy
|
||||
internal sealed class TestDataTransferErrorDetectionStrategy : DataTransferErrorDetectionStrategy
|
||||
{
|
||||
public bool InvokeCanRetrySqlException(SqlException exception)
|
||||
{
|
||||
return CanRetrySqlException(exception);
|
||||
}
|
||||
}
|
||||
internal class TestSqlAzureTemporaryAndIgnorableErrorDetectionStrategy : SqlAzureTemporaryAndIgnorableErrorDetectionStrategy
|
||||
internal sealed class TestSqlAzureTemporaryAndIgnorableErrorDetectionStrategy : SqlAzureTemporaryAndIgnorableErrorDetectionStrategy
|
||||
{
|
||||
public TestSqlAzureTemporaryAndIgnorableErrorDetectionStrategy()
|
||||
: base (new int[] { 100 })
|
||||
@@ -54,7 +54,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestFixedDelayPolicy : FixedDelayPolicy
|
||||
internal sealed class TestFixedDelayPolicy : FixedDelayPolicy
|
||||
{
|
||||
public TestFixedDelayPolicy(
|
||||
IErrorDetectionStrategy strategy,
|
||||
@@ -77,7 +77,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestProgressiveRetryPolicy : ProgressiveRetryPolicy
|
||||
internal sealed class TestProgressiveRetryPolicy : ProgressiveRetryPolicy
|
||||
{
|
||||
public TestProgressiveRetryPolicy(
|
||||
IErrorDetectionStrategy strategy,
|
||||
@@ -97,7 +97,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestTimeBasedRetryPolicy : TimeBasedRetryPolicy
|
||||
internal sealed class TestTimeBasedRetryPolicy : TimeBasedRetryPolicy
|
||||
{
|
||||
public TestTimeBasedRetryPolicy(
|
||||
IErrorDetectionStrategy strategy,
|
||||
@@ -916,7 +916,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
|
||||
command.UpdatedRowSource = UpdateRowSource.None;
|
||||
Assert.AreEqual(UpdateRowSource.None, command.UpdatedRowSource);
|
||||
Assert.NotNull(command.GetUnderlyingCommand());
|
||||
Assert.Throws<InvalidOperationException>(() => command.ValidateConnectionIsSet());
|
||||
Assert.Throws<InvalidOperationException>(command.ValidateConnectionIsSet);
|
||||
command.Prepare();
|
||||
Assert.NotNull(command.CreateParameter());
|
||||
command.Cancel();
|
||||
|
||||
@@ -30,7 +30,7 @@ using static Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility.LiveConnec
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
|
||||
{
|
||||
class BackupRestoreUrlTests
|
||||
internal sealed class BackupRestoreUrlTests
|
||||
{
|
||||
/// <summary>
|
||||
/// Create simple backup test
|
||||
|
||||
@@ -574,7 +574,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery
|
||||
string backUpFilePath = string.Empty;
|
||||
if (backupFileNames != null)
|
||||
{
|
||||
var filePaths = backupFileNames.Select(x => GetBackupFilePath(x));
|
||||
var filePaths = backupFileNames.Select(GetBackupFilePath);
|
||||
backUpFilePath = filePaths.Aggregate((current, next) => current + " ," + next);
|
||||
}
|
||||
|
||||
|
||||
@@ -368,7 +368,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
|
||||
await langService.HandleDidChangeLanguageFlavorNotification(new LanguageFlavorChangeParams
|
||||
{
|
||||
Uri = scriptFile.ClientUri,
|
||||
Language = LanguageService.SQL_LANG.ToLower(),
|
||||
Language = LanguageService.SQL_LANG.ToLower(System.Globalization.CultureInfo.InvariantCulture),
|
||||
Flavor = "MSSQL"
|
||||
}, eventContextSql.Object);
|
||||
await langService.DelayedDiagnosticsTask; // to ensure completion and validation before moveing to next step
|
||||
@@ -379,7 +379,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
|
||||
await langService.HandleDidChangeLanguageFlavorNotification(new LanguageFlavorChangeParams
|
||||
{
|
||||
Uri = scriptFile.ClientUri,
|
||||
Language = LanguageService.SQL_CMD_LANG.ToLower(),
|
||||
Language = LanguageService.SQL_CMD_LANG.ToLower(System.Globalization.CultureInfo.InvariantCulture),
|
||||
Flavor = "MSSQL"
|
||||
}, eventContextSqlCmd.Object);
|
||||
await langService.DelayedDiagnosticsTask;
|
||||
|
||||
@@ -6,8 +6,6 @@
|
||||
<PackageId>Microsoft.SqlTools.ServiceLayer.IntegrationTests</PackageId>
|
||||
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
|
||||
<DefineConstants>$(DefineConstants);TRACE</DefineConstants>
|
||||
<!-- TODO FIX THESE WARNINGS ASAP -->
|
||||
<NoWarn>$(NoWarn);SYSLIB1045;IDE0200;IDE0230;CA1311;CA1852;CA1854</NoWarn>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/Microsoft.SqlTools.Hosting/Microsoft.SqlTools.Hosting.csproj" />
|
||||
|
||||
@@ -28,7 +28,7 @@ using static Microsoft.SqlTools.ServiceLayer.ObjectExplorer.ObjectExplorerServic
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
|
||||
{
|
||||
public class ObjectExplorerServiceTests
|
||||
public partial class ObjectExplorerServiceTests
|
||||
{
|
||||
private ObjectExplorerService _service = TestServiceProvider.Instance.ObjectExplorerService;
|
||||
|
||||
@@ -124,10 +124,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
|
||||
{
|
||||
var query = "";
|
||||
string databaseName = "#testDb#";
|
||||
await RunTest(databaseName, query, "TestDb", async (testDbName, session) =>
|
||||
{
|
||||
await ExpandAndVerifyDatabaseNode(testDbName, session);
|
||||
});
|
||||
await RunTest(databaseName, query, "TestDb", ExpandAndVerifyDatabaseNode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -376,7 +373,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
|
||||
ConnectParams connectParams = TestServiceProvider.Instance.ConnectionProfileService.GetConnectionParameters(TestServerType.OnPrem, databaseName);
|
||||
//connectParams.Connection.Pooling = false;
|
||||
ConnectionDetails details = connectParams.Connection;
|
||||
string uri = ObjectExplorerService.GenerateUri(details);
|
||||
string uri = GenerateUri(details);
|
||||
|
||||
var session = await _service.DoCreateSession(details, uri);
|
||||
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "OE session created for database: {0}", databaseName));
|
||||
@@ -387,10 +384,10 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
|
||||
{
|
||||
Assert.That(session, Is.Not.Null, nameof(session));
|
||||
Assert.That(session.Root, Is.Not.Null, nameof(session.Root));
|
||||
NodeInfo nodeInfo = session.Root.ToNodeInfo();
|
||||
var nodeInfo = session.Root.ToNodeInfo();
|
||||
Assert.That(nodeInfo.IsLeaf, Is.False, "Should not be a leaf node");
|
||||
|
||||
NodeInfo? databaseNode = null;
|
||||
NodeInfo databaseNode = null;
|
||||
|
||||
if (serverNode)
|
||||
{
|
||||
@@ -435,7 +432,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
|
||||
{
|
||||
Assert.NotNull(session);
|
||||
Assert.NotNull(session.Root);
|
||||
NodeInfo nodeInfo = session.Root.ToNodeInfo();
|
||||
var nodeInfo = session.Root.ToNodeInfo();
|
||||
Assert.AreEqual(false, nodeInfo.IsLeaf);
|
||||
Assert.AreEqual(nodeInfo.NodeType, NodeTypes.Database.ToString());
|
||||
Assert.True(nodeInfo.Label.Contains(databaseName));
|
||||
@@ -457,7 +454,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
|
||||
Console.WriteLine($"Session closed uri:{uri}");
|
||||
}
|
||||
|
||||
private async Task ExpandTree(NodeInfo node, ObjectExplorerSession session, StringBuilder? stringBuilder = null, bool verifySystemObjects = false)
|
||||
private async Task ExpandTree(NodeInfo node, ObjectExplorerSession session, StringBuilder stringBuilder = null, bool verifySystemObjects = false)
|
||||
{
|
||||
if (node != null && !node.IsLeaf)
|
||||
{
|
||||
@@ -552,7 +549,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
|
||||
private async Task<bool> VerifyObjectExplorerTest(string databaseName, string testDbPrefix, string queryFileName, string baselineFileName, bool verifySystemObjects = false)
|
||||
{
|
||||
var query = string.IsNullOrEmpty(queryFileName) ? string.Empty : LoadScript(queryFileName);
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
var stringBuilder = new StringBuilder();
|
||||
await RunTest(databaseName, query, testDbPrefix, async (testDbName, session) =>
|
||||
{
|
||||
await ExpandServerNodeAndVerifyDatabaseHierachy(testDbName, session, false);
|
||||
@@ -564,7 +561,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
|
||||
|
||||
// Dropped ledger objects have a randomly generated GUID appended to their name when they are deleted
|
||||
// For testing purposes, those guids need to be replaced with a deterministic string
|
||||
actual = Regex.Replace(actual, "[A-Z0-9]{32}", "<<NonDeterministic>>");
|
||||
actual = GetBaselineRegex().Replace(actual, "<<NonDeterministic>>");
|
||||
|
||||
// Write output to a bin directory for easier comparison
|
||||
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;
|
||||
@@ -640,5 +637,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
|
||||
FileInfo inputFile = GetBaseLineFile(fileName);
|
||||
return TestUtilities.ReadTextAndNormalizeLineEndings(inputFile.FullName);
|
||||
}
|
||||
|
||||
[GeneratedRegex("[A-Z0-9]{32}")]
|
||||
private static partial Regex GetBaselineRegex();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
|
||||
// SQL greater than 300000 characters should throw
|
||||
string bigSql = string.Concat(Repeat(element: sqlLength_300, count: 1100));
|
||||
DbCommand command2 = new SqlCommand { CommandText = bigSql };
|
||||
Assert.Throws<ParameterizationScriptTooLargeException>(() => command2.Parameterize());
|
||||
Assert.Throws<ParameterizationScriptTooLargeException>(command2.Parameterize);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -128,7 +128,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
|
||||
string sql = string.Concat(Repeat(element: invalidSql, count: 1000));
|
||||
DbCommand command = new SqlCommand { CommandText = sql };
|
||||
|
||||
Assert.Throws<ParameterizationParsingException>(() => command.Parameterize());
|
||||
Assert.Throws<ParameterizationParsingException>(command.Parameterize);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -149,7 +149,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.AutoParameterization
|
||||
GO";
|
||||
|
||||
DbCommand command = new SqlCommand { CommandText = sql };
|
||||
Assert.Throws<ParameterizationFormatException>(() => command.Parameterize());
|
||||
Assert.Throws<ParameterizationFormatException>(command.Parameterize);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -15,7 +15,7 @@ using Azure.Storage.Sas;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.DisasterRecovery
|
||||
{
|
||||
class SharedAccessSignatureCreatorTests
|
||||
internal sealed class SharedAccessSignatureCreatorTests
|
||||
{
|
||||
[Test]
|
||||
public void GetServiceSasUriForContainerReturnsNullWhenCannotGenerateSasUri()
|
||||
|
||||
@@ -105,8 +105,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
yield return new object[] {"0x000", new byte[] {0x00, 0x00}, "0x0000"}; // Base16, odd
|
||||
|
||||
// Single byte tests
|
||||
yield return new object[] {"50", new byte[] {0x32}, "0x32"}; // Base10
|
||||
yield return new object[] {"050", new byte[] {0x32}, "0x32"}; // Base10, leading zeros
|
||||
yield return new object[] {"50", "2"u8.ToArray(), "0x32"}; // Base10
|
||||
yield return new object[] {"050", "2"u8.ToArray(), "0x32"}; // Base10, leading zeros
|
||||
yield return new object[] {"0xF0", new byte[] {0xF0}, "0xF0"}; // Base16
|
||||
yield return new object[] {"0x0F", new byte[] {0x0F}, "0x0F"}; // Base16, leading zeros
|
||||
yield return new object[] {"0xF", new byte[] {0x0F}, "0x0F"}; // Base16, odd
|
||||
@@ -296,7 +296,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
return new DbColumnWrapper(new CellUpdateTestDbColumn(typeof(T), dataTypeName, allowNull, colSize));
|
||||
}
|
||||
|
||||
private class CellUpdateTestDbColumn : DbColumn
|
||||
private sealed class CellUpdateTestDbColumn : DbColumn
|
||||
{
|
||||
public CellUpdateTestDbColumn(Type dataType, string dataTypeName, bool allowNull = true, int? colSize = null)
|
||||
{
|
||||
|
||||
@@ -21,18 +21,18 @@ using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
public class RowCreateTests
|
||||
public partial class RowCreateTests
|
||||
{
|
||||
[Test]
|
||||
public async Task RowCreateConstruction()
|
||||
{
|
||||
// Setup: Create the values to store
|
||||
const long rowId = 100;
|
||||
Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(false, false, 0, 0);
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, 0, 0);
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
|
||||
// If: I create a RowCreate instance
|
||||
RowCreate rc = new RowCreate(rowId, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(rowId, rs, data.TableMetadata);
|
||||
|
||||
// Then: The values I provided should be available
|
||||
Assert.AreEqual(rowId, rc.RowId);
|
||||
@@ -67,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// Setup: Generate the parameters for the row create
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, defaultCols, nullableCols);
|
||||
var rs = await Common.GetResultSet(data.DbColumns, includeIdentity);
|
||||
RowCreate rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
|
||||
// If: I ask for a script to be generated without setting any values
|
||||
// Then: An exception should be thrown for missing cells
|
||||
@@ -116,11 +116,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Generate the parameters for the row create
|
||||
Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, colsWithDefaultConstraints, colsThatAllowNull);
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, colsWithDefaultConstraints, colsThatAllowNull);
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, includeIdentity);
|
||||
|
||||
// ... Create a row create and set the appropriate number of cells
|
||||
RowCreate rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
Common.AddCells(rc, valuesToSkipSetting);
|
||||
|
||||
// If: I ask for the script for the row insert
|
||||
@@ -139,8 +139,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
if (expectedOutput == null)
|
||||
{
|
||||
// If expected output was null make sure we match the default values reges
|
||||
Regex r = new Regex(@"INSERT INTO (.+) DEFAULT VALUES");
|
||||
Match m = r.Match(sql);
|
||||
Match m = GetInsert1Regex().Match(sql);
|
||||
Assert.True(m.Success);
|
||||
|
||||
// Table name matches
|
||||
@@ -149,8 +148,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
else
|
||||
{
|
||||
// Do the whole validation
|
||||
Regex r = new Regex(@"INSERT INTO (.+)\((.+)\) VALUES \((.+)\)");
|
||||
Match m = r.Match(sql);
|
||||
Match m = GetInsert2Regex().Match(sql);
|
||||
Assert.True(m.Success);
|
||||
|
||||
// Table name matches
|
||||
@@ -174,14 +172,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// Setup:
|
||||
// ... Generate the parameters for the row create
|
||||
const long rowId = 100;
|
||||
Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, 0, 0);
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, 0, 0);
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, includeIdentity);
|
||||
|
||||
// ... Setup a db reader for the result of an insert
|
||||
var newRowReader = Common.GetNewRowDataReader(data.DbColumns, includeIdentity);
|
||||
|
||||
// If: I ask for the change to be applied
|
||||
RowCreate rc = new RowCreate(rowId, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(rowId, rs, data.TableMetadata);
|
||||
await rc.ApplyChanges(newRowReader);
|
||||
|
||||
// Then: The result set should have an additional row in it
|
||||
@@ -226,9 +224,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Generate the row create object
|
||||
Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, defaultCols, nullableCols);
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, defaultCols, nullableCols);
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, includeIdentity);
|
||||
RowCreate rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
|
||||
// ... Create a mock db connection for building the command
|
||||
var mockConn = new TestSqlConnection();
|
||||
@@ -280,14 +278,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Generate the parameters for the row create
|
||||
Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, defaultCols, nullableCols);
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, defaultCols, nullableCols);
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, includeIdentity);
|
||||
|
||||
// ... Mock db connection for building the command
|
||||
var mockConn = new TestSqlConnection(null);
|
||||
|
||||
// ... Create a row create and set the appropriate number of cells
|
||||
RowCreate rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
Common.AddCells(rc, valuesToSkip);
|
||||
|
||||
// If: I ask for the command for the row insert
|
||||
@@ -311,8 +309,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
Assert.AreEqual(3, splitSql.Length);
|
||||
|
||||
// Check the declare statement first
|
||||
Regex declareRegex = new Regex(@"^DECLARE @(.+) TABLE \((.+)\)$");
|
||||
Match declareMatch = declareRegex.Match(splitSql[0]);
|
||||
Match declareMatch = GetDeclareRegex().Match(splitSql[0]);
|
||||
Assert.True(declareMatch.Success);
|
||||
|
||||
// Declared table name matches
|
||||
@@ -327,7 +324,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
if (expectedOutput.ExpectedInColumns == 0 || expectedOutput.ExpectedInValues == 0)
|
||||
{
|
||||
// If expected output was null make sure we match the default values reges
|
||||
Regex insertRegex = new Regex(@"^INSERT INTO (.+) OUTPUT (.+) INTO @(.+) DEFAULT VALUES$");
|
||||
var insertRegex = GetInsertRegex();
|
||||
Match insertMatch = insertRegex.Match(splitSql[1]);
|
||||
Assert.True(insertMatch.Success);
|
||||
|
||||
@@ -347,7 +344,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
else
|
||||
{
|
||||
// Do the whole validation
|
||||
Regex insertRegex = new Regex(@"^INSERT INTO (.+)\((.+)\) OUTPUT (.+) INTO @(.+) VALUES \((.+)\)$");
|
||||
var insertRegex = GetInsertFullRegex();
|
||||
Match insertMatch = insertRegex.Match(splitSql[1]);
|
||||
Assert.True(insertMatch.Success);
|
||||
|
||||
@@ -380,7 +377,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
}
|
||||
|
||||
// Check the select statement last
|
||||
Regex selectRegex = new Regex(@"^SELECT (.+) FROM @(.+)$");
|
||||
var selectRegex = GetSelectRegex();
|
||||
Match selectMatch = selectRegex.Match(splitSql[2]);
|
||||
Assert.True(selectMatch.Success);
|
||||
|
||||
@@ -425,9 +422,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup: Generate a row create with default values
|
||||
const long rowId = 100;
|
||||
Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(false, false, 3, 0);
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, 3, 0);
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
RowCreate rc = new RowCreate(rowId, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(rowId, rs, data.TableMetadata);
|
||||
|
||||
// If: I request an edit row from the row create
|
||||
EditRow er = rc.GetEditRow(null);
|
||||
@@ -451,9 +448,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup: Generate a row create with an identity column
|
||||
const long rowId = 100;
|
||||
Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(false, true, 0, 0);
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, true, 0, 0);
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, true);
|
||||
RowCreate rc = new RowCreate(rowId, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(rowId, rs, data.TableMetadata);
|
||||
|
||||
// If: I request an edit row from the row created
|
||||
EditRow er = rc.GetEditRow(null);
|
||||
@@ -573,7 +570,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
var etm = Common.GetCustomEditTableMetadata(cols);
|
||||
|
||||
// ... Create the row create
|
||||
RowCreate rc = new RowCreate(100, rs, etm);
|
||||
var rc = new RowCreate(100, rs, etm);
|
||||
|
||||
// If: I set a cell in the newly created row to something that will be corrected
|
||||
EditUpdateCellResult eucr = rc.SetCell(0, "1000");
|
||||
@@ -644,9 +641,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Generate the parameters for the row create
|
||||
Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(false, false, defaultCols, 0);
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, defaultCols, 0);
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
RowCreate rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
|
||||
// If: I attempt to revert a cell that has not been set
|
||||
EditRevertCellResult result = rc.RevertCell(0);
|
||||
@@ -673,9 +670,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Generate the parameters for the row create
|
||||
Common.TestDbColumnsWithTableMetadata data = new Common.TestDbColumnsWithTableMetadata(false, false, defaultCols, 0);
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, defaultCols, 0);
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
RowCreate rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
var rc = new RowCreate(100, rs, data.TableMetadata);
|
||||
rc.SetCell(0, "1");
|
||||
|
||||
// If: I attempt to revert a cell that was set
|
||||
@@ -720,5 +717,25 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
public int ExpectedInValues { get; }
|
||||
public int ExpectedOutColumns { get; }
|
||||
}
|
||||
|
||||
#region Generated Regex
|
||||
[GeneratedRegex("INSERT INTO (.+) DEFAULT VALUES")]
|
||||
private static partial Regex GetInsert1Regex();
|
||||
|
||||
[GeneratedRegex("INSERT INTO (.+)\\((.+)\\) VALUES \\((.+)\\)")]
|
||||
private static partial Regex GetInsert2Regex();
|
||||
|
||||
[GeneratedRegex("^DECLARE @(.+) TABLE \\((.+)\\)$")]
|
||||
private static partial Regex GetDeclareRegex();
|
||||
|
||||
[GeneratedRegex("^INSERT INTO (.+) OUTPUT (.+) INTO @(.+) DEFAULT VALUES$")]
|
||||
private static partial Regex GetInsertRegex();
|
||||
|
||||
[GeneratedRegex("^INSERT INTO (.+)\\((.+)\\) OUTPUT (.+) INTO @(.+) VALUES \\((.+)\\)$")]
|
||||
private static partial Regex GetInsertFullRegex();
|
||||
|
||||
[GeneratedRegex("^SELECT (.+) FROM @(.+)$")]
|
||||
private static partial Regex GetSelectRegex();
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,7 +251,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
return resultSet;
|
||||
}
|
||||
|
||||
private class RowEditTester : RowEditBase
|
||||
private sealed class RowEditTester : RowEditBase
|
||||
{
|
||||
public RowEditTester(ResultSet rs, EditTableMetadata meta) : base(0, rs, meta) { }
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
public class RowUpdateTests
|
||||
public partial class RowUpdateTests
|
||||
{
|
||||
[Test]
|
||||
public async Task RowUpdateConstruction()
|
||||
@@ -32,7 +32,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
var rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
|
||||
// If: I create a RowUpdate instance
|
||||
RowUpdate rc = new RowUpdate(rowId, rs, data.TableMetadata);
|
||||
var rc = new RowUpdate(rowId, rs, data.TableMetadata);
|
||||
|
||||
// Then: The values I provided should be available
|
||||
Assert.AreEqual(rowId, rc.RowId);
|
||||
@@ -61,7 +61,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
|
||||
// If:
|
||||
// ... I add updates to all the cells in the row
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
Common.AddCells(ru, 1);
|
||||
|
||||
// ... Then I update a cell back to it's old value
|
||||
@@ -83,8 +83,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
Assert.True(eucr.IsRowDirty);
|
||||
|
||||
// ... It should be formatted as an update script
|
||||
Regex r = new Regex(@"UPDATE .+ SET (.*) WHERE");
|
||||
var m = r.Match(ru.GetScript());
|
||||
var m = GetUpdateRegex().Match(ru.GetScript());
|
||||
|
||||
// ... It should have 2 updates
|
||||
string updates = m.Groups[1].Value;
|
||||
@@ -102,7 +101,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
|
||||
// If:
|
||||
// ... I add updates to one cell in the row
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
ru.SetCell(1, "qqq");
|
||||
|
||||
// ... Then I update the cell to its original value
|
||||
@@ -149,7 +148,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
var etm = Common.GetCustomEditTableMetadata(cols);
|
||||
|
||||
// ... Create the row update
|
||||
RowUpdate ru = new RowUpdate(0, rs, etm);
|
||||
var ru = new RowUpdate(0, rs, etm);
|
||||
|
||||
// If: I set a cell in the newly created row to something that will be corrected
|
||||
EditUpdateCellResult eucr = ru.SetCell(0, "1000");
|
||||
@@ -214,7 +213,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
ResultSet rs = await Common.GetResultSet(data.DbColumns, true);
|
||||
|
||||
// If: I ask for a script to be generated for update
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
Common.AddCells(ru, 1);
|
||||
string script = ru.GetScript();
|
||||
|
||||
@@ -226,7 +225,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
string regexString = isMemoryOptimized
|
||||
? @"UPDATE (.+) WITH \(SNAPSHOT\) SET (.*) WHERE .+"
|
||||
: @"UPDATE (.+) SET (.*) WHERE .+";
|
||||
Regex r = new Regex(regexString);
|
||||
var r = new Regex(regexString);
|
||||
var m = r.Match(script);
|
||||
Assert.True(m.Success);
|
||||
|
||||
@@ -248,7 +247,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// ... Create a row update with cell updates
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(isMemoryOptimized, includeIdentity, 0, 0);
|
||||
var rs = await Common.GetResultSet(data.DbColumns, includeIdentity);
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
Common.AddCells(ru, includeIdentity ? 1 : 0);
|
||||
|
||||
// ... Mock db connection for building the command
|
||||
@@ -267,8 +266,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
Assert.True(splitSql.Length >= 3);
|
||||
|
||||
// Check the declare statement first
|
||||
Regex declareRegex = new Regex(@"^DECLARE @(.+) TABLE \((.+)\)$");
|
||||
Match declareMatch = declareRegex.Match(splitSql[0]);
|
||||
Match declareMatch = GetDeclareTableRegex().Match(splitSql[0]);
|
||||
Assert.True(declareMatch.Success);
|
||||
|
||||
// Declared table name matches
|
||||
@@ -283,7 +281,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
string regex = isMemoryOptimized
|
||||
? @"^UPDATE (.+) WITH \(SNAPSHOT\) SET (.+) OUTPUT (.+) INTO @(.+) WHERE .+$"
|
||||
: @"^UPDATE (.+) SET (.+) OUTPUT (.+) INTO @(.+) WHERE .+$";
|
||||
Regex updateRegex = new Regex(regex);
|
||||
var updateRegex = new Regex(regex);
|
||||
Match updateMatch = updateRegex.Match(splitSql[10]);
|
||||
Assert.True(updateMatch.Success);
|
||||
|
||||
@@ -304,8 +302,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
Assert.That(updateMatch.Groups[4].Value, Does.EndWith("Output"));
|
||||
|
||||
// Check the select statement last
|
||||
Regex selectRegex = new Regex(@"^SELECT (.+) FROM @(.+)$");
|
||||
Match selectMatch = selectRegex.Match(splitSql[11]);
|
||||
Match selectMatch = GetSelectRegex().Match(splitSql[11]);
|
||||
Assert.True(selectMatch.Success);
|
||||
|
||||
// Correct number of columns in select statement
|
||||
@@ -343,7 +340,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// Setup: Create a row update with a cell set
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, 0, 0);
|
||||
var rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
ru.SetCell(0, "foo");
|
||||
|
||||
// If: I attempt to get an edit row
|
||||
@@ -399,7 +396,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// ... Create a row update (no cell updates needed)
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, includeIdentity, 0, 0);
|
||||
var rs = await Common.GetResultSet(data.DbColumns, includeIdentity);
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
long oldBytesWritten = rs.totalBytesWritten;
|
||||
|
||||
// ... Setup a db reader for the result of an update
|
||||
@@ -421,7 +418,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// ... Create a row update (no cell updates needed)
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, true, 0, 0);
|
||||
var rs = await Common.GetResultSet(data.DbColumns, true);
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
|
||||
// If: I ask for the changes to be applied with a null db reader
|
||||
// Then: I should get an exception
|
||||
@@ -439,7 +436,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// ... Create a row update (no cell updates needed)
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, 0, 0);
|
||||
var rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
|
||||
// If: I attempt to revert a cell that is out of range
|
||||
// Then: I should get an exception
|
||||
@@ -453,7 +450,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// ... Create a row update (no cell updates needed)
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, true, 0, 0);
|
||||
var rs = await Common.GetResultSet(data.DbColumns, true);
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
|
||||
// If: I attempt to revert a cell that has not been set
|
||||
EditRevertCellResult result = ru.RevertCell(0);
|
||||
@@ -480,7 +477,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// ... Create a row update
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, 0, 0);
|
||||
var rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
ru.SetCell(0, "qqq");
|
||||
ru.SetCell(1, "qqq");
|
||||
|
||||
@@ -509,7 +506,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// ... Create a row update
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, 0, 0);
|
||||
var rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
RowUpdate ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
var ru = new RowUpdate(0, rs, data.TableMetadata);
|
||||
ru.SetCell(0, "qqq");
|
||||
|
||||
// If: I attempt to revert a cell that was set
|
||||
@@ -538,5 +535,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
var rs = await Common.GetResultSet(data.DbColumns, false);
|
||||
return new RowUpdate(0, rs, data.TableMetadata);
|
||||
}
|
||||
|
||||
[GeneratedRegex("^DECLARE @(.+) TABLE \\((.+)\\)$")]
|
||||
private static partial Regex GetDeclareTableRegex();
|
||||
|
||||
[GeneratedRegex("^SELECT (.+) FROM @(.+)$")]
|
||||
private static partial Regex GetSelectRegex();
|
||||
|
||||
[GeneratedRegex("UPDATE .+ SET (.*) WHERE")]
|
||||
private static partial Regex GetUpdateRegex();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
public class SessionTests
|
||||
public partial class SessionTests
|
||||
{
|
||||
#region Construction Tests
|
||||
|
||||
@@ -42,8 +42,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
public void SessionConstructionValid()
|
||||
{
|
||||
// If: I create a session object with a proper arguments
|
||||
Mock<IEditMetadataFactory> mockFactory = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(mockFactory.Object);
|
||||
var mockFactory = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(mockFactory.Object);
|
||||
|
||||
// Then:
|
||||
// ... The edit cache should not exist
|
||||
@@ -87,7 +87,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
|
||||
|
||||
var fsf = MemoryFileSystem.GetFileStreamFactory();
|
||||
Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fsf);
|
||||
var query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fsf);
|
||||
query.Execute();
|
||||
query.ExecutionTask.Wait();
|
||||
|
||||
@@ -116,8 +116,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session without initializing
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// If: I ask to create a row without initializing
|
||||
// Then: I should get an exception
|
||||
@@ -292,8 +292,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session and fake that it has been initialized
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object) {IsInitialized = true};
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object) {IsInitialized = true};
|
||||
|
||||
// If: I initialize it
|
||||
// Then: I should get an exception
|
||||
@@ -305,8 +305,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session and fake that it is in progress of initializing
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object) {InitializeTask = new Task(() => {})};
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object) {InitializeTask = new Task(() => {})};
|
||||
|
||||
// If: I initialize it
|
||||
// Then: I should get an exception
|
||||
@@ -320,8 +320,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session that hasn't been initialized
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
Assert.Catch<ArgumentException>(() => s.Initialize(initParams, c, qr, sh, fh), "I initialize it with a missing parameter. It should throw an exception");
|
||||
}
|
||||
@@ -381,12 +381,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a metadata factory that throws
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
emf.Setup(f => f.GetObjectMetadata(It.IsAny<DbConnection>(), It.IsAny<string[]>(), It.IsAny<string>()))
|
||||
.Throws<Exception>();
|
||||
|
||||
// ... Create a session that hasn't been initialized
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// ... Create a mock for verifying the failure handler will be called
|
||||
var successHandler = DoNothingSuccessMock;
|
||||
@@ -414,15 +414,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// ... Create a metadata factory that will return some generic column information
|
||||
var b = QueryExecution.Common.GetBasicExecutedBatch();
|
||||
var etm = Common.GetCustomEditTableMetadata(b.ResultSets[0].Columns.Cast<DbColumn>().ToArray());
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
emf.Setup(f => f.GetObjectMetadata(It.IsAny<DbConnection>(), It.IsAny<string[]>(), It.IsAny<string>()))
|
||||
.Returns(etm);
|
||||
|
||||
// ... Create a session that hasn't been initialized
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// ... Create a query runner that will fail via exception
|
||||
Mock<EditSession.QueryRunner> qr = new Mock<EditSession.QueryRunner>();
|
||||
var qr = new Mock<EditSession.QueryRunner>();
|
||||
qr.Setup(r => r(It.IsAny<string>())).Throws(new Exception("qqq"));
|
||||
|
||||
// ... Create a mock for verifying the failure handler will be called
|
||||
@@ -451,15 +451,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
// ... Create a metadata factory that will return some generic column information
|
||||
var b = QueryExecution.Common.GetBasicExecutedBatch();
|
||||
var etm = Common.GetCustomEditTableMetadata(b.ResultSets[0].Columns.Cast<DbColumn>().ToArray());
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
emf.Setup(f => f.GetObjectMetadata(It.IsAny<DbConnection>(), It.IsAny<string[]>(), It.IsAny<string>()))
|
||||
.Returns(etm);
|
||||
|
||||
// ... Create a session that hasn't been initialized
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// ... Create a query runner that will fail via returning a null query
|
||||
Mock<EditSession.QueryRunner> qr = new Mock<EditSession.QueryRunner>();
|
||||
var qr = new Mock<EditSession.QueryRunner>();
|
||||
qr.Setup(r => r(It.IsAny<string>()))
|
||||
.Returns(Task.FromResult(new EditSession.EditSessionQueryExecutionState(null, message)));
|
||||
|
||||
@@ -490,15 +490,15 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
var q = QueryExecution.Common.GetBasicExecutedQuery();
|
||||
var rs = q.Batches[0].ResultSets[0];
|
||||
var etm = Common.GetCustomEditTableMetadata(rs.Columns.Cast<DbColumn>().ToArray());
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
emf.Setup(f => f.GetObjectMetadata(It.IsAny<DbConnection>(), It.IsAny<string[]>(), It.IsAny<string>()))
|
||||
.Returns(etm);
|
||||
|
||||
// ... Create a session that hasn't been initialized
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// ... Create a query runner that will return a successful query
|
||||
Mock<EditSession.QueryRunner> qr = new Mock<EditSession.QueryRunner>();
|
||||
var qr = new Mock<EditSession.QueryRunner>();
|
||||
qr.Setup(r => r(It.IsAny<string>()))
|
||||
.Returns(Task.FromResult(new EditSession.EditSessionQueryExecutionState(q)));
|
||||
|
||||
@@ -533,8 +533,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session without initializing
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// If: I ask to delete a row without initializing
|
||||
// Then: I should get an exception
|
||||
@@ -583,8 +583,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session without initializing
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// If: I ask to revert a row without initializing
|
||||
// Then: I should get an exception
|
||||
@@ -683,8 +683,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session without initializing
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// If: I ask to revert a cell without initializing
|
||||
// Then: I should get an exception
|
||||
@@ -724,8 +724,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session without initializing
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// If: I ask to update a cell without initializing
|
||||
// Then: I should get an exception
|
||||
@@ -807,8 +807,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session without initializing
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// If: I ask to update a cell without initializing
|
||||
// Then: I should get an exception
|
||||
@@ -974,8 +974,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session without initializing
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// If: I ask to script edits without initializing
|
||||
// Then: I should get an exception
|
||||
@@ -1001,12 +1001,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
EditSession s = await GetBasicSession();
|
||||
|
||||
// ... Add two mock edits that will generate a script
|
||||
Mock<RowEditBase> edit = new Mock<RowEditBase>();
|
||||
var edit = new Mock<RowEditBase>();
|
||||
edit.Setup(e => e.GetScript()).Returns("test");
|
||||
s.EditCache[0] = edit.Object;
|
||||
s.EditCache[1] = edit.Object;
|
||||
|
||||
using (SelfCleaningTempFile file = new SelfCleaningTempFile())
|
||||
using (var file = new SelfCleaningTempFile())
|
||||
{
|
||||
// If: I script the edit cache to a local output path
|
||||
string outputPath = s.ScriptEdits(file.FilePath);
|
||||
@@ -1029,8 +1029,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
// Setup:
|
||||
// ... Create a session without initializing
|
||||
Mock<IEditMetadataFactory> emf = new Mock<IEditMetadataFactory>();
|
||||
EditSession s = new EditSession(emf.Object);
|
||||
var emf = new Mock<IEditMetadataFactory>();
|
||||
var s = new EditSession(emf.Object);
|
||||
|
||||
// If: I ask to script edits without initializing
|
||||
// Then: I should get an exception
|
||||
@@ -1088,7 +1088,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
DbConnection conn = new TestSqlConnection(null);
|
||||
|
||||
// ... Mock a task that has not completed
|
||||
Task notCompleted = new Task(() => {});
|
||||
var notCompleted = new Task(() => {});
|
||||
s.CommitTask = notCompleted;
|
||||
|
||||
// If: I attempt to commit while a task is in progress
|
||||
@@ -1106,7 +1106,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
DbConnection conn = new TestSqlConnection(null);
|
||||
|
||||
// ... Add a mock commands for fun
|
||||
Mock<RowEditBase> edit = new Mock<RowEditBase>();
|
||||
var edit = new Mock<RowEditBase>();
|
||||
edit.Setup(e => e.GetCommand(It.IsAny<DbConnection>())).Returns<DbConnection>(dbc => dbc.CreateCommand());
|
||||
edit.Setup(e => e.ApplyChanges(It.IsAny<DbDataReader>())).Returns(Task.FromResult(0));
|
||||
s.EditCache[0] = edit.Object;
|
||||
@@ -1150,7 +1150,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
DbConnection conn = new TestSqlConnection(null);
|
||||
|
||||
// ... Add a mock edit that will explode on generating a command
|
||||
Mock<RowEditBase> edit = new Mock<RowEditBase>();
|
||||
var edit = new Mock<RowEditBase>();
|
||||
edit.Setup(e => e.GetCommand(It.IsAny<DbConnection>())).Throws<Exception>();
|
||||
s.EditCache[0] = edit.Object;
|
||||
|
||||
@@ -1194,7 +1194,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, 0, 0);
|
||||
|
||||
// If: I generate a query for selecting rows without a limit
|
||||
EditInitializeFiltering eif = new EditInitializeFiltering
|
||||
var eif = new EditInitializeFiltering
|
||||
{
|
||||
LimitResults = null
|
||||
};
|
||||
@@ -1202,7 +1202,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
|
||||
// Then:
|
||||
// ... The query should look like a select statement
|
||||
Regex selectRegex = new Regex("SELECT (.+) FROM (.+)", RegexOptions.IgnoreCase);
|
||||
Regex selectRegex = GetSelectRegex();
|
||||
var match = selectRegex.Match(query);
|
||||
Assert.True(match.Success);
|
||||
|
||||
@@ -1223,7 +1223,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
|
||||
// If: I generate a query for selecting rows with a negative limit
|
||||
// Then: An exception should be thrown
|
||||
EditInitializeFiltering eif = new EditInitializeFiltering
|
||||
var eif = new EditInitializeFiltering
|
||||
{
|
||||
LimitResults = -1
|
||||
};
|
||||
@@ -1237,7 +1237,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
var data = new Common.TestDbColumnsWithTableMetadata(false, false, 0, 0);
|
||||
|
||||
// If: I generate a query for selecting rows without a limit
|
||||
EditInitializeFiltering eif = new EditInitializeFiltering
|
||||
var eif = new EditInitializeFiltering
|
||||
{
|
||||
LimitResults = limit
|
||||
};
|
||||
@@ -1245,7 +1245,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
|
||||
// Then:
|
||||
// ... The query should look like a select statement
|
||||
Regex selectRegex = new Regex(@"SELECT TOP (\d+) (.+) FROM (.+)", RegexOptions.IgnoreCase);
|
||||
var selectRegex = GetSelectTopRegex();
|
||||
var match = selectRegex.Match(query);
|
||||
Assert.True(match.Success);
|
||||
|
||||
@@ -1286,7 +1286,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
private static Mock<Func<Task>> DoNothingSuccessMock
|
||||
{
|
||||
get {
|
||||
Mock<Func<Task>> successHandler = new Mock<Func<Task>>();
|
||||
var successHandler = new Mock<Func<Task>>();
|
||||
successHandler.Setup(f => f()).Returns(Task.FromResult(0));
|
||||
return successHandler;
|
||||
}
|
||||
@@ -1296,7 +1296,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
{
|
||||
get
|
||||
{
|
||||
Mock<Func<Exception, Task>> failureHandler = new Mock<Func<Exception, Task>>();
|
||||
var failureHandler = new Mock<Func<Exception, Task>>();
|
||||
failureHandler.Setup(f => f(It.IsAny<Exception>())).Returns(Task.FromResult(0));
|
||||
return failureHandler;
|
||||
}
|
||||
@@ -1309,5 +1309,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
|
||||
EditTableMetadata etm = Common.GetCustomEditTableMetadata(rs.Columns.Cast<DbColumn>().ToArray());
|
||||
return await Common.GetCustomSession(q, etm);
|
||||
}
|
||||
|
||||
[GeneratedRegex("SELECT (.+) FROM (.+)", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex GetSelectRegex();
|
||||
|
||||
[GeneratedRegex("SELECT TOP (\\d+) (.+) FROM (.+)", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex GetSelectTopRegex();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
|
||||
await langService.HandleDidChangeLanguageFlavorNotification(new LanguageFlavorChangeParams
|
||||
{
|
||||
Uri = textDocument.TextDocument.Uri,
|
||||
Language = LanguageService.SQL_LANG.ToLower(),
|
||||
Language = LanguageService.SQL_LANG.ToLower(System.Globalization.CultureInfo.InvariantCulture),
|
||||
Flavor = "NotMSSQL"
|
||||
}, null);
|
||||
await langService.HandleSignatureHelpRequest(textDocument, signatureRequestContext.Object);
|
||||
|
||||
@@ -152,7 +152,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
|
||||
Assert.AreEqual(0, AutoCompleteHelper.EmptyCompletionList.Length);
|
||||
}
|
||||
|
||||
internal class TestScriptDocumentInfo : ScriptDocumentInfo
|
||||
internal sealed class TestScriptDocumentInfo : ScriptDocumentInfo
|
||||
{
|
||||
public TestScriptDocumentInfo(TextDocumentPosition textDocumentPosition, ScriptFile scriptFile, ScriptParseInfo scriptParseInfo,
|
||||
string tokenText = null)
|
||||
|
||||
@@ -95,7 +95,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
|
||||
inputStream.Flush();
|
||||
inputStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
Assert.ThrowsAsync<ArgumentException>(() => messageReader.ReadMessage(), "An exception should be thrown while reading");
|
||||
Assert.ThrowsAsync<ArgumentException>(messageReader.ReadMessage, "An exception should be thrown while reading");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
|
||||
inputStream.Flush();
|
||||
inputStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
Assert.ThrowsAsync<MessageParseException>(() => messageReader.ReadMessage(), "An exception should be thrown while reading") ;
|
||||
Assert.ThrowsAsync<MessageParseException>(messageReader.ReadMessage, "An exception should be thrown while reading") ;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
|
||||
inputStream.Flush();
|
||||
inputStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
Assert.ThrowsAsync<MessageParseException>(() => messageReader.ReadMessage(), "An exception should be thrown while reading");
|
||||
Assert.ThrowsAsync<MessageParseException>(messageReader.ReadMessage, "An exception should be thrown while reading");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,9 +153,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
|
||||
inputStream.Flush();
|
||||
inputStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
Assert.ThrowsAsync<JsonReaderException>(() => messageReader.ReadMessage(), "The first read should fail with an exception while deserializing");
|
||||
Assert.ThrowsAsync<JsonReaderException>(messageReader.ReadMessage, "The first read should fail with an exception while deserializing");
|
||||
|
||||
Assert.ThrowsAsync<MessageParseException>(() => messageReader.ReadMessage(), "The second read should fail with an exception while reading headers");
|
||||
Assert.ThrowsAsync<MessageParseException>(messageReader.ReadMessage, "The second read should fail with an exception while reading headers");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
|
||||
inputStream.Flush();
|
||||
inputStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
Assert.ThrowsAsync<ArgumentException>(() => messageReader.ReadMessage(), "An exception should be thrown while reading the first one");
|
||||
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;
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
|
||||
{
|
||||
#region Request Types
|
||||
|
||||
internal class TestRequest
|
||||
internal sealed class TestRequest
|
||||
{
|
||||
public Task ProcessMessage(MessageWriter messageWriter)
|
||||
{
|
||||
@@ -20,7 +20,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestRequestArguments
|
||||
internal sealed class TestRequestArguments
|
||||
{
|
||||
public string SomeString { get; set; }
|
||||
}
|
||||
@@ -29,11 +29,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
|
||||
|
||||
#region Response Types
|
||||
|
||||
internal class TestResponse
|
||||
internal sealed class TestResponse
|
||||
{
|
||||
}
|
||||
|
||||
internal class TestResponseBody
|
||||
internal sealed class TestResponseBody
|
||||
{
|
||||
public string SomeString { get; set; }
|
||||
}
|
||||
@@ -42,11 +42,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
|
||||
|
||||
#region Event Types
|
||||
|
||||
internal class TestEvent
|
||||
internal sealed class TestEvent
|
||||
{
|
||||
}
|
||||
|
||||
internal class TestEventBody
|
||||
internal sealed class TestEventBody
|
||||
{
|
||||
public string SomeString { get; set; }
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
<IsPackable>false</IsPackable>
|
||||
<ApplicationIcon />
|
||||
<StartupObject />
|
||||
<!-- TODO FIX THESE WARNINGS ASAP -->
|
||||
<NoWarn>$(NoWarn);SYSLIB1045;IDE0200;IDE0230;CA1311;CA1852;CA1854</NoWarn>
|
||||
<!-- False alerts, disabled due to issue: https://github.com/dotnet/roslyn/issues/65850 -->
|
||||
<NoWarn>$(NoWarn);CS8795</NoWarn>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.Text.Encoding.CodePages" />
|
||||
|
||||
@@ -15,7 +15,7 @@ using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer
|
||||
{
|
||||
class GroupBySchemaTests
|
||||
internal sealed class GroupBySchemaTests
|
||||
{
|
||||
Mock<DatabaseChildFactory> factory;
|
||||
Mock<TreeNode> node;
|
||||
|
||||
@@ -183,7 +183,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
|
||||
{
|
||||
await service.HandleExecuteRequest(qeParams, requestContext);
|
||||
await service.WorkTask;
|
||||
if (service.ActiveQueries.ContainsKey(qeParams.OwnerUri) && service.ActiveQueries[qeParams.OwnerUri].ExecutionTask != null)
|
||||
if (service.ActiveQueries.TryGetValue(qeParams.OwnerUri, out Query? query) && query.ExecutionTask != null)
|
||||
{
|
||||
await service.ActiveQueries[qeParams.OwnerUri].ExecutionTask;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
{
|
||||
public class SaveAsCsvFileStreamWriterTests
|
||||
public partial class SaveAsCsvFileStreamWriterTests
|
||||
{
|
||||
[Test]
|
||||
public void Constructor_NullStream()
|
||||
@@ -148,7 +148,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
string output = writer.EncodeCsvField(field);
|
||||
|
||||
// Then: It should wrap it in quotes
|
||||
Assert.True(Regex.IsMatch(output, "^\".*\"$", RegexOptions.Singleline));
|
||||
Assert.True(GetCsvRegexSingleLine().IsMatch(output));
|
||||
}
|
||||
|
||||
[TestCase("Something\rElse")] // Contains carriage return [TODO: Don't support this]
|
||||
@@ -165,7 +165,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
string output = writer.EncodeCsvField(field);
|
||||
|
||||
// Then: It should wrap it in quotes
|
||||
Assert.True(Regex.IsMatch(output, @"^\[.*\[$", RegexOptions.Singleline));
|
||||
Assert.True(GetCsvBracketRegex().IsMatch(output));
|
||||
}
|
||||
|
||||
[TestCase("\tSomething")] // Starts with tab
|
||||
@@ -186,7 +186,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
string output = writer.EncodeCsvField(field);
|
||||
|
||||
// Then: It should wrap it in quotes
|
||||
Assert.True(Regex.IsMatch(output, "^\".*\"$", RegexOptions.Singleline));
|
||||
Assert.True(GetCsvRegexSingleLine().IsMatch(output));
|
||||
}
|
||||
|
||||
[TestCase("Something")]
|
||||
@@ -201,7 +201,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
string output = writer.EncodeCsvField(field);
|
||||
|
||||
// Then: It should not wrap it in quotes
|
||||
Assert.False(Regex.IsMatch(output, "^\".*\"$"));
|
||||
Assert.False(GetCsvRegex().IsMatch(output));
|
||||
}
|
||||
|
||||
[TestCase(null, "Some\"thing", "\"Some\"\"thing\"")] // Default identifier
|
||||
@@ -277,7 +277,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
byte[] output = new byte[8192];
|
||||
|
||||
// If: I write a row
|
||||
SaveAsCsvFileStreamWriter writer = new SaveAsCsvFileStreamWriter(new MemoryStream(output), requestParams, columns);
|
||||
var writer = new SaveAsCsvFileStreamWriter(new MemoryStream(output), requestParams, columns);
|
||||
using (writer)
|
||||
{
|
||||
writer.WriteRow(data, columns);
|
||||
@@ -425,5 +425,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
Assert.IsEmpty(lines[lines.Length - 1]);
|
||||
return lines.Take(lines.Length - 1).ToArray();
|
||||
}
|
||||
|
||||
[GeneratedRegex("^\\[.*\\[$", RegexOptions.Singleline)]
|
||||
private static partial Regex GetCsvBracketRegex();
|
||||
|
||||
[GeneratedRegex("^\".*\"$")]
|
||||
private static partial Regex GetCsvRegex();
|
||||
|
||||
[GeneratedRegex("^\".*\"$", RegexOptions.Singleline)]
|
||||
private static partial Regex GetCsvRegexSingleLine();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
{
|
||||
public class SaveAsExcelFileStreamWriterHelperTests : IDisposable
|
||||
public partial class SaveAsExcelFileStreamWriterHelperTests : IDisposable
|
||||
{
|
||||
private Stream _stream;
|
||||
public SaveAsExcelFileStreamWriterHelperTests()
|
||||
@@ -25,7 +25,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
using (var helper = new SaveAsExcelFileStreamWriterHelper(_stream, true))
|
||||
using (var sheet = helper.AddSheet())
|
||||
{
|
||||
DbCellValue value = new DbCellValue();
|
||||
var value = new DbCellValue();
|
||||
sheet.AddRow();
|
||||
|
||||
value.IsNull = true;
|
||||
@@ -71,7 +71,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
sheet.AddCell(value);
|
||||
}
|
||||
}
|
||||
Regex contentRemoveLinebreakLeadingSpace = new Regex(@"\r?\n\s*");
|
||||
|
||||
[GeneratedRegex("\\r?\\n\\s*")]
|
||||
private static partial Regex GetContentRemoveLinebreakLeadingSpaceRegex();
|
||||
|
||||
private void ContentMatch(string fileName)
|
||||
{
|
||||
string referencePath = Path.Combine(RunEnvironmentInfo.GetTestDataLocation(),
|
||||
@@ -79,11 +82,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
"SaveAsExcelFileStreamWriterHelperTests",
|
||||
fileName);
|
||||
string referenceContent = File.ReadAllText(referencePath);
|
||||
referenceContent = contentRemoveLinebreakLeadingSpace.Replace(referenceContent, "");
|
||||
referenceContent = GetContentRemoveLinebreakLeadingSpaceRegex().Replace(referenceContent, "");
|
||||
|
||||
using (ZipArchive zip = new ZipArchive(_stream, ZipArchiveMode.Read, true))
|
||||
using (var zip = new ZipArchive(_stream, ZipArchiveMode.Read, true))
|
||||
{
|
||||
using (var reader = new StreamReader(zip.GetEntry(fileName).Open()))
|
||||
using (var reader = new StreamReader(zip?.GetEntry(fileName)?.Open()!))
|
||||
{
|
||||
string realContent = reader.ReadToEnd();
|
||||
Assert.AreEqual(referenceContent, realContent);
|
||||
@@ -130,7 +133,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
public class SaveAsExcelFileStreamWriterHelperReferenceManagerTests
|
||||
{
|
||||
private Mock<XmlWriter> _xmlWriterMock;
|
||||
private string LastWrittenReference { get; set; }
|
||||
private string? LastWrittenReference { get; set; }
|
||||
private int LastWrittenRow { get; set; }
|
||||
|
||||
public SaveAsExcelFileStreamWriterHelperReferenceManagerTests()
|
||||
@@ -145,7 +148,6 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
_xmlWriterMock.Setup(a => a.WriteEndAttribute());
|
||||
_xmlWriterMock.Setup(a => a.WriteValue(It.IsAny<int>()))
|
||||
.Callback<int>(row => LastWrittenRow = row);
|
||||
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -203,8 +205,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
manager.AssureColumnReference();
|
||||
manager.WriteAndIncreaseColumnReference();
|
||||
Assert.AreEqual("XFD1", LastWrittenReference);
|
||||
var ex = Assert.Throws<InvalidOperationException>(
|
||||
() => manager.AssureColumnReference());
|
||||
var ex = Assert.Throws<InvalidOperationException>(manager.AssureColumnReference);
|
||||
Assert.That(ex.Message, Does.Contain("max column number is 16384"));
|
||||
}
|
||||
[Test]
|
||||
@@ -232,8 +233,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
var xmlWriter = _xmlWriterMock.Object;
|
||||
var manager = new SaveAsExcelFileStreamWriterHelper.ReferenceManager(xmlWriter);
|
||||
|
||||
var ex = Assert.Throws<InvalidOperationException>(
|
||||
() => manager.AssureColumnReference());
|
||||
var ex = Assert.Throws<InvalidOperationException>(manager.AssureColumnReference);
|
||||
Assert.That(ex.Message, Does.Contain("AddRow must be called before AddCell"));
|
||||
}
|
||||
|
||||
|
||||
@@ -18,10 +18,11 @@ using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
{
|
||||
public class SaveAsMarkdownFileStreamWriterTests
|
||||
public partial class SaveAsMarkdownFileStreamWriterTests
|
||||
{
|
||||
// Regex: Matches '|' not preceded by a '\'
|
||||
private static readonly Regex UnescapedPipe = new Regex(@"(?<!\\)\|", RegexOptions.Compiled);
|
||||
[GeneratedRegex("(?<!\\\\)\\|", RegexOptions.Compiled)]
|
||||
private static partial Regex GetUnescapedPipeRegex();
|
||||
|
||||
[Test]
|
||||
public void Constructor_NullStream()
|
||||
@@ -362,7 +363,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
|
||||
private static void ValidateLine(string line, IEnumerable<string> expectedCells)
|
||||
{
|
||||
string[] cells = UnescapedPipe.Split(line);
|
||||
string[] cells = GetUnescapedPipeRegex().Split(line);
|
||||
string[] expectedCellsArray = expectedCells as string[] ?? expectedCells.ToArray();
|
||||
Assert.That(cells.Length - 2, Is.EqualTo(expectedCellsArray.Length), "Wrong number of cells in output");
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
{
|
||||
public class ServiceBufferReaderWriterTests
|
||||
public partial class ServiceBufferReaderWriterTests
|
||||
{
|
||||
[Test]
|
||||
public void ReaderStreamNull()
|
||||
@@ -49,7 +49,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
invalidStream.SetupGet(s => s.CanSeek).Returns(true);
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
{
|
||||
ServiceBufferFileStreamReader obj = new ServiceBufferFileStreamReader(invalidStream.Object, new QueryExecutionSettings());
|
||||
var obj = new ServiceBufferFileStreamReader(invalidStream.Object, new QueryExecutionSettings());
|
||||
obj.Dispose();
|
||||
});
|
||||
}
|
||||
@@ -64,7 +64,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
invalidStream.SetupGet(s => s.CanSeek).Returns(false);
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
{
|
||||
ServiceBufferFileStreamReader obj = new ServiceBufferFileStreamReader(invalidStream.Object, new QueryExecutionSettings());
|
||||
var obj = new ServiceBufferFileStreamReader(invalidStream.Object, new QueryExecutionSettings());
|
||||
obj.Dispose();
|
||||
});
|
||||
}
|
||||
@@ -95,7 +95,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
invalidStream.SetupGet(s => s.CanSeek).Returns(true);
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
{
|
||||
ServiceBufferFileStreamWriter obj = new ServiceBufferFileStreamWriter(invalidStream.Object, new QueryExecutionSettings());
|
||||
var obj = new ServiceBufferFileStreamWriter(invalidStream.Object, new QueryExecutionSettings());
|
||||
obj.Dispose();
|
||||
});
|
||||
}
|
||||
@@ -110,7 +110,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
invalidStream.SetupGet(s => s.CanSeek).Returns(false);
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
{
|
||||
ServiceBufferFileStreamWriter obj = new ServiceBufferFileStreamWriter(invalidStream.Object, new QueryExecutionSettings());
|
||||
var obj = new ServiceBufferFileStreamWriter(invalidStream.Object, new QueryExecutionSettings());
|
||||
obj.Dispose();
|
||||
});
|
||||
}
|
||||
@@ -128,7 +128,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
|
||||
// If:
|
||||
// ... I write a type T to the writer
|
||||
using (ServiceBufferFileStreamWriter writer = new ServiceBufferFileStreamWriter(new MemoryStream(storage), overrideSettings))
|
||||
using (var writer = new ServiceBufferFileStreamWriter(new MemoryStream(storage), overrideSettings))
|
||||
{
|
||||
int writtenBytes = writeFunc(writer, value);
|
||||
Assert.AreEqual(valueLength, writtenBytes);
|
||||
@@ -136,7 +136,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
|
||||
// ... And read the type T back
|
||||
FileStreamReadResult outValue;
|
||||
using (ServiceBufferFileStreamReader reader = new ServiceBufferFileStreamReader(new MemoryStream(storage), overrideSettings))
|
||||
using (var reader = new ServiceBufferFileStreamReader(new MemoryStream(storage), overrideSettings))
|
||||
{
|
||||
outValue = readFunc(reader, rowId);
|
||||
}
|
||||
@@ -312,7 +312,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
};
|
||||
|
||||
// Setup: Create a DATE column
|
||||
DbColumnWrapper col = new DbColumnWrapper(new TestDbColumn {DataTypeName = "DaTe"});
|
||||
var col = new DbColumnWrapper(new TestDbColumn {DataTypeName = "DaTe"});
|
||||
|
||||
foreach (DateTime value in testValues)
|
||||
{
|
||||
@@ -320,7 +320,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
(reader, rowId) => reader.ReadDateTime(0, rowId, col));
|
||||
|
||||
// Make sure the display value does not have a time string
|
||||
Assert.True(Regex.IsMatch(displayValue, @"^[\d]{4}-[\d]{2}-[\d]{2}$"));
|
||||
Assert.True(GetDateRegex().IsMatch(displayValue));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,7 +335,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
};
|
||||
|
||||
// Setup: Create a DATETIME column
|
||||
DbColumnWrapper col = new DbColumnWrapper(new TestDbColumn {DataTypeName = "DaTeTiMe"});
|
||||
var col = new DbColumnWrapper(new TestDbColumn {DataTypeName = "DaTeTiMe"});
|
||||
|
||||
foreach (DateTime value in testValues)
|
||||
{
|
||||
@@ -343,7 +343,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
(reader, rowId) => reader.ReadDateTime(0, rowId, col));
|
||||
|
||||
// Make sure the display value has a time string with 3 milliseconds
|
||||
Assert.True(Regex.IsMatch(displayValue, @"^[\d]{4}-[\d]{2}-[\d]{2} [\d]{2}:[\d]{2}:[\d]{2}\.[\d]{3}$"));
|
||||
Assert.True(GetDateTimeRegex().IsMatch(displayValue));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +358,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
};
|
||||
|
||||
// Setup: Create a DATETIME column
|
||||
DbColumnWrapper col = new DbColumnWrapper(new TestDbColumn
|
||||
var col = new DbColumnWrapper(new TestDbColumn
|
||||
{
|
||||
DataTypeName = "DaTeTiMe2",
|
||||
NumericScale = precision
|
||||
@@ -370,7 +370,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
(reader, rowId) => reader.ReadDateTime(0, rowId, col));
|
||||
|
||||
// Make sure the display value has a time string with variable number of milliseconds
|
||||
Assert.True(Regex.IsMatch(displayValue, @"^[\d]{4}-[\d]{2}-[\d]{2} [\d]{2}:[\d]{2}:[\d]{2}"));
|
||||
Assert.True(GetTimeRegex().IsMatch(displayValue));
|
||||
if (precision > 0)
|
||||
{
|
||||
Assert.True(Regex.IsMatch(displayValue, $@"\.[\d]{{{precision}}}$"));
|
||||
@@ -389,7 +389,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
};
|
||||
|
||||
// Setup: Create a DATETIME2 column
|
||||
DbColumnWrapper col = new DbColumnWrapper(new TestDbColumn {DataTypeName = "DaTeTiMe2", NumericScale = 0});
|
||||
var col = new DbColumnWrapper(new TestDbColumn {DataTypeName = "DaTeTiMe2", NumericScale = 0});
|
||||
|
||||
foreach (DateTime value in testValues)
|
||||
{
|
||||
@@ -397,7 +397,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
(reader, rowId) => reader.ReadDateTime(0, rowId, col));
|
||||
|
||||
// Make sure the display value has a time string with 0 milliseconds
|
||||
Assert.True(Regex.IsMatch(displayValue, @"^[\d]{4}-[\d]{2}-[\d]{2} [\d]{2}:[\d]{2}:[\d]{2}$"));
|
||||
Assert.True(GetTimeRegex().IsMatch(displayValue));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,7 +412,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
};
|
||||
|
||||
// Setup: Create a DATETIME2 column
|
||||
DbColumnWrapper col = new DbColumnWrapper(new TestDbColumn {DataTypeName = "DaTeTiMe2", NumericScale = 255});
|
||||
var col = new DbColumnWrapper(new TestDbColumn {DataTypeName = "DaTeTiMe2", NumericScale = 255});
|
||||
|
||||
foreach (DateTime value in testValues)
|
||||
{
|
||||
@@ -420,7 +420,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
(reader, rowId) => reader.ReadDateTime(0, rowId, col));
|
||||
|
||||
// Make sure the display value has a time string with 7 milliseconds
|
||||
Assert.True(Regex.IsMatch(displayValue, @"^[\d]{4}-[\d]{2}-[\d]{2} [\d]{2}:[\d]{2}:[\d]{2}\.[\d]{7}$"));
|
||||
Assert.True(GetDateTime2Regex().IsMatch(displayValue));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -436,7 +436,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
};
|
||||
|
||||
// Setup: Create a DATETIMEOFFSET column
|
||||
DbColumnWrapper col = new DbColumnWrapper(new TestDbColumn { DataTypeName = "datetimeoffset", NumericScale = 6 });
|
||||
var col = new DbColumnWrapper(new TestDbColumn { DataTypeName = "datetimeoffset", NumericScale = 6 });
|
||||
|
||||
foreach (DateTimeOffset value in testValues)
|
||||
{
|
||||
@@ -444,7 +444,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
(reader, rowId) => reader.ReadDateTimeOffset(0, rowId, col));
|
||||
|
||||
// Make sure the display value has a time string with 6 milliseconds and a time zone
|
||||
Assert.True(Regex.IsMatch(displayValue, @"^[\d]{4}-[\d]{2}-[\d]{2} [\d]{2}:[\d]{2}:[\d]{2}\.[\d]{6} [+-][01][\d]:[\d]{2}$"));
|
||||
Assert.True(GetDateTimeOffset6Regex().IsMatch(displayValue));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,7 +458,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
};
|
||||
|
||||
// Setup: Create a DATETIMEOFFSET column
|
||||
DbColumnWrapper col = new DbColumnWrapper(new TestDbColumn { DataTypeName = "datetimeoffset", NumericScale = 0 });
|
||||
var col = new DbColumnWrapper(new TestDbColumn { DataTypeName = "datetimeoffset", NumericScale = 0 });
|
||||
|
||||
foreach (DateTimeOffset value in testValues)
|
||||
{
|
||||
@@ -466,7 +466,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
(reader, rowId) => reader.ReadDateTimeOffset(0, rowId, col));
|
||||
|
||||
// Make sure the display value has a time string with no millisecond and a time zone
|
||||
Assert.True(Regex.IsMatch(displayValue, @"^[\d]{4}-[\d]{2}-[\d]{2} [\d]{2}:[\d]{2}:[\d]{2} [+-][01][\d]:[\d]{2}$"));
|
||||
Assert.True(GetDateTimeOffset0Regex().IsMatch(displayValue));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -490,11 +490,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
public void StringNullTest()
|
||||
{
|
||||
// Setup: Create a mock file stream
|
||||
using (MemoryStream stream = new MemoryStream(new byte[8192]))
|
||||
using (var stream = new MemoryStream(new byte[8192]))
|
||||
{
|
||||
// If:
|
||||
// ... I write null as a string to the writer
|
||||
using (ServiceBufferFileStreamWriter writer = new ServiceBufferFileStreamWriter(stream, new QueryExecutionSettings()))
|
||||
using (var writer = new ServiceBufferFileStreamWriter(stream, new QueryExecutionSettings()))
|
||||
{
|
||||
// Then:
|
||||
// ... I should get an argument null exception
|
||||
@@ -514,7 +514,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
{
|
||||
// Setup:
|
||||
// ... Generate the test value
|
||||
StringBuilder sb = new StringBuilder();
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
sb.Append(values[i%values.Length]);
|
||||
@@ -529,11 +529,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
public void BytesNullTest()
|
||||
{
|
||||
// Setup: Create a mock file stream wrapper
|
||||
using (MemoryStream stream = new MemoryStream(new byte[8192]))
|
||||
using (var stream = new MemoryStream(new byte[8192]))
|
||||
{
|
||||
// If:
|
||||
// ... I write null as a string to the writer
|
||||
using (ServiceBufferFileStreamWriter writer = new ServiceBufferFileStreamWriter(stream, new QueryExecutionSettings()))
|
||||
using (var writer = new ServiceBufferFileStreamWriter(stream, new QueryExecutionSettings()))
|
||||
{
|
||||
// Then:
|
||||
// ... I should get an argument null exception
|
||||
@@ -554,7 +554,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
{
|
||||
// Setup:
|
||||
// ... Generate the test value
|
||||
List<byte> sb = new List<byte>();
|
||||
var sb = new List<byte>();
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
sb.Add(values[i % values.Length]);
|
||||
@@ -602,5 +602,22 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
|
||||
(reader, rowId) => reader.ReadMoney(0, rowId));
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("^[\\d]{4}-[\\d]{2}-[\\d]{2}$")]
|
||||
private static partial Regex GetDateRegex();
|
||||
|
||||
[GeneratedRegex("^[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")]
|
||||
private static partial Regex GetTimeRegex();
|
||||
|
||||
[GeneratedRegex("^[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}\\.[\\d]{3}$")]
|
||||
private static partial Regex GetDateTimeRegex();
|
||||
|
||||
[GeneratedRegex("^[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}\\.[\\d]{7}$")]
|
||||
private static partial Regex GetDateTime2Regex();
|
||||
|
||||
[GeneratedRegex("^[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}\\.[\\d]{6} [+-][01][\\d]:[\\d]{2}$")]
|
||||
private static partial Regex GetDateTimeOffset6Regex();
|
||||
[GeneratedRegex("^[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2} [+-][01][\\d]:[\\d]{2}$")]
|
||||
private static partial Regex GetDateTimeOffset0Regex();
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
BatchCallbackHelper(batch,
|
||||
b => batchStartCalls++,
|
||||
b => batchEndCalls++,
|
||||
m => messages.Add(m),
|
||||
messages.Add,
|
||||
r => resultSetCalls++);
|
||||
await batch.Execute(GetConnection(Common.CreateTestConnectionInfo(null, false, false)), CancellationToken.None);
|
||||
|
||||
@@ -108,7 +108,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
BatchCallbackHelper(batch,
|
||||
b => batchStartCalls++,
|
||||
b => batchEndCalls++,
|
||||
m => messages.Add(m),
|
||||
messages.Add,
|
||||
r => resultSetCalls++);
|
||||
await batch.Execute(GetConnection(ci), CancellationToken.None);
|
||||
|
||||
@@ -144,7 +144,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
BatchCallbackHelper(batch,
|
||||
b => batchStartCalls++,
|
||||
b => batchEndCalls++,
|
||||
m => messages.Add(m),
|
||||
messages.Add,
|
||||
r => resultSetCalls++);
|
||||
await batch.Execute(GetConnection(ci), CancellationToken.None);
|
||||
|
||||
@@ -180,7 +180,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
BatchCallbackHelper(batch,
|
||||
b => batchStartCalls++,
|
||||
b => batchEndCalls++,
|
||||
m => messages.Add(m),
|
||||
messages.Add,
|
||||
r => resultSetCalls++);
|
||||
await batch.Execute(GetConnection(ci), CancellationToken.None);
|
||||
|
||||
@@ -213,7 +213,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
BatchCallbackHelper(batch,
|
||||
b => batchStartCalls++,
|
||||
b => batchEndCalls++,
|
||||
m => messages.Add(m),
|
||||
messages.Add,
|
||||
r => { throw new Exception("ResultSet callback was called when it should not have been."); });
|
||||
await batch.Execute(GetConnection(ci), CancellationToken.None);
|
||||
|
||||
@@ -245,7 +245,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
BatchCallbackHelper(batch,
|
||||
b => batchStartCalls++,
|
||||
b => batchEndCalls++,
|
||||
m => messages.Add(m),
|
||||
messages.Add,
|
||||
r => { throw new Exception("ResultSet callback was called when it should not have been."); });
|
||||
await batch.Execute(GetConnection(ci), CancellationToken.None);
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
/// <summary>
|
||||
/// Test DbColumn derived class
|
||||
/// </summary>
|
||||
private class TestColumn : DbColumn
|
||||
private sealed class TestColumn : DbColumn
|
||||
{
|
||||
public TestColumn(
|
||||
string dataTypeName = null,
|
||||
|
||||
@@ -122,7 +122,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
BatchCallbackHelper(query,
|
||||
b => { throw new Exception("Batch startup callback should not have been called."); },
|
||||
b => { throw new Exception("Batch completion callback was called"); },
|
||||
m => messages.Add(m));
|
||||
messages.Add);
|
||||
|
||||
// If:
|
||||
// ... I Then execute the query
|
||||
@@ -235,7 +235,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
BatchCallbackHelper(query,
|
||||
b => { throw new Exception("Batch start handler was called"); },
|
||||
b => { throw new Exception("Batch completed handler was called"); },
|
||||
m => messages.Add(m));
|
||||
messages.Add);
|
||||
|
||||
// .. I then execute the query
|
||||
query.Execute();
|
||||
@@ -271,7 +271,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
|
||||
BatchCallbackHelper(query,
|
||||
b => batchStartCallbacksReceived++,
|
||||
b => batchCompletionCallbacksReceived++,
|
||||
m => messages.Add(m));
|
||||
messages.Add);
|
||||
|
||||
// ... I then execute the query
|
||||
query.Execute();
|
||||
|
||||
@@ -50,7 +50,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
|
||||
|
||||
// Then:
|
||||
// ... It should throw an exception
|
||||
Assert.ThrowsAsync<Exception>(() => planResultSet.GetExecutionPlan());
|
||||
Assert.ThrowsAsync<Exception>(planResultSet.GetExecutionPlan);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -375,11 +375,11 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
|
||||
}
|
||||
else if (column.DataTypeName == "Int")
|
||||
{
|
||||
return Int64.Parse(value.DisplayValue.ToLower());
|
||||
return Int64.Parse(value.DisplayValue.ToLower(System.Globalization.CultureInfo.InvariantCulture));
|
||||
}
|
||||
else if (column.DataTypeName == "Bit")
|
||||
{
|
||||
return Boolean.Parse(value.DisplayValue.ToLower());
|
||||
return Boolean.Parse(value.DisplayValue.ToLower(System.Globalization.CultureInfo.InvariantCulture));
|
||||
}
|
||||
return value.DisplayValue;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
|
||||
var currentUserAccount = CreateAccount();
|
||||
currentUserAccount.Account.IsStale = true;
|
||||
IAzureAuthenticationManager accountManager = await CreateAccountManager(currentUserAccount, null);
|
||||
Assert.ThrowsAsync<ExpiredTokenException>(() => accountManager.GetSelectedSubscriptionsAsync());
|
||||
Assert.ThrowsAsync<ExpiredTokenException>(accountManager.GetSelectedSubscriptionsAsync);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -61,7 +61,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
|
||||
{
|
||||
var currentUserAccount = CreateAccount();
|
||||
IAzureAuthenticationManager accountManager = await CreateAccountManager(currentUserAccount, null, true);
|
||||
Assert.ThrowsAsync<ServiceFailedException>(() => accountManager.GetSelectedSubscriptionsAsync());
|
||||
Assert.ThrowsAsync<ServiceFailedException>(accountManager.GetSelectedSubscriptionsAsync);
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
|
||||
/// <summary>
|
||||
/// A container to create test data and mock classes to test azure services and providers
|
||||
/// </summary>
|
||||
internal class AzureTestContext
|
||||
internal sealed class AzureTestContext
|
||||
{
|
||||
public AzureTestContext(Dictionary<string, List<string>> subscriptionToDatabaseMap)
|
||||
{
|
||||
|
||||
@@ -406,7 +406,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider
|
||||
}
|
||||
}
|
||||
|
||||
internal class ServiceTestContext
|
||||
internal sealed class ServiceTestContext
|
||||
{
|
||||
private string _validServerName = "validServerName.database.windows.net";
|
||||
private string _startIpAddressValue = "1.2.3.6";
|
||||
|
||||
@@ -21,7 +21,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlProjects
|
||||
DatabaseVariable = "$(DatabaseVariable)"
|
||||
};
|
||||
|
||||
Assert.Throws<ArgumentException>(() => reference.Validate(), $"Validate() for a reference with both {nameof(reference.DatabaseLiteral)} and {nameof(reference.DatabaseVariable)} should have failed");
|
||||
Assert.Throws<ArgumentException>(reference.Validate, $"Validate() for a reference with both {nameof(reference.DatabaseLiteral)} and {nameof(reference.DatabaseVariable)} should have failed");
|
||||
|
||||
// Verify that Validate() passes any other time
|
||||
reference = new AddDacpacReferenceParams() { DatabaseLiteral = "DatabaseName" };
|
||||
|
||||
@@ -15,7 +15,7 @@ using NUnit.Framework;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
public class ToSqlScriptTests
|
||||
public partial class ToSqlScriptTests
|
||||
{
|
||||
#region FormatValue Tests
|
||||
|
||||
@@ -60,7 +60,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the integer type column
|
||||
DbColumn column = new FormatterTestDbColumn(dataType);
|
||||
DbCellValue cell = new DbCellValue { RawObject = (long)123 };
|
||||
var cell = new DbCellValue { RawObject = (long)123 };
|
||||
|
||||
// If: I attempt to format an integer type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
@@ -82,13 +82,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the decimal type column
|
||||
DbColumn column = new FormatterTestDbColumn(dataType, precision, scale);
|
||||
DbCellValue cell = new DbCellValue { RawObject = 123.45m };
|
||||
var cell = new DbCellValue { RawObject = 123.45m };
|
||||
|
||||
// If: I attempt to format a decimal type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
|
||||
// Then: It should match a something like CAST(123.45 AS MONEY)
|
||||
Regex castRegex = new Regex($@"CAST\([\d\.]+ AS {regex}", RegexOptions.IgnoreCase);
|
||||
var castRegex = new Regex($@"CAST\([\d\.]+ AS {regex}", RegexOptions.IgnoreCase);
|
||||
Assert.True(castRegex.IsMatch(output));
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the approx numeric type column
|
||||
DbColumn column = new FormatterTestDbColumn("FLOAT");
|
||||
DbCellValue cell = new DbCellValue { RawObject = 3.14159d };
|
||||
var cell = new DbCellValue { RawObject = 3.14159d };
|
||||
|
||||
// If: I attempt to format a approx numeric type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
@@ -111,7 +111,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the approx numeric type column
|
||||
DbColumn column = new FormatterTestDbColumn("REAL");
|
||||
DbCellValue cell = new DbCellValue { RawObject = (float)3.14159 };
|
||||
var cell = new DbCellValue { RawObject = (float)3.14159 };
|
||||
|
||||
// If: I attempt to format a approx numeric type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
@@ -129,15 +129,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the datetime type column
|
||||
DbColumn column = new FormatterTestDbColumn(dataType);
|
||||
DbCellValue cell = new DbCellValue { RawObject = DateTime.Now };
|
||||
var cell = new DbCellValue { RawObject = DateTime.Now };
|
||||
|
||||
// If: I attempt to format a datetime type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
|
||||
// Then: The output string should be able to be converted back into a datetime
|
||||
Regex dateTimeRegex = new Regex("N'(.*)'");
|
||||
DateTime outputDateTime;
|
||||
Assert.True(DateTime.TryParse(dateTimeRegex.Match(output).Groups[1].Value, out outputDateTime));
|
||||
Assert.True(DateTime.TryParse(GetDateTimeRegex().Match(output).Groups[1].Value, out outputDateTime));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -145,15 +144,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the datetime offset type column
|
||||
DbColumn column = new FormatterTestDbColumn("DATETIMEOFFSET");
|
||||
DbCellValue cell = new DbCellValue { RawObject = DateTimeOffset.Now };
|
||||
var cell = new DbCellValue { RawObject = DateTimeOffset.Now };
|
||||
|
||||
// If: I attempt to format a datetime offset type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
|
||||
// Then: The output string should be able to be converted back into a datetime offset
|
||||
Regex dateTimeRegex = new Regex("N'(.*)'");
|
||||
DateTimeOffset outputDateTime;
|
||||
Assert.True(DateTimeOffset.TryParse(dateTimeRegex.Match(output).Groups[1].Value, out outputDateTime));
|
||||
Assert.True(DateTimeOffset.TryParse(GetDateTimeRegex().Match(output).Groups[1].Value, out outputDateTime));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -161,15 +159,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the time type column
|
||||
DbColumn column = new FormatterTestDbColumn("TIME");
|
||||
DbCellValue cell = new DbCellValue { RawObject = TimeSpan.FromHours(12) };
|
||||
var cell = new DbCellValue { RawObject = TimeSpan.FromHours(12) };
|
||||
|
||||
// If: I attempt to format a time type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
|
||||
// Then: The output string should be able to be converted back into a timespan
|
||||
Regex dateTimeRegex = new Regex("N'(.*)'");
|
||||
TimeSpan outputDateTime;
|
||||
Assert.True(TimeSpan.TryParse(dateTimeRegex.Match(output).Groups[1].Value, out outputDateTime));
|
||||
Assert.True(TimeSpan.TryParse(GetDateTimeRegex().Match(output).Groups[1].Value, out outputDateTime));
|
||||
}
|
||||
|
||||
private static readonly object[] stringFormats =
|
||||
@@ -186,7 +183,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
// Setup: Build a column and cell for the string type column
|
||||
// NOTE: We're using VARCHAR because it's very general purpose.
|
||||
DbColumn column = new FormatterTestDbColumn("VARCHAR");
|
||||
DbCellValue cell = new DbCellValue { RawObject = input };
|
||||
var cell = new DbCellValue { RawObject = input };
|
||||
|
||||
// If: I attempt to format a string type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
@@ -208,7 +205,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the string type column
|
||||
DbColumn column = new FormatterTestDbColumn(datatype);
|
||||
DbCellValue cell = new DbCellValue { RawObject = "test string" };
|
||||
var cell = new DbCellValue { RawObject = "test string" };
|
||||
|
||||
// If: I attempt to format a string type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
@@ -222,17 +219,16 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the string type column
|
||||
DbColumn column = new FormatterTestDbColumn(datatype);
|
||||
DbCellValue cell = new DbCellValue
|
||||
var cell = new DbCellValue
|
||||
{
|
||||
RawObject = new byte[] { 0x42, 0x45, 0x4e, 0x49, 0x53, 0x43, 0x4f, 0x4f, 0x4c }
|
||||
RawObject = "BENISCOOL"u8.ToArray()
|
||||
};
|
||||
|
||||
// If: I attempt to format a string type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
|
||||
// Then: The output string should match the output string
|
||||
Regex regex = new Regex("0x[0-9A-F]+", RegexOptions.IgnoreCase);
|
||||
Assert.True(regex.IsMatch(output));
|
||||
Assert.True(GetOuputRegex().IsMatch(output));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -240,13 +236,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
{
|
||||
// Setup: Build a column and cell for the string type column
|
||||
DbColumn column = new FormatterTestDbColumn("UNIQUEIDENTIFIER");
|
||||
DbCellValue cell = new DbCellValue { RawObject = Guid.NewGuid() };
|
||||
var cell = new DbCellValue { RawObject = Guid.NewGuid() };
|
||||
|
||||
// If: I attempt to format a string type column
|
||||
string output = ToSqlScript.FormatValue(cell, column);
|
||||
|
||||
// Then: The output string should match the output string
|
||||
Regex regex = new Regex(@"N'[0-9A-F]{8}(-[0-9A-F]{4}){3}-[0-9A-F]{12}'", RegexOptions.IgnoreCase);
|
||||
var regex = GetGuidRegex();
|
||||
Assert.True(regex.IsMatch(output));
|
||||
}
|
||||
|
||||
@@ -391,7 +387,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
|
||||
#endregion
|
||||
|
||||
private class FormatterTestDbColumn : DbColumn
|
||||
private sealed class FormatterTestDbColumn : DbColumn
|
||||
{
|
||||
public FormatterTestDbColumn(string dataType, int? precision = null, int? scale = null, int? size = null)
|
||||
{
|
||||
@@ -401,5 +397,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.UtilityTests
|
||||
ColumnSize = size;
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("0x[0-9A-F]+", RegexOptions.IgnoreCase, "en-CA")]
|
||||
private static partial Regex GetOuputRegex();
|
||||
|
||||
[GeneratedRegex("N'[0-9A-F]{8}(-[0-9A-F]{4}){3}-[0-9A-F]{12}'", RegexOptions.IgnoreCase, "en-CA")]
|
||||
private static partial Regex GetGuidRegex();
|
||||
|
||||
[GeneratedRegex("N'(.*)'")]
|
||||
private static partial Regex GetDateTimeRegex();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user