Isolate Shared Test Code (#252)

The goal of this make sure that test code is correctly organized to ensure that test suites aren't dependent on each other.
* UnitTests get their own project now (renaming Microsoft.SqlTools.ServiceLayer.Test to Microsoft.SqlTools.ServiceLayer.UnitTests) which is about 90% of the changes to the files.
* IntegrationTests no longer depends on UnitTests, only Test.Common
* Any shared components from TestObjects that spins up a "live" connection has been moved to IntegrationTests Utility/LiveConnectionHelper.cs
* The dictionary-based mock file stream factory has been moved to Test.Common since it is used by UnitTests and IntegrationTests
    * Added a overload that doesn't take a dictionary for when we don't care about monitoring the storage (about 90% of the time)
* The RunIf* wrapper methods have been moved to Test.Common
* OwnerUri and StandardQuery constants have been moved to Test.Common Constants file

* Updating to latest SDK version available at https://www.microsoft.com/net/core#windowscmd

* Moving unit tests to unit test folder

* Changing namespaces to UnitTests

* Moving some constants and shared functionality into common project, making the UnitTests reference it

* Unit tests are working!

* Integration tests are working

* Updating automated test runs

* Fixing one last broken unit test

* Exposing internals for other projects

* Moving edit data tests to UnitTest project

* Applying refactor fixes to unit tests

* Fixing flaky test that wasn't awaiting completion
This commit is contained in:
Benjamin Russell
2017-03-02 13:00:31 -08:00
committed by GitHub
parent f9abe5f0bd
commit 1166778249
110 changed files with 700 additions and 764 deletions

View File

@@ -36,7 +36,7 @@ install:
script:
- dotnet build src/Microsoft.SqlTools.ServiceLayer
- dotnet test test/Microsoft.SqlTools.ServiceLayer.Test
- dotnet test test/Microsoft.SqlTools.ServiceLayer.UnitTests
env:
# Since we are building from root, current directory is the project path

View File

@@ -19,7 +19,7 @@ build_script:
- dotnet build src/Microsoft.SqlTools.ServiceLayer
test_script:
- dotnet test test/Microsoft.SqlTools.ServiceLayer.Test
- dotnet test test/Microsoft.SqlTools.ServiceLayer.UnitTests
after_test:
- cd test/CodeCoverage

View File

@@ -9,10 +9,15 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{32DC973E-9EEA-4694-B1C2-B031167AB945}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
.mention-bot = .mention-bot
.travis.yml = .travis.yml
appveyor.yml = appveyor.yml
BUILD.md = BUILD.md
global.json = global.json
license.txt = license.txt
nuget.config = nuget.config
README.md = README.md
RefreshDllsForTestRun.cmd = RefreshDllsForTestRun.cmd
EndProjectSection
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.SqlTools.Credentials", "src\Microsoft.SqlTools.Credentials\Microsoft.SqlTools.Credentials.xproj", "{1D61DC2B-DA66-441D-B9D0-887798F780F9}"
@@ -21,7 +26,7 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.SqlTools.Hosting"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.SqlTools.ServiceLayer", "src\Microsoft.SqlTools.ServiceLayer\Microsoft.SqlTools.ServiceLayer.xproj", "{0D61DC2B-DA66-441D-B9D0-F76C98F780F9}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.SqlTools.ServiceLayer.Test", "test\Microsoft.SqlTools.ServiceLayer.Test\Microsoft.SqlTools.ServiceLayer.Test.xproj", "{2D771D16-9D85-4053-9F79-E2034737DEEF}"
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.SqlTools.ServiceLayer.UnitTests", "test\Microsoft.SqlTools.ServiceLayer.UnitTests\Microsoft.SqlTools.ServiceLayer.UnitTests.xproj", "{2D771D16-9D85-4053-9F79-E2034737DEEF}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.SqlTools.ServiceLayer.TestDriver", "test\Microsoft.SqlTools.ServiceLayer.TestDriver\Microsoft.SqlTools.ServiceLayer.TestDriver.xproj", "{CC785604-6277-4878-8DA9-360C47158E96}"
EndProject

View File

@@ -42,7 +42,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyInformationalVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.Test")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.UnitTests")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.IntegrationTests")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.Test.Common")]

View File

@@ -41,6 +41,6 @@ using System.Runtime.InteropServices;
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.Test")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.UnitTests")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.IntegrationTests")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.Test.Common")]

View File

@@ -41,6 +41,6 @@ using System.Runtime.InteropServices;
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.Test")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.UnitTests")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.IntegrationTests")]
[assembly: InternalsVisibleTo("Microsoft.SqlTools.ServiceLayer.Test.Common")]

View File

@@ -18,7 +18,7 @@ REM rebuild the SqlToolsService project
dotnet build %WORKINGDIR%..\..\src\Microsoft.SqlTools.ServiceLayer\project.json %DOTNETCONFIG%
REM run the tests through OpenCover and generate a report
dotnet build %WORKINGDIR%..\..\test\Microsoft.SqlTools.ServiceLayer.Test\project.json %DOTNETCONFIG%
dotnet build %WORKINGDIR%..\..\test\Microsoft.SqlTools.ServiceLayer.UnitTests\project.json %DOTNETCONFIG%
dotnet build %WORKINGDIR%..\..\test\Microsoft.SqlTools.ServiceLayer.TestDriver\project.json %DOTNETCONFIG%
dotnet build %WORKINGDIR%..\..\test\Microsoft.SqlTools.ServiceLayer.Tests.Common\project.json %DOTNETCONFIG%
dotnet build %WORKINGDIR%..\..\test\Microsoft.SqlTools.ServiceLayer.IntegrationTests\project.json %DOTNETCONFIG%
@@ -35,12 +35,13 @@ dotnet.exe test %WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.TestDriver.Tests\
SET SERVICECODECOVERAGE=FALSE
"%WORKINGDIR%packages\OpenCover.4.6.519\tools\OpenCover.Console.exe" -mergeoutput -register:user -target:dotnet.exe -targetargs:"test %WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.TestDriver.Tests\project.json %DOTNETCONFIG%" -oldstyle -filter:"+[Microsoft.SqlTools.*]* -[xunit*]* -[Microsoft.SqlTools.ServiceLayer.Test*]*" -output:coverage.xml -searchdirs:%WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.TestDriver.Tests\bin\Debug\netcoreapp1.0
%CODECOVERAGETOOL% -mergeoutput -register:user -target:dotnet.exe -targetargs:"test %WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.TestDriver.Tests\project.json %DOTNETCONFIG%" -oldstyle -filter:"+[Microsoft.SqlTools.*]* -[xunit*]* -[Microsoft.SqlTools.ServiceLayer.Test*]*" -output:coverage.xml -searchdirs:%WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.TestDriver.Tests\bin\Debug\netcoreapp1.0
"%WORKINGDIR%packages\OpenCover.4.6.519\tools\OpenCover.Console.exe" -mergeoutput -register:user -target:dotnet.exe -targetargs:"test %WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.Test\project.json %DOTNETCONFIG%" -oldstyle -filter:"+[Microsoft.SqlTools.*]* -[xunit*]* -[Microsoft.SqlTools.ServiceLayer.Test*]*" -output:coverage.xml -searchdirs:%WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.Test\bin\Debug\netcoreapp1.0
%CODECOVERAGETOOL% -mergeoutput -register:user -target:dotnet.exe -targetargs:"test %WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.UnitTests\project.json %DOTNETCONFIG%" -oldstyle -filter:"+[Microsoft.SqlTools.*]* -[xunit*]* -[Microsoft.SqlTools.ServiceLayer.Test*]*" -output:coverage.xml -searchdirs:%WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.UnitTests\bin\Debug\netcoreapp1.0
"%WORKINGDIR%packages\OpenCover.4.6.519\tools\OpenCover.Console.exe" -mergeoutput -register:user -target:dotnet.exe -targetargs:"test %WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.IntegrationTests\project.json %DOTNETCONFIG%" -oldstyle -filter:"+[Microsoft.SqlTools.*]* -[xunit*]* -[Microsoft.SqlTools.ServiceLayer.Test*]*" -output:coverage.xml -searchdirs:%WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.IntegrationTests\bin\Debug\netcoreapp1.0
%CODECOVERAGETOOL% -mergeoutput -register:user -target:dotnet.exe -targetargs:"test %WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.IntegrationTests\project.json %DOTNETCONFIG%" -oldstyle -filter:"+[Microsoft.SqlTools.*]* -[xunit*]* -[Microsoft.SqlTools.ServiceLayer.Test*]*" -output:coverage.xml -searchdirs:%WORKINGDIR%..\Microsoft.SqlTools.ServiceLayer.IntegrationTests\bin\Debug\netcoreapp1.0
REM Generate the report
"%WORKINGDIR%packages\OpenCoverToCoberturaConverter.0.2.4.0\tools\OpenCoverToCoberturaConverter.exe" -input:coverage.xml -output:outputCobertura.xml -sources:%WORKINGDIR%..\..\src\Microsoft.SqlTools.ServiceLayer
"%WORKINGDIR%packages\ReportGenerator.2.4.5.0\tools\ReportGenerator.exe" "-reports:coverage.xml" "-targetdir:%WORKINGDIR%\reports"

View File

@@ -3,17 +3,14 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Collections.Generic;
using System.Data.Common;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
{
@@ -30,7 +27,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
service.OwnerToConnectionMap.Clear();
for (int i = 0; i < 2; i++)
{
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
ConnectionInfo connectionInfo = result.ConnectionInfo;
string uri = connectionInfo.OwnerUri;
@@ -39,8 +36,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.Equal(1, service.OwnerToConnectionMap.Count);
// If we run a query
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Query query = new Query(Common.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Constants.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory);
query.Execute();
query.ExecutionTask.Wait();
@@ -48,7 +45,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
Assert.Equal(2, connectionInfo.CountConnections);
// If we run another query
query = new Query(Common.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory);
query = new Query(Constants.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory);
query.Execute();
query.ExecutionTask.Wait();
@@ -69,7 +66,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
{
// If we make a connection to a live database
ConnectionService service = ConnectionService.Instance;
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
ConnectionInfo connectionInfo = result.ConnectionInfo;
ConnectionDetails details = connectionInfo.ConnectionDetails;
string uri = connectionInfo.OwnerUri;
@@ -78,8 +75,8 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
string changeDatabaseQuery = "use " + newDatabaseName;
// Then run any query to create a query DbConnection
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Query query = new Query(Common.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Constants.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory);
query.Execute();
query.ExecutionTask.Wait();

View File

@@ -9,16 +9,11 @@ using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Test.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
using Xunit;
using static Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.ReliableConnectionHelper;
using static Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.RetryPolicy;
@@ -451,7 +446,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
[Fact]
public void RetryPolicyFactoryConstructsPoliciesSuccessfully()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Assert.NotNull(RetryPolicyFactory.CreateColumnEncryptionTransferRetryPolicy());
Assert.NotNull(RetryPolicyFactory.CreateDatabaseCommandRetryPolicy());
@@ -539,7 +534,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
[Fact]
public void TestTryGetServerVersionInvalidConnectionString()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
ReliableConnectionHelper.ServerInfo info = null;
Assert.False(ReliableConnectionHelper.TryGetServerVersion("this is not a valid connstr", out info));
@@ -681,7 +676,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
[Fact]
public void ReliableConnectionHelperTest()
{
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
ConnectionInfo connInfo = result.ConnectionInfo;
DbConnection connection = connInfo.ConnectionTypeToConnectionMap[ConnectionType.Default];
@@ -726,7 +721,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Connection
[Fact]
public void InitReliableSqlConnectionTest()
{
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
ConnectionInfo connInfo = result.ConnectionInfo;
DbConnection dbConnection;
connInfo.TryGetConnection(ConnectionType.Default, out dbConnection);

View File

@@ -5,14 +5,11 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlServer.Management.SqlParser.Parser;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
@@ -22,11 +19,11 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
/// </summary>
public class LanguageServiceTests
{
private TestConnectionResult GetLiveAutoCompleteTestObjects()
private LiveConnectionHelper.TestConnectionResult GetLiveAutoCompleteTestObjects()
{
var textDocument = new TextDocumentPosition
{
TextDocument = new TextDocumentIdentifier { Uri = TestObjects.ScriptUri },
TextDocument = new TextDocumentIdentifier { Uri = Constants.OwnerUri },
Position = new Position
{
Line = 0,
@@ -34,7 +31,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
}
};
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
result.TextDocumentPosition = textDocument;
return result;
}
@@ -66,7 +63,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
[Fact]
public void PrepopulateCommonMetadata()
{
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
var connInfo = result.ConnectionInfo;
ScriptParseInfo scriptInfo = new ScriptParseInfo { IsConnected = true };
@@ -104,7 +101,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
{
// When we make a connection to a live database
Hosting.ServiceHost.SendEventIgnoreExceptions = true;
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
// And we place the cursor after a function that should prompt for signature help
string queryWithFunction = "EXEC sys.fn_isrolemember ";
@@ -142,7 +139,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.LanguageServer
[Fact]
public void OverwriteBindingContext()
{
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
// add a new connection context
var connectionKey = LanguageService.Instance.BindingQueue.AddConnectionContext(result.ConnectionInfo, overwrite: true);

View File

@@ -6,14 +6,13 @@ using System;
using System.Data.Common;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.SqlParser.Intellisense;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
using Moq;
using Xunit;
using ConnectionType = Microsoft.SqlTools.ServiceLayer.Connection.ConnectionType;
@@ -86,8 +85,8 @@ GO";
public void GetValidTableDefinitionTest()
{
// Get live connectionInfo and serverConnection
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "spt_monitor";
@@ -108,8 +107,8 @@ GO";
public void GetTableDefinitionInvalidObjectTest()
{
// Get live connectionInfo and serverConnection
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "test_invalid";
@@ -128,8 +127,8 @@ GO";
public void GetTableDefinitionWithSchemaTest()
{
// Get live connectionInfo and serverConnection
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "spt_monitor";
@@ -147,10 +146,10 @@ GO";
/// Test GetDefinition with an unsupported type(schema - dbo). Expect a error result.
/// </summary>
[Fact]
public async Task GetUnsupportedDefinitionErrorTest()
public void GetUnsupportedDefinitionErrorTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "objects";
@@ -168,8 +167,8 @@ GO";
[Fact]
public void GetDefinitionWithNoResultsFoundError()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "from";
@@ -226,7 +225,7 @@ GO";
Character = 20
}
};
TestConnectionResult connectionResult = TestObjects.InitLiveConnectionInfo();
LiveConnectionHelper.TestConnectionResult connectionResult = LiveConnectionHelper.InitLiveConnectionInfo();
ScriptFile scriptFile = connectionResult.ScriptFile;
ConnectionInfo connInfo = connectionResult.ConnectionInfo;
scriptFile.Contents = "select * from dbo.func ()";
@@ -250,8 +249,8 @@ GO";
[Fact]
public void GetValidViewDefinitionTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "objects";
@@ -270,8 +269,8 @@ GO";
public void GetViewDefinitionInvalidObjectTest()
{
// Get live connectionInfo and serverConnection
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "objects";
@@ -289,8 +288,8 @@ GO";
public void GetStoredProcedureDefinitionTest()
{
// Get live connectionInfo and serverConnection
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "sp_MSrepl_startup";
@@ -310,8 +309,8 @@ GO";
public void GetStoredProcedureDefinitionFailureTest()
{
// Get live connectionInfo and serverConnection
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "SP2";
@@ -329,8 +328,8 @@ GO";
public void GetStoredProcedureDefinitionWithoutSchemaTest()
{
// Get live connectionInfo and serverConnection
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "sp_MSrepl_startup";
@@ -369,8 +368,8 @@ GO";
private void ValidatePeekTest(string databaseName, string objectName, string objectType, string schemaName, bool shouldReturnValidResult)
{
// Get live connectionInfo and serverConnection
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition(databaseName);
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(databaseName);
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
@@ -571,8 +570,8 @@ GO";
[Fact]
public void GetDefinitionUsingDeclarationTypeWithValidObjectTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "objects";
@@ -593,8 +592,8 @@ GO";
[Fact]
public void GetDefinitionUsingDeclarationTypeWithNonexistentObjectTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "doesNotExist";
@@ -612,8 +611,8 @@ GO";
[Fact]
public void GetDefinitionUsingQuickInfoTextWithValidObjectTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "objects";
@@ -635,8 +634,8 @@ GO";
[Fact]
public void GetDefinitionUsingQuickInfoTextWithNonexistentObjectTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
PeekDefinition peekDefinition = new PeekDefinition(serverConnection, connInfo);
string objectName = "doesNotExist";
@@ -656,8 +655,8 @@ GO";
[Fact]
public void GetDatabaseWithNoQueryConnectionTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
DbConnection connection;
//Check if query connection is present
Assert.False(connInfo.TryGetConnection(ConnectionType.Query, out connection));
@@ -675,8 +674,8 @@ GO";
[Fact]
public void GetDatabaseWithQueryConnectionTest()
{
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = TestObjects.InitLiveServerConnectionForDefinition(connInfo);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition();
ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);
//Mock a query connection object
var mockQueryConnection = new Mock<DbConnection> { CallBase = true };
mockQueryConnection.SetupGet(x => x.Database).Returns("testdb");

View File

@@ -5,11 +5,9 @@
using System;
using System.Data.Common;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataStorage
@@ -18,7 +16,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution.DataSt
{
private StorageDataReader GetTestStorageDataReader(string query)
{
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
DbConnection connection;
result.ConnectionInfo.TryGetConnection(ConnectionType.Default, out connection);

View File

@@ -1,15 +1,12 @@
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
@@ -22,9 +19,9 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
const string refactorText = "ROLLBACK TRANSACTION";
// Given a connection to a live database
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
ConnectionInfo connInfo = result.ConnectionInfo;
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
// If I run a "ROLLBACK TRANSACTION" query
Query query = new Query(refactorText, connInfo, new QueryExecutionSettings(), fileStreamFactory);
@@ -42,9 +39,9 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
const string rollbackText = "ROLLBACK TRANSACTION";
// Given a connection to a live database
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
ConnectionInfo connInfo = result.ConnectionInfo;
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
// If I run a "BEGIN TRANSACTION" query
CreateAndExecuteQuery(beginText, connInfo, fileStreamFactory);
@@ -61,9 +58,9 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
const string insertTempText = "INSERT INTO #someTempTable VALUES(1)";
// Given a connection to a live database
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
ConnectionInfo connInfo = result.ConnectionInfo;
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(new Dictionary<string, byte[]>());
// If I run a query creating a temp table
CreateAndExecuteQuery(createTempText, connInfo, fileStreamFactory);
@@ -81,12 +78,12 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.QueryExecution
const string useQuery = "USE {0}";
// Given a connection to a live database
var result = TestObjects.InitLiveConnectionInfo();
var result = LiveConnectionHelper.InitLiveConnectionInfo();
ConnectionInfo connInfo = result.ConnectionInfo;
DbConnection connection;
connInfo.TryGetConnection(ConnectionType.Default, out connection);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(new Dictionary<string, byte[]>());
// If I use master, the current database should be master
CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory);

View File

@@ -10,8 +10,8 @@ using System.Data.SqlClient;
using System.Threading;
using Microsoft.SqlTools.ServiceLayer.BatchParser.ExecutionEngineCode;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.Test.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.TSQLExecutionEngine
@@ -46,7 +46,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.TSQLExecutionEngine
private SqlConnection SetUpConnection(string name)
{
SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, name);
ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfoForDefinition(testDb.DatabaseName);
ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(testDb.DatabaseName);
string connectionString = ConnectionService.BuildConnectionString(connInfo.ConnectionDetails);
SqlConnection resultConnection = new SqlConnection(connectionString);
resultConnection.Open();

View File

@@ -0,0 +1,106 @@
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Reflection;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility
{
public class LiveConnectionHelper
{
public static string GetTestSqlFile()
{
string filePath = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"sqltest.sql");
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.WriteAllText(filePath, "SELECT * FROM sys.objects\n");
return filePath;
}
public static TestConnectionResult InitLiveConnectionInfo()
{
string sqlFilePath = GetTestSqlFile();
ScriptFile scriptFile = TestServiceProvider.Instance.WorkspaceService.Workspace.GetFile(sqlFilePath);
ConnectParams connectParams = TestServiceProvider.Instance.ConnectionProfileService.GetConnectionParameters(TestServerType.OnPrem);
string ownerUri = scriptFile.ClientFilePath;
var connectionService = GetLiveTestConnectionService();
var connectionResult =
connectionService
.Connect(new ConnectParams
{
OwnerUri = ownerUri,
Connection = connectParams.Connection
});
connectionResult.Wait();
ConnectionInfo connInfo = null;
connectionService.TryFindConnection(ownerUri, out connInfo);
return new TestConnectionResult() { ConnectionInfo = connInfo, ScriptFile = scriptFile };
}
public static ConnectionInfo InitLiveConnectionInfoForDefinition(string databaseName = null)
{
ConnectParams connectParams = TestServiceProvider.Instance.ConnectionProfileService.GetConnectionParameters(TestServerType.OnPrem, databaseName);
const string ScriptUriTemplate = "file://some/{0}.sql";
string ownerUri = string.Format(CultureInfo.InvariantCulture, ScriptUriTemplate, string.IsNullOrEmpty(databaseName) ? "file" : databaseName);
var connectionService = GetLiveTestConnectionService();
var connectionResult =
connectionService
.Connect(new ConnectParams
{
OwnerUri = ownerUri,
Connection = connectParams.Connection
});
connectionResult.Wait();
ConnectionInfo connInfo = null;
connectionService.TryFindConnection(ownerUri, out connInfo);
Assert.NotNull(connInfo);
return connInfo;
}
public static ServerConnection InitLiveServerConnectionForDefinition(ConnectionInfo connInfo)
{
SqlConnection sqlConn = new SqlConnection(ConnectionService.BuildConnectionString(connInfo.ConnectionDetails));
return new ServerConnection(sqlConn);
}
/// <summary>
/// Creates a test sql connection factory instance
/// </summary>
public static ISqlConnectionFactory GetLiveTestSqlConnectionFactory()
{
// connect to a real server instance
return ConnectionService.Instance.ConnectionFactory;
}
public static ConnectionService GetLiveTestConnectionService()
{
// connect to a real server instance
return ConnectionService.Instance;
}
public class TestConnectionResult
{
public ConnectionInfo ConnectionInfo { get; set; }
public ScriptFile ScriptFile { get; set; }
public TextDocumentPosition TextDocumentPosition { get; set; }
}
}
}

View File

@@ -33,7 +33,7 @@
"target": "project"
},
"Moq": "4.6.36-alpha",
"Microsoft.SqlTools.ServiceLayer.Test": "1.0.0-*"
"Microsoft.SqlTools.ServiceLayer.Test.Common": "1.0.0-*"
},
"testRunner": "xunit",
"frameworks": {

View File

@@ -30,5 +30,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
public const string BVTLocalRoot = "BVT_LOCALROOT";
public const string DBIMode = "DBI_MODE";
public const string OwnerUri = "testFile";
public const string StandardQuery = "SELECT * FROM sys.objects";
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Moq;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{
public class MemoryFileSystem
{
public static IFileStreamFactory GetFileStreamFactory()
{
return GetFileStreamFactory(new Dictionary<string, byte[]>());
}
public static IFileStreamFactory GetFileStreamFactory(Dictionary<string, byte[]> storage)
{
Mock<IFileStreamFactory> mock = new Mock<IFileStreamFactory>();
mock.Setup(fsf => fsf.CreateFile())
.Returns(() =>
{
string fileName = Guid.NewGuid().ToString();
storage.Add(fileName, new byte[8192]);
return fileName;
});
mock.Setup(fsf => fsf.GetReader(It.IsAny<string>()))
.Returns<string>(output => new ServiceBufferFileStreamReader(new MemoryStream(storage[output]), new QueryExecutionSettings()));
mock.Setup(fsf => fsf.GetWriter(It.IsAny<string>()))
.Returns<string>(output => new ServiceBufferFileStreamWriter(new MemoryStream(storage[output]), new QueryExecutionSettings()));
return mock.Object;
}
}
}

View File

@@ -0,0 +1,37 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Runtime.InteropServices;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common
{
public class RunIfWrapper
{
public static void RunIfLinux(Action test)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
test();
}
}
public static void RunIfLinuxOrOSX(Action test)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
test();
}
}
public static void RunIfWindows(Action test)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
test();
}
}
}
}

View File

@@ -4,18 +4,13 @@
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Credentials;
using Microsoft.SqlTools.ServiceLayer.Hosting;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common
@@ -74,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
{
ConnectionInfo connInfo = InitLiveConnectionInfo(serverType, databaseName, queryTempFile.FilePath);
Query query = new Query(queryText, connInfo, new QueryExecutionSettings(), GetFileStreamFactory(new Dictionary<string, byte[]>()));
Query query = new Query(queryText, connInfo, new QueryExecutionSettings(), MemoryFileSystem.GetFileStreamFactory());
query.Execute();
query.ExecutionTask.Wait();
}
@@ -100,24 +95,6 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
return connInfo;
}
private static IFileStreamFactory GetFileStreamFactory(Dictionary<string, byte[]> storage)
{
Mock<IFileStreamFactory> mock = new Mock<IFileStreamFactory>();
mock.Setup(fsf => fsf.CreateFile())
.Returns(() =>
{
string fileName = Guid.NewGuid().ToString();
storage.Add(fileName, new byte[8192]);
return fileName;
});
mock.Setup(fsf => fsf.GetReader(It.IsAny<string>()))
.Returns<string>(output => new ServiceBufferFileStreamReader(new MemoryStream(storage[output]), new QueryExecutionSettings()));
mock.Setup(fsf => fsf.GetWriter(It.IsAny<string>()))
.Returns<string>(output => new ServiceBufferFileStreamWriter(new MemoryStream(storage[output]), new QueryExecutionSettings()));
return mock.Object;
}
private static bool hasInitServices = false;
private static void InitializeTestServices()

View File

@@ -1,55 +0,0 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//#define USE_LIVE_CONNECTION
using System.Data.Common;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
public class ExecuteTests
{
#if USE_LIVE_CONNECTION
[Fact]
public void QueryUdtShouldNotRetry()
{
// If:
// ... I create a query with a udt column in the result set
ConnectionInfo connectionInfo = TestObjects.GetTestConnectionInfo();
Query query = new Query(Common.UdtQuery, connectionInfo, new QueryExecutionSettings(), Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
// If:
// ... I then execute the query
DateTime startTime = DateTime.Now;
query.Execute();
query.ExecutionTask.Wait();
// Then:
// ... The query should complete within 2 seconds since retry logic should not kick in
Assert.True(DateTime.Now.Subtract(startTime) < TimeSpan.FromSeconds(2), "Query completed slower than expected, did retry logic execute?");
// Then:
// ... There should be an error on the batch
Assert.True(query.HasExecuted);
Assert.NotEmpty(query.BatchSummaries);
Assert.Equal(1, query.BatchSummaries.Length);
Assert.True(query.BatchSummaries[0].HasError);
Assert.NotEmpty(query.BatchSummaries[0].Messages);
}
#endif
}
}

View File

@@ -9,7 +9,7 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Completion
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion
{
public class AutoCompletionResultTest
{

View File

@@ -8,7 +8,7 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Completion
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Completion
{
public class ScriptDocumentInfoTest
{

View File

@@ -3,11 +3,10 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using Xunit;
using Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{
/// <summary>
/// Tests for Sever Information Caching Class

View File

@@ -14,13 +14,13 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Moq;
using Moq.Protected;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
{
/// <summary>
/// Tests for the ServiceHost Connection Service tests
@@ -249,8 +249,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
/// provided as a parameter.
/// </summary>
[Theory]
[InlineDataAttribute(null)]
[InlineDataAttribute("")]
[InlineData(null)]
[InlineData("")]
public async Task CanConnectWithEmptyDatabaseName(string databaseName)
{
// Connect
@@ -273,8 +273,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
/// provided as a parameter.
/// </summary>
[Theory]
[InlineDataAttribute("master")]
[InlineDataAttribute("nonMasterDb")]
[InlineData("master")]
[InlineData("nonMasterDb")]
public async Task ConnectToDefaultDatabaseRespondsWithActualDbName(string expectedDbName)
{
// Given connecting with empty database name will return the expected DB name
@@ -701,8 +701,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
/// Test that disconnecting validates parameters and doesn't succeed when they are invalid
/// </summary>
[Theory]
[InlineDataAttribute(null)]
[InlineDataAttribute("")]
[InlineData(null)]
[InlineData("")]
public async Task DisconnectValidatesParameters(string disconnectUri)
{
@@ -869,7 +869,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
[Fact]
public void TestThatLinuxAndOsxSqlExceptionHasNoErrorCode()
{
TestUtils.RunIfLinuxOrOSX(() =>
RunIfWrapper.RunIfLinuxOrOSX(() =>
{
try
{

View File

@@ -10,12 +10,10 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Credentials;
using Microsoft.SqlTools.ServiceLayer.Credentials.Contracts;
using Microsoft.SqlTools.ServiceLayer.Credentials.Linux;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Moq;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Connection
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
{
/// <summary>
/// Credential Service tests that should pass on all platforms, regardless of backing store.

View File

@@ -5,10 +5,10 @@
using Microsoft.SqlTools.ServiceLayer.Credentials;
using Microsoft.SqlTools.ServiceLayer.Credentials.Linux;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Linux
{
public class LinuxInteropTests
{
@@ -16,7 +16,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
public void GetEUidReturnsInt()
{
#if !WINDOWS_ONLY_BUILD
TestUtils.RunIfLinux(() =>
RunIfWrapper.RunIfLinux(() =>
{
Assert.NotNull(Interop.Sys.GetEUid());
});
@@ -27,7 +27,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
public void GetHomeDirectoryFromPwFindsHomeDir()
{
#if !WINDOWS_ONLY_BUILD
TestUtils.RunIfLinux(() =>
RunIfWrapper.RunIfLinux(() =>
{
string userDir = LinuxCredentialStore.GetHomeDirectoryFromPw();
Assert.StartsWith("/", userDir);

View File

@@ -5,17 +5,17 @@
using System;
using Microsoft.SqlTools.ServiceLayer.Credentials.Win32;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
{
public class CredentialSetTests
{
[Fact]
public void CredentialSetCreate()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Assert.NotNull(new CredentialSet());
});
@@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void CredentialSetCreateWithTarget()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Assert.NotNull(new CredentialSet("target"));
});
@@ -33,7 +33,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void CredentialSetShouldBeIDisposable()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Assert.True(new CredentialSet() is IDisposable, "CredentialSet needs to implement IDisposable Interface.");
});
@@ -42,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void CredentialSetLoad()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Win32Credential credential = new Win32Credential
{
@@ -67,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void CredentialSetLoadShouldReturnSelf()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
CredentialSet set = new CredentialSet();
Assert.IsType<CredentialSet>(set.Load());
@@ -79,7 +79,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void CredentialSetLoadWithTargetFilter()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Win32Credential credential = new Win32Credential
{

View File

@@ -5,17 +5,17 @@
using System;
using Microsoft.SqlTools.ServiceLayer.Credentials.Win32;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
{
public class Win32CredentialTests
{
[Fact]
public void Credential_Create_ShouldNotThrowNull()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Assert.NotNull(new Win32Credential());
});
@@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_Create_With_Username_ShouldNotThrowNull()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Assert.NotNull(new Win32Credential("username"));
});
@@ -33,7 +33,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_Create_With_Username_And_Password_ShouldNotThrowNull()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Assert.NotNull(new Win32Credential("username", "password"));
});
@@ -42,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_Create_With_Username_Password_Target_ShouldNotThrowNull()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Assert.NotNull(new Win32Credential("username", "password", "target"));
});
@@ -51,7 +51,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_ShouldBe_IDisposable()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Assert.True(new Win32Credential() is IDisposable, "Credential should implement IDisposable Interface.");
});
@@ -60,7 +60,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_Dispose_ShouldNotThrowException()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
new Win32Credential().Dispose();
});
@@ -69,7 +69,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_ShouldThrowObjectDisposedException()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Win32Credential disposed = new Win32Credential { Password = "password" };
disposed.Dispose();
@@ -80,7 +80,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_Save()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Win32Credential saved = new Win32Credential("username", "password", "target", CredentialType.Generic);
saved.PersistanceType = PersistanceType.LocalComputer;
@@ -91,7 +91,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_Delete()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
new Win32Credential("username", "password", "target").Save();
Assert.True(new Win32Credential("username", "password", "target").Delete());
@@ -101,7 +101,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_Delete_NullTerminator()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Win32Credential credential = new Win32Credential((string)null, (string)null, "\0", CredentialType.None);
credential.Description = (string)null;
@@ -112,7 +112,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_Load()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
Win32Credential setup = new Win32Credential("username", "password", "target", CredentialType.Generic);
setup.Save();
@@ -131,7 +131,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Credentials
[Fact]
public void Credential_Exists_Target_ShouldNotBeNull()
{
TestUtils.RunIfWindows(() =>
RunIfWrapper.RunIfWindows(() =>
{
new Win32Credential { Username = "username", Password = "password", Target = "target" }.Save();

View File

@@ -9,7 +9,7 @@ using System.Data.Common;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{
public class CellUpdateTests
{

View File

@@ -11,11 +11,12 @@ using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{
public class Common
{
@@ -75,7 +76,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
: new[] { new object[] { "1", "2", "3" } };
var testResultSet = new TestResultSet(columns, rows);
var reader = new TestDbDataReader(new[] { testResultSet });
var resultSet = new ResultSet(reader, 0, 0, QueryExecution.Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
var resultSet = new ResultSet(reader, 0, 0, MemoryFileSystem.GetFileStreamFactory());
resultSet.ReadResultToEnd(CancellationToken.None).Wait();
return resultSet;
}

View File

@@ -11,7 +11,7 @@ using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{
public class RowCreateTests
{

View File

@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{
public class RowDeleteTests
{

View File

@@ -13,10 +13,11 @@ using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.Contracts;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{
public class RowEditBaseTests
{
@@ -103,7 +104,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
object[][] rows = {row};
var testResultSet = new TestResultSet(columns, rows);
var testReader = new TestDbDataReader(new [] {testResultSet});
var resultSet = new ResultSet(testReader, 0,0, QueryExecution.Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
var resultSet = new ResultSet(testReader, 0,0, MemoryFileSystem.GetFileStreamFactory());
resultSet.ReadResultToEnd(CancellationToken.None).Wait();
return resultSet;
}

View File

@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{
public class RowUpdateTests
{

View File

@@ -10,11 +10,12 @@ using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.Contracts;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{
public class ServiceIntegrationTests
{
@@ -114,20 +115,20 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
// Setup: Create an edit data service with a session
var eds = new EditDataService(null, null, null);
eds.ActiveSessions[Common.OwnerUri] = GetDefaultSession();
eds.ActiveSessions[Constants.OwnerUri] = GetDefaultSession();
// If: I validly ask to delete a row
var efv = new EventFlowValidator<EditDeleteRowResult>()
.AddResultValidation(Assert.NotNull)
.Complete();
await eds.HandleDeleteRowRequest(new EditDeleteRowParams {OwnerUri = Common.OwnerUri, RowId = 0}, efv.Object);
await eds.HandleDeleteRowRequest(new EditDeleteRowParams {OwnerUri = Constants.OwnerUri, RowId = 0}, efv.Object);
// Then:
// ... It should be successful
efv.Validate();
// ... There should be a delete in the session
Session s = eds.ActiveSessions[Common.OwnerUri];
Session s = eds.ActiveSessions[Constants.OwnerUri];
Assert.True(s.EditCache.Any(e => e.Value is RowDelete));
}
@@ -136,20 +137,20 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
// Setup: Create an edit data service with a session
var eds = new EditDataService(null, null, null);
eds.ActiveSessions[Common.OwnerUri] = GetDefaultSession();
eds.ActiveSessions[Constants.OwnerUri] = GetDefaultSession();
// If: I ask to create a row from a non existant session
var efv = new EventFlowValidator<EditCreateRowResult>()
.AddResultValidation(ecrr => { Assert.True(ecrr.NewRowId > 0); })
.Complete();
await eds.HandleCreateRowRequest(new EditCreateRowParams { OwnerUri = Common.OwnerUri }, efv.Object);
await eds.HandleCreateRowRequest(new EditCreateRowParams { OwnerUri = Constants.OwnerUri }, efv.Object);
// Then:
// ... It should have been successful
efv.Validate();
// ... There should be a create in the session
Session s = eds.ActiveSessions[Common.OwnerUri];
Session s = eds.ActiveSessions[Constants.OwnerUri];
Assert.True(s.EditCache.Any(e => e.Value is RowCreate));
}
@@ -160,20 +161,20 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
var eds = new EditDataService(null, null, null);
var session = GetDefaultSession();
session.EditCache[0] = new Mock<RowEditBase>().Object;
eds.ActiveSessions[Common.OwnerUri] = session;
eds.ActiveSessions[Constants.OwnerUri] = session;
// If: I ask to revert a row that has a pending edit
var efv = new EventFlowValidator<EditRevertRowResult>()
.AddResultValidation(Assert.NotNull)
.Complete();
await eds.HandleRevertRowRequest(new EditRevertRowParams { OwnerUri = Common.OwnerUri, RowId = 0}, efv.Object);
await eds.HandleRevertRowRequest(new EditRevertRowParams { OwnerUri = Constants.OwnerUri, RowId = 0}, efv.Object);
// Then:
// ... It should have succeeded
efv.Validate();
// ... The edit cache should be empty again
Session s = eds.ActiveSessions[Common.OwnerUri];
Session s = eds.ActiveSessions[Constants.OwnerUri];
Assert.Empty(s.EditCache);
}
@@ -183,7 +184,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
// Setup: Create an edit data service with a session
var eds = new EditDataService(null, null, null);
var session = GetDefaultSession();
eds.ActiveSessions[Common.OwnerUri] = session;
eds.ActiveSessions[Constants.OwnerUri] = session;
var edit = new Mock<RowEditBase>();
edit.Setup(e => e.SetCell(It.IsAny<int>(), It.IsAny<string>())).Returns(new EditUpdateCellResult
{
@@ -204,7 +205,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
Assert.False(eucr.IsNull);
})
.Complete();
await eds.HandleUpdateCellRequest(new EditUpdateCellParams { OwnerUri = Common.OwnerUri, RowId = 0}, efv.Object);
await eds.HandleUpdateCellRequest(new EditUpdateCellParams { OwnerUri = Constants.OwnerUri, RowId = 0}, efv.Object);
// Then:
// ... It should be successful

View File

@@ -13,11 +13,11 @@ using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.EditData
{
public class SessionTests
{
@@ -87,8 +87,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
ConnectionInfo ci = QueryExecution.Common.CreateConnectedConnectionInfo(results, false);
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
var fsf = QueryExecution.Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Query query = new Query(QueryExecution.Common.StandardQuery, ci, new QueryExecutionSettings(), fsf);
var fsf = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fsf);
query.Execute();
query.ExecutionTask.Wait();

View File

@@ -11,7 +11,7 @@ using Microsoft.SqlTools.ServiceLayer.Extensibility;
using Microsoft.SqlTools.ServiceLayer.Formatter;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Extensibility
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility
{
public class ExtensionTests
{

View File

@@ -8,7 +8,7 @@ using System.Linq;
using Microsoft.SqlTools.ServiceLayer.Extensibility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Extensibility
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Extensibility
{
public class ServiceProviderTests
{

View File

@@ -6,7 +6,7 @@
using Microsoft.SqlTools.ServiceLayer.Formatter;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class BinaryQueryExpressionFormatterTests : FormatterUnitTestsBase
{

View File

@@ -7,7 +7,7 @@
using Microsoft.SqlTools.ServiceLayer.Formatter;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class CommonTableExpressionFormatterTests : FormatterUnitTestsBase

View File

@@ -6,7 +6,7 @@
using Microsoft.SqlTools.ServiceLayer.Formatter;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class CreateProcedureFormatterTests : FormatterUnitTestsBase

View File

@@ -6,7 +6,7 @@
using Microsoft.SqlTools.ServiceLayer.Formatter;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class CreateTableFormatterTests : FormatterUnitTestsBase

View File

@@ -7,7 +7,7 @@
using Microsoft.SqlTools.ServiceLayer.Formatter;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class CreateViewFormatterTests : FormatterUnitTestsBase

View File

@@ -9,7 +9,7 @@ using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class FormatterSettingsTests
{

View File

@@ -3,7 +3,6 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.IO;
using System.Reflection;
using Microsoft.SqlTools.ServiceLayer.Extensibility;
@@ -14,7 +13,7 @@ using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Moq;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class FormatterUnitTestsBase
{

View File

@@ -6,7 +6,7 @@
using Microsoft.SqlTools.ServiceLayer.Formatter;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class GeneralFormatterTests : FormatterUnitTestsBase
{

View File

@@ -7,7 +7,7 @@
using Microsoft.SqlTools.ServiceLayer.Formatter;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class InsertFormatterTests : FormatterUnitTestsBase

View File

@@ -6,7 +6,7 @@
using Microsoft.SqlTools.ServiceLayer.Formatter;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class SqlSelectStatementFormatterTests : FormatterUnitTestsBase

View File

@@ -11,12 +11,12 @@ using Microsoft.SqlTools.ServiceLayer.Formatter.Contracts;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Formatter
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Formatter
{
public class TSqlFormatterServiceTests : FormatterUnitTestsBase
{

View File

@@ -13,14 +13,14 @@ using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
using GlobalCommon = Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
{
/// <summary>
/// Tests for the language service autocomplete component
@@ -65,7 +65,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
// set up file for returning the query
scriptFile = new Mock<ScriptFile>();
scriptFile.SetupGet(file => file.Contents).Returns(QueryExecution.Common.StandardQuery);
scriptFile.SetupGet(file => file.Contents).Returns(GlobalCommon.Constants.StandardQuery);
scriptFile.SetupGet(file => file.ClientFilePath).Returns(this.testScriptUri);
// set up workspace mock

View File

@@ -14,7 +14,7 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
{
/// <summary>

View File

@@ -16,7 +16,7 @@ using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServer
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
{
public class CompletionServiceTest
{

View File

@@ -7,7 +7,7 @@ using System;
using System.Collections.Generic;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServer
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
{
public class InteractionMetricsTest
{

View File

@@ -3,15 +3,14 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServer
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
{
/// <summary>
/// Tests for the ServiceHost Language Service tests

View File

@@ -2,6 +2,7 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.IO;
@@ -18,14 +19,15 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.Test.Utility;
using Moq;
using GlobalCommon = Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
using Location = Microsoft.SqlTools.ServiceLayer.Workspace.Contracts.Location;
namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
{
/// <summary>
/// Tests for the language service peek definition/ go to definition feature
@@ -48,8 +50,6 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
private TextDocumentPosition textDocument;
private const string OwnerUri = "testFile1";
private void InitializeTestObjects()
{
// initial cursor position in the script file
@@ -68,7 +68,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
// set up file for returning the query
var fileMock = new Mock<ScriptFile>();
fileMock.SetupGet(file => file.Contents).Returns(QueryExecution.Common.StandardQuery);
fileMock.SetupGet(file => file.Contents).Returns(GlobalCommon.Constants.StandardQuery);
fileMock.SetupGet(file => file.ClientFilePath).Returns(this.testScriptUri);
// set up workspace mock

View File

@@ -9,7 +9,7 @@ using Microsoft.SqlTools.ServiceLayer.LanguageServices.Completion;
using Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServer
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.LanguageServer
{
public class SqlCompletionItemTests
{

View File

@@ -5,7 +5,7 @@
using System.Text;
namespace Microsoft.SqlTools.ServiceLayer.Test.Messaging
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
{
public class Common
{

View File

@@ -11,7 +11,7 @@ using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Contracts;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Messaging
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
{
public class MessageDispatcherTests
{

View File

@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Serializers;
using Newtonsoft.Json;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Messaging
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
{
public class MessageReaderTests
{

View File

@@ -12,7 +12,7 @@ using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Serializers;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Messaging
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
{
public class MessageWriterTests
{

View File

@@ -6,7 +6,7 @@
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
namespace Microsoft.SqlTools.ServiceLayer.Test.Messaging
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
{
#region Request Types

View File

@@ -7,7 +7,7 @@
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>2d771d16-9d85-4053-9f79-e2034737deef</ProjectGuid>
<RootNamespace>Microsoft.SqlTools.ServiceLayer.Test</RootNamespace>
<RootNamespace>Microsoft.SqlTools.ServiceLayer.UnitTests</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'==''">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>

View File

@@ -7,12 +7,13 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
{
public class CancelTests
{
@@ -21,17 +22,17 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I request a query (doesn't matter what kind) and execute it
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri };
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri };
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
queryService.ActiveQueries[Common.OwnerUri].HasExecuted = false; // Fake that it hasn't completed execution
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
queryService.ActiveQueries[Constants.OwnerUri].HasExecuted = false; // Fake that it hasn't completed execution
// ... And then I request to cancel the query
var cancelParams = new QueryCancelParams {OwnerUri = Common.OwnerUri};
var cancelParams = new QueryCancelParams {OwnerUri = Constants.OwnerUri};
var cancelRequest = new EventFlowValidator<QueryCancelResult>()
.AddResultValidation(r =>
{
@@ -50,16 +51,16 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I request a query (doesn't matter what kind) and wait for execution
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri};
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// ... And then I request to cancel the query
var cancelParams = new QueryCancelParams {OwnerUri = Common.OwnerUri};
var cancelParams = new QueryCancelParams {OwnerUri = Constants.OwnerUri};
var cancelRequest = new EventFlowValidator<QueryCancelResult>()
.AddResultValidation(r =>
{

View File

@@ -2,29 +2,27 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using HostingProtocol = Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq;
using Moq.Protected;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
{
public class Common
{
@@ -36,12 +34,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
public const int Ordinal = 100; // We'll pick something other than default(int)
public const string OwnerUri = "testFile";
public const int StandardColumns = 5;
public const string StandardQuery = "SELECT * FROM sys.objects";
public const int StandardRows = 5;
public const string UdtQuery = "SELECT hierarchyid::Parse('/')";
@@ -78,14 +72,16 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
public static Batch GetBasicExecutedBatch()
{
Batch batch = new Batch(StandardQuery, SubsectionDocument, 1, GetFileStreamFactory(new Dictionary<string, byte[]>()));
Batch batch = new Batch(Constants.StandardQuery, SubsectionDocument, 1,
MemoryFileSystem.GetFileStreamFactory());
batch.Execute(CreateTestConnection(StandardTestDataSet, false), CancellationToken.None).Wait();
return batch;
}
public static Batch GetExecutedBatchWithExecutionPlan()
{
Batch batch = new Batch(StandardQuery, SubsectionDocument, 1, GetFileStreamFactory(new Dictionary<string, byte[]>()));
Batch batch = new Batch(Constants.StandardQuery, SubsectionDocument, 1,
MemoryFileSystem.GetFileStreamFactory());
batch.Execute(CreateTestConnection(ExecutionPlanTestDataSet, false), CancellationToken.None).Wait();
return batch;
}
@@ -98,7 +94,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
// ConnectionInfo with the same URI as the query, so we will manually set it
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
Query query = new Query(StandardQuery, ci, new QueryExecutionSettings(), GetFileStreamFactory(new Dictionary<string, byte[]>()));
Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(),
MemoryFileSystem.GetFileStreamFactory());
query.Execute();
query.ExecutionTask.Wait();
return query;
@@ -112,7 +109,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
// ConnectionInfo with the same URI as the query, so we will manually set it
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
Query query = new Query(StandardQuery, ci, querySettings, GetFileStreamFactory(new Dictionary<string, byte[]>()));
Query query = new Query(Constants.StandardQuery, ci, querySettings,
MemoryFileSystem.GetFileStreamFactory());
query.Execute();
query.ExecutionTask.Wait();
return query;
@@ -124,7 +122,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
}
public static async Task AwaitExecution(QueryExecutionService service, ExecuteDocumentSelectionParams qeParams,
RequestContext<ExecuteRequestResult> requestContext)
HostingProtocol.RequestContext<ExecuteRequestResult> requestContext)
{
await service.HandleExecuteRequest(qeParams, requestContext);
if (service.ActiveQueries.ContainsKey(qeParams.OwnerUri) && service.ActiveQueries[qeParams.OwnerUri].ExecutionTask != null)
@@ -135,28 +133,6 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
#endregion
#region FileStreamWriteMocking
public static IFileStreamFactory GetFileStreamFactory(Dictionary<string, byte[]> storage)
{
Mock<IFileStreamFactory> mock = new Mock<IFileStreamFactory>();
mock.Setup(fsf => fsf.CreateFile())
.Returns(() =>
{
string fileName = Guid.NewGuid().ToString();
storage.Add(fileName, new byte[8192]);
return fileName;
});
mock.Setup(fsf => fsf.GetReader(It.IsAny<string>()))
.Returns<string>(output => new ServiceBufferFileStreamReader(new MemoryStream(storage[output]), new QueryExecutionSettings()));
mock.Setup(fsf => fsf.GetWriter(It.IsAny<string>()))
.Returns<string>(output => new ServiceBufferFileStreamWriter(new MemoryStream(storage[output]), new QueryExecutionSettings()));
return mock.Object;
}
#endregion
#region DbConnection Mocking
public static DbCommand CreateTestCommand(TestResultSet[] data, bool throwOnRead)
@@ -208,7 +184,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// Create a connection info and add the default connection to it
ISqlConnectionFactory factory = CreateMockFactory(data, throwOnRead);
ConnectionInfo ci = new ConnectionInfo(factory, OwnerUri, StandardConnectionDetails);
ConnectionInfo ci = new ConnectionInfo(factory, Constants.OwnerUri, StandardConnectionDetails);
ci.ConnectionTypeToConnectionMap[ConnectionType.Default] = factory.CreateSqlConnection(null);
return ci;
}
@@ -222,12 +198,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
ConnectParams connectParams = new ConnectParams
{
Connection = StandardConnectionDetails,
OwnerUri = OwnerUri,
OwnerUri = Constants.OwnerUri,
Type = type
};
connectionService.Connect(connectParams).Wait();
return connectionService.OwnerToConnectionMap[OwnerUri];
return connectionService.OwnerToConnectionMap[connectParams.OwnerUri];
}
#endregion
@@ -250,7 +226,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
.OutCallback((string owner, out ConnectionInfo connInfo) => connInfo = isConnected ? ci : null)
.Returns(isConnected);
return new QueryExecutionService(connectionService.Object, workspaceService) { BufferFileStreamFactory = GetFileStreamFactory(storage) };
return new QueryExecutionService(connectionService.Object, workspaceService) { BufferFileStreamFactory = MemoryFileSystem.GetFileStreamFactory(storage) };
}
public static QueryExecutionService GetPrimedExecutionService(TestResultSet[] data, bool isConnected, bool throwOnRead, WorkspaceService<SqlToolsSettings> workspaceService)

View File

@@ -10,10 +10,10 @@ using System.Text;
using System.Text.RegularExpressions;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.DataStorage
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
{
public class SaveAsCsvFileStreamWriterTests
{

View File

@@ -8,11 +8,11 @@ using System.IO;
using System.Text;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Newtonsoft.Json;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.DataStorage
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
{
public class SaveAsJsonFileStreamWriterTests
{

View File

@@ -13,11 +13,11 @@ using System.Text.RegularExpressions;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.DataStorage
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.DataStorage
{
public class ReaderWriterPairTest
{

View File

@@ -9,12 +9,13 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
{
public class DisposeTests
{
@@ -38,15 +39,15 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I request a query (doesn't matter what kind)
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Common.OwnerUri};
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Constants.OwnerUri};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// ... And then I dispose of the query
var disposeParams = new QueryDisposeParams {OwnerUri = Common.OwnerUri};
var disposeParams = new QueryDisposeParams {OwnerUri = Constants.OwnerUri};
var disposeRequest = new EventFlowValidator<QueryDisposeResult>()
.AddStandardQueryDisposeValidator()
.Complete();
@@ -65,7 +66,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
// ... I attempt to dispose a query that doesn't exist
var workspaceService = new Mock<WorkspaceService<SqlToolsSettings>>();
var queryService = Common.GetPrimedExecutionService(null, false, false, workspaceService.Object);
var disposeParams = new QueryDisposeParams {OwnerUri = Common.OwnerUri};
var disposeParams = new QueryDisposeParams {OwnerUri = Constants.OwnerUri};
var disposeRequest = new EventFlowValidator<QueryDisposeResult>()
.AddErrorValidation<string>(Assert.NotEmpty)
@@ -81,15 +82,15 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// Setup:
// ... We need a query service
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
// If:
// ... I execute some bogus query
var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri };
var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri };
var requestContext = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(queryParams, requestContext.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// ... And it sticks around as an active query
Assert.Equal(1, queryService.ActiveQueries.Count);

View File

@@ -13,9 +13,10 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
{
public class BatchTests
{
@@ -23,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
public void BatchCreationTest()
{
// If I create a new batch...
Batch batch = new Batch(Common.StandardQuery, Common.SubsectionDocument, Common.Ordinal, Common.GetFileStreamFactory(null));
Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory());
// Then:
// ... The text of the batch should be stored
@@ -63,8 +64,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
List<ResultMessage> messages = new List<ResultMessage>();
// If I execute a query that should get no result sets
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Batch batch = new Batch(Common.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
BatchCallbackHelper(batch,
b => batchStartCalls++,
b => batchEndCalls++,
@@ -99,8 +100,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
ConnectionInfo ci = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false);
// If I execute a query that should get one result set
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Batch batch = new Batch(Common.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
BatchCallbackHelper(batch,
b => batchStartCalls++,
b => batchEndCalls++,
@@ -135,8 +136,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
ConnectionInfo ci = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false);
// If I execute a query that should get two result sets
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Batch batch = new Batch(Common.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
BatchCallbackHelper(batch,
b => batchStartCalls++,
b => batchEndCalls++,
@@ -167,8 +168,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If I execute a batch that is invalid
var ci = Common.CreateTestConnectionInfo(null, true);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Batch batch = new Batch(Common.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
BatchCallbackHelper(batch,
b => batchStartCalls++,
b => batchEndCalls++,
@@ -202,8 +203,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
ConnectionInfo ci = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false);
// If I execute a batch
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Batch batch = new Batch(Common.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
await batch.Execute(GetConnection(ci), CancellationToken.None);
// Then:
@@ -235,7 +236,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// ... I create a batch that has an empty query
// Then:
// ... It should throw an exception
Assert.Throws<ArgumentException>(() => new Batch(query, Common.SubsectionDocument, Common.Ordinal, Common.GetFileStreamFactory(null)));
Assert.Throws<ArgumentException>(() => new Batch(query, Common.SubsectionDocument, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory()));
}
[Fact]
@@ -255,7 +256,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// ... I create a batch has has an ordinal less than 0
// Then:
// ... It should throw an exception
Assert.Throws<ArgumentOutOfRangeException>(() => new Batch("stuff", Common.SubsectionDocument, -1, Common.GetFileStreamFactory(null)));
Assert.Throws<ArgumentOutOfRangeException>(() => new Batch("stuff", Common.SubsectionDocument, -1, MemoryFileSystem.GetFileStreamFactory()));
}
[Fact]
@@ -263,7 +264,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
// If:
// ... I call the StatementCompletedHandler
Batch batch = new Batch(Common.StandardQuery, Common.SubsectionDocument, Common.Ordinal, Common.GetFileStreamFactory(null));
Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory());
int messageCalls = 0;
batch.BatchMessageSent += args =>
{

View File

@@ -7,7 +7,7 @@ using System.Data.Common;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
{
/// <summary>
/// DbColumnWrapper tests

View File

@@ -11,9 +11,10 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
{
public class QueryTests
{
@@ -24,8 +25,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a query
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Query query = new Query(Common.StandardQuery, ci, new QueryExecutionSettings(), fileStreamFactory);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fileStreamFactory);
// Then:
// ... I should get back two batches to execute that haven't been executed
@@ -42,7 +43,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// Then:
// ... It should throw an exception
Assert.Throws<ArgumentException>(() =>
new Query(null, Common.CreateTestConnectionInfo(null, false), new QueryExecutionSettings(), Common.GetFileStreamFactory(null)));
new Query(null, Common.CreateTestConnectionInfo(null, false), new QueryExecutionSettings(), MemoryFileSystem.GetFileStreamFactory()));
}
[Fact]
@@ -52,7 +53,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// ... I create a query that has a null connection info
// Then:
// ... It should throw an exception
Assert.Throws<ArgumentNullException>(() => new Query("Some Query", null, new QueryExecutionSettings(), Common.GetFileStreamFactory(null)));
Assert.Throws<ArgumentNullException>(() => new Query("Some Query", null, new QueryExecutionSettings(), MemoryFileSystem.GetFileStreamFactory()));
}
[Fact]
@@ -63,7 +64,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// Then:
// ... It should throw an exception
Assert.Throws<ArgumentNullException>(() =>
new Query("Some query", Common.CreateTestConnectionInfo(null, false), null, Common.GetFileStreamFactory(null)));
new Query("Some query", Common.CreateTestConnectionInfo(null, false), null, MemoryFileSystem.GetFileStreamFactory()));
}
[Fact]
@@ -89,8 +90,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a query from a single batch (without separator)
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Query query = new Query(Common.StandardQuery, ci, new QueryExecutionSettings(), fileStreamFactory);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fileStreamFactory);
BatchCallbackHelper(query,
b => batchStartCallbacksReceived++,
b => batchCompleteCallbacksReceived++,
@@ -117,7 +118,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
}
[Fact]
public void QueryExecuteSingleNoOpBatch()
public async Task QueryExecuteSingleNoOpBatch()
{
// Setup: Keep track of all the messages received
List<ResultMessage> messages = new List<ResultMessage>();
@@ -125,7 +126,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a query from a single batch that does nothing
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Common.NoOpQuery, ci, new QueryExecutionSettings(), fileStreamFactory);
BatchCallbackHelper(query,
b => { throw new Exception("Batch startup callback should not have been called."); },
@@ -135,6 +136,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I Then execute the query
query.Execute();
await query.ExecutionTask;
// Then:
// ... There should be no batches
@@ -160,8 +162,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// ... I create a query from two batches (with separator)
ConnectionInfo ci = Common.CreateConnectedConnectionInfo(null, false);
string queryText = string.Format("{0}\r\nGO\r\n{0}", Common.StandardQuery);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
string queryText = string.Format("{0}\r\nGO\r\n{0}", Constants.StandardQuery);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(queryText, ci, new QueryExecutionSettings(), fileStreamFactory);
BatchCallbackHelper(query,
b => batchStartCallbacksReceived++,
@@ -189,7 +191,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
}
[Fact]
public void QueryExecuteMultipleBatchesWithNoOp()
public async Task QueryExecuteMultipleBatchesWithNoOp()
{
// Setup:
// ... Keep track of how many times callbacks are called
@@ -199,9 +201,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a query from a two batches (with separator)
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false);
string queryText = string.Format("{0}\r\nGO\r\n{1}", Common.StandardQuery, Common.NoOpQuery);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
ConnectionInfo ci = Common.CreateConnectedConnectionInfo(null, false);
string queryText = string.Format("{0}\r\nGO\r\n{1}", Constants.StandardQuery, Common.NoOpQuery);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(queryText, ci, new QueryExecutionSettings(), fileStreamFactory);
BatchCallbackHelper(query,
b => batchStartCallbacksReceived++,
@@ -210,23 +212,24 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// .. I then execute the query
query.Execute();
await query.ExecutionTask;
// Then:
// ... I should get back a query with two batches
Assert.NotEmpty(query.Batches);
Assert.Equal(2, query.Batches.Length);
//// ... The query shouldn't have completed successfully unless all batches were executed
Assert.False(query.HasExecuted);
// ... The query should have completed successfully
Assert.True(query.HasExecuted);
//// ... The batch callbacks should have been called 0 times
Assert.Equal(0, batchStartCallbacksReceived);
Assert.Equal(0, batchCompletionCallbacksReceived);
Assert.Equal(0, batchMessageCallbacksReceived);
// ... The batch callbacks should have been called 2 times (for each no op batch)
Assert.Equal(2, batchStartCallbacksReceived);
Assert.Equal(2, batchCompletionCallbacksReceived);
Assert.Equal(2, batchMessageCallbacksReceived);
}
[Fact]
public void QueryExecuteMultipleNoOpBatches()
public async Task QueryExecuteMultipleNoOpBatches()
{
// Setup:
// ... Keep track of how many messages were sent
@@ -236,7 +239,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// ... I create a query from a two batches (with separator)
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false);
string queryText = string.Format("{0}\r\nGO\r\n{1}", Common.NoOpQuery, Common.NoOpQuery);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(queryText, ci, new QueryExecutionSettings(), fileStreamFactory);
BatchCallbackHelper(query,
b => { throw new Exception("Batch start handler was called"); },
@@ -245,6 +248,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// .. I then execute the query
query.Execute();
await query.ExecutionTask;
// Then:
// ... I should get back a query with no batches
@@ -271,7 +275,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
ConnectionInfo ci = Common.CreateTestConnectionInfo(null, true);
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
Query query = new Query(Common.InvalidQuery, ci, new QueryExecutionSettings(), fileStreamFactory);
BatchCallbackHelper(query,
b => batchStartCallbacksReceived++,

View File

@@ -4,7 +4,6 @@
//
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading;
@@ -12,10 +11,11 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
{
public class ResultSetTests
{
@@ -25,7 +25,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a new result set with a valid db data reader
DbDataReader mockReader = GetReader(null, false, string.Empty);
ResultSet resultSet = new ResultSet(mockReader, Common.Ordinal, Common.Ordinal, Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
ResultSet resultSet = new ResultSet(mockReader, Common.Ordinal, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory());
// Then:
// ... There should not be any data read yet
@@ -65,8 +65,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a new resultset with a valid db data reader that has data
// ... and I read it to the end
DbDataReader mockReader = GetReader(Common.StandardTestDataSet, false, Common.StandardQuery);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
DbDataReader mockReader = GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
ResultSet resultSet = new ResultSet(mockReader, Common.Ordinal, Common.Ordinal, fileStreamFactory);
resultSet.ResultCompletion += callback;
await resultSet.ReadResultToEnd(CancellationToken.None);
@@ -109,8 +109,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a new resultset with a valid db data reader that is FOR XML/JSON
// ... and I read it to the end
DbDataReader mockReader = GetReader(dataSets, false, Common.StandardQuery);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
DbDataReader mockReader = GetReader(dataSets, false, Constants.StandardQuery);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
ResultSet resultSet = new ResultSet(mockReader, Common.Ordinal, Common.Ordinal, fileStreamFactory);
resultSet.ResultCompletion += callback;
await resultSet.ReadResultToEnd(CancellationToken.None);
@@ -139,7 +139,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a new result set with a valid db data reader without executing it
DbDataReader mockReader = GetReader(null, false, string.Empty);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
ResultSet resultSet = new ResultSet(mockReader, Common.Ordinal, Common.Ordinal, fileStreamFactory);
// Then:
@@ -156,8 +156,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a new result set with a valid db data reader
// ... And execute the result
DbDataReader mockReader = GetReader(Common.StandardTestDataSet, false, Common.StandardQuery);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
DbDataReader mockReader = GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
ResultSet resultSet = new ResultSet(mockReader, Common.Ordinal, Common.Ordinal, fileStreamFactory);
await resultSet.ReadResultToEnd(CancellationToken.None);
@@ -177,8 +177,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I create a new result set with a valid db data reader
// ... And execute the result set
DbDataReader mockReader = GetReader(Common.StandardTestDataSet, false, Common.StandardQuery);
var fileStreamFactory = Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
DbDataReader mockReader = GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery);
var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
ResultSet resultSet = new ResultSet(mockReader, Common.Ordinal, Common.Ordinal, fileStreamFactory);
await resultSet.ReadResultToEnd(CancellationToken.None);

View File

@@ -8,12 +8,13 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.Execution
{
public class ServiceIntegrationTests
{
@@ -27,12 +28,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// ... Create a workspace service with a multi-line constructed query
// ... Create a query execution service without a connection service (we won't be
// executing queries), and the previously created workspace service
string query = string.Format("{0}{1}GO{1}{0}", Common.StandardQuery, Environment.NewLine);
string query = string.Format("{0}{1}GO{1}{0}", Constants.StandardQuery, Environment.NewLine);
var workspaceService = GetDefaultWorkspaceService(query);
var queryService = new QueryExecutionService(null, workspaceService);
// If: I attempt to get query text from execute document params (entire document)
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument };
var queryParams = new ExecuteDocumentSelectionParams {OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
var queryText = queryService.GetSqlText(queryParams);
// Then: The text should match the constructed query
@@ -44,12 +45,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
// Setup:
// ... Create a workspace service with a multi-line constructed query
string query = string.Format("{0}{1}GO{1}{0}", Common.StandardQuery, Environment.NewLine);
string query = string.Format("{0}{1}GO{1}{0}", Constants.StandardQuery, Environment.NewLine);
var workspaceService = GetDefaultWorkspaceService(query);
var queryService = new QueryExecutionService(null, workspaceService);
// If: I attempt to get query text from execute document params (partial document)
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.OwnerUri, QuerySelection = Common.SubsectionDocument };
var queryParams = new ExecuteDocumentSelectionParams {OwnerUri = Constants.OwnerUri, QuerySelection = Common.SubsectionDocument};
var queryText = queryService.GetSqlText(queryParams);
// Then: The text should be a subset of the constructed query
@@ -65,11 +66,11 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
var queryService = new QueryExecutionService(null, null);
// If: I attempt to get query text from execute string params
var queryParams = new ExecuteStringParams { OwnerUri = Common.OwnerUri, Query = Common.StandardQuery };
var queryParams = new ExecuteStringParams {OwnerUri = Constants.OwnerUri, Query = Constants.StandardQuery};
var queryText = queryService.GetSqlText(queryParams);
// Then: The text should match the standard query
Assert.Equal(Common.StandardQuery, queryText);
Assert.Equal(Constants.StandardQuery, queryText);
}
[Fact]
@@ -128,7 +129,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If: I call the inter-service API to dispose a query with a null success function
// Then: It should throw
await Assert.ThrowsAsync<ArgumentNullException>(
() => qes.InterServiceDisposeQuery(Common.OwnerUri, null, failureFunc));
() => qes.InterServiceDisposeQuery(Constants.OwnerUri, null, failureFunc));
}
[Fact]
@@ -141,7 +142,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If: I call the inter-service API to dispose a query with a null success function
// Then: It should throw
await Assert.ThrowsAsync<ArgumentNullException>(
() => qes.InterServiceDisposeQuery(Common.OwnerUri, successFunc, null));
() => qes.InterServiceDisposeQuery(Constants.OwnerUri, successFunc, null));
}
#endregion
@@ -157,7 +158,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// ... I request to execute a valid query with all batches as no op
var workspaceService = GetDefaultWorkspaceService(string.Format("{0}\r\nGO\r\n{0}", Common.NoOpQuery));
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri };
var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri };
var efv = new EventFlowValidator<ExecuteRequestResult>()
.AddStandardQueryResultValidator()
@@ -170,7 +171,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
.AddEventValidation(QueryCompleteEvent.Type, p =>
{
// Validate OwnerURI matches
Assert.Equal(Common.OwnerUri, p.OwnerUri);
Assert.Equal(Constants.OwnerUri, p.OwnerUri);
Assert.NotNull(p.BatchSummaries);
Assert.Equal(2, p.BatchSummaries.Length);
Assert.All(p.BatchSummaries, bs => Assert.Equal(0, bs.ResultSetSummaries.Length));
@@ -190,9 +191,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
// If:
// ... I request to execute a valid query with no results
var workspaceService = GetDefaultWorkspaceService(Common.StandardQuery);
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri };
var queryParams = new ExecuteDocumentSelectionParams { QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri};
var efv = new EventFlowValidator<ExecuteRequestResult>()
.AddStandardQueryResultValidator()
@@ -217,10 +218,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
// If:
// ... I request to execute a valid query with results
var workspaceService = GetDefaultWorkspaceService(Common.StandardQuery);
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false,
workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument };
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
var efv = new EventFlowValidator<ExecuteRequestResult>()
.AddStandardQueryResultValidator()
@@ -245,10 +246,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
// If:
// ... I request to execute a valid query with one batch and multiple result sets
var workspaceService = GetDefaultWorkspaceService(Common.StandardQuery);
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var dataset = new[] {Common.StandardTestResultSet, Common.StandardTestResultSet};
var queryService = Common.GetPrimedExecutionService(dataset, true, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument };
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
var efv = new EventFlowValidator<ExecuteRequestResult>()
.AddStandardQueryResultValidator()
@@ -273,9 +274,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
// If:
// ... I request a to execute a valid query with multiple batches
var workspaceService = GetDefaultWorkspaceService(string.Format("{0}\r\nGO\r\n{0}", Common.StandardQuery));
var workspaceService = GetDefaultWorkspaceService(string.Format("{0}\r\nGO\r\n{0}", Constants.StandardQuery));
var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument };
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
var efv = new EventFlowValidator<ExecuteRequestResult>()
.AddStandardQueryResultValidator()
@@ -305,7 +306,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// Given:
// If:
// ... I request to execute a query using a file URI that isn't connected
var workspaceService = GetDefaultWorkspaceService(Common.StandardQuery);
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, false, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = "notConnected", QuerySelection = Common.WholeDocument };
@@ -327,16 +328,16 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
// If:
// ... I request to execute a query
var workspaceService = GetDefaultWorkspaceService(Common.StandardQuery);
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument };
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
// Note, we don't care about the results of the first request
var firstRequestContext = RequestContextMocks.Create<ExecuteRequestResult>(null);
await Common.AwaitExecution(queryService, queryParams, firstRequestContext.Object);
// ... And then I request another query without waiting for the first to complete
queryService.ActiveQueries[Common.OwnerUri].HasExecuted = false; // Simulate query hasn't finished
queryService.ActiveQueries[Constants.OwnerUri].HasExecuted = false; // Simulate query hasn't finished
var efv = new EventFlowValidator<ExecuteRequestResult>()
.AddErrorValidation<string>(Assert.NotEmpty)
.Complete();
@@ -355,9 +356,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
// If:
// ... I request to execute a query
var workspaceService = GetDefaultWorkspaceService(Common.StandardQuery);
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument };
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
// Note, we don't care about the results of the first request
var firstRequestContext = RequestContextMocks.Create<ExecuteRequestResult>(null);
@@ -391,7 +392,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
// If:
// ... I request to execute a query with a missing query string
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.OwnerUri, QuerySelection = null };
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Constants.OwnerUri, QuerySelection = null};
var efv = new EventFlowValidator<ExecuteRequestResult>()
.AddErrorValidation<string>(Assert.NotEmpty)
@@ -411,9 +412,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
// If:
// ... I request to execute a query that is invalid
var workspaceService = GetDefaultWorkspaceService(Common.StandardQuery);
var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, true, workspaceService);
var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument };
var queryParams = new ExecuteDocumentSelectionParams {OwnerUri = Constants.OwnerUri, QuerySelection = Common.WholeDocument};
var efv = new EventFlowValidator<ExecuteRequestResult>()
.AddStandardQueryResultValidator()
@@ -456,7 +457,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
return efv.AddEventValidation(BatchStartEvent.Type, p =>
{
// Validate OwnerURI and batch summary is returned
Assert.Equal(Common.OwnerUri, p.OwnerUri);
Assert.Equal(Constants.OwnerUri, p.OwnerUri);
Assert.NotNull(p.BatchSummary);
});
}
@@ -467,7 +468,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
return efv.AddEventValidation(BatchCompleteEvent.Type, p =>
{
// Validate OwnerURI and result summary are returned
Assert.Equal(Common.OwnerUri, p.OwnerUri);
Assert.Equal(Constants.OwnerUri, p.OwnerUri);
Assert.NotNull(p.BatchSummary);
});
}
@@ -478,7 +479,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
return efv.AddEventValidation(MessageEvent.Type, p =>
{
// Validate OwnerURI and message are returned
Assert.Equal(Common.OwnerUri, p.OwnerUri);
Assert.Equal(Constants.OwnerUri, p.OwnerUri);
Assert.NotNull(p.Message);
});
}
@@ -489,7 +490,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
return efv.AddEventValidation(ResultSetCompleteEvent.Type, p =>
{
// Validate OwnerURI and summary are returned
Assert.Equal(Common.OwnerUri, p.OwnerUri);
Assert.Equal(Constants.OwnerUri, p.OwnerUri);
Assert.NotNull(p.ResultSetSummary);
});
}
@@ -499,7 +500,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.Execution
{
return efv.AddEventValidation(QueryCompleteEvent.Type, p =>
{
Assert.Equal(Common.OwnerUri, p.OwnerUri);
Assert.Equal(Constants.OwnerUri, p.OwnerUri);
Assert.NotNull(p.BatchSummaries);
Assert.Equal(expectedBatches, p.BatchSummaries.Length);
});

View File

@@ -9,11 +9,12 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
{
public class ExecutionPlanTests
{
@@ -136,12 +137,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I have a query that has results in the form of an execution plan
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams
{
QuerySelection = null,
OwnerUri = Common.OwnerUri,
OwnerUri = Constants.OwnerUri,
ExecutionPlanOptions = new ExecutionPlanOptions
{
IncludeActualExecutionPlanXml = false,
@@ -150,10 +151,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// ... And I then ask for a valid execution plan
var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Common.OwnerUri, BatchIndex = 0, ResultSetIndex = 0 };
var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Constants.OwnerUri, BatchIndex = 0, ResultSetIndex = 0 };
var executionPlanRequest = new EventFlowValidator<QueryExecutionPlanResult>()
.AddResultValidation(r =>
{
@@ -170,9 +171,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I ask for an execution plan for a file that hasn't executed a query
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Common.OwnerUri, ResultSetIndex = 0, BatchIndex = 0 };
var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Constants.OwnerUri, ResultSetIndex = 0, BatchIndex = 0 };
var executionPlanRequest = new EventFlowValidator<QueryExecutionPlanResult>()
.AddErrorValidation<string>(Assert.NotNull).Complete();
await queryService.HandleExecutionPlanRequest(executionPlanParams, executionPlanRequest.Object);
@@ -184,12 +185,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I have a query that hasn't finished executing (doesn't matter what)
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams
{
QuerySelection = null,
OwnerUri = Common.OwnerUri,
OwnerUri = Constants.OwnerUri,
ExecutionPlanOptions = new ExecutionPlanOptions
{
IncludeActualExecutionPlanXml = false,
@@ -198,11 +199,11 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
queryService.ActiveQueries[Common.OwnerUri].Batches[0].ResultSets[0].hasBeenRead = false;
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
queryService.ActiveQueries[Constants.OwnerUri].Batches[0].ResultSets[0].hasBeenRead = false;
// ... And I then ask for a valid execution plan from it
var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Common.OwnerUri, ResultSetIndex = 0, BatchIndex = 0 };
var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Constants.OwnerUri, ResultSetIndex = 0, BatchIndex = 0 };
var executionPlanRequest = new EventFlowValidator<QueryExecutionPlanResult>()
.AddErrorValidation<string>(Assert.NotNull).Complete();
await queryService.HandleExecutionPlanRequest(executionPlanParams, executionPlanRequest.Object);
@@ -214,12 +215,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I have a query that doesn't have any result sets
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams
{
QuerySelection = null,
OwnerUri = Common.OwnerUri,
OwnerUri = Constants.OwnerUri,
ExecutionPlanOptions = new ExecutionPlanOptions
{
IncludeActualExecutionPlanXml = false,
@@ -228,10 +229,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// ... And I then ask for an execution plan from a result set
var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Common.OwnerUri, ResultSetIndex = 0, BatchIndex = 0 };
var executionPlanParams = new QueryExecutionPlanParams { OwnerUri = Constants.OwnerUri, ResultSetIndex = 0, BatchIndex = 0 };
var executionPlanRequest = new EventFlowValidator<QueryExecutionPlanResult>()
.AddErrorValidation<string>(Assert.NotNull).Complete();
await queryService.HandleExecutionPlanRequest(executionPlanParams, executionPlanRequest.Object);

View File

@@ -8,7 +8,7 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
{
public class BatchTests
{

View File

@@ -8,7 +8,7 @@ using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
{
public class QueryTests
{

View File

@@ -12,11 +12,12 @@ using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
{
public class ResultSetTests
{
@@ -27,10 +28,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// Then: I should get a null argument exception
ResultSet rs = new ResultSet(
GetReader(null, false, Common.NoOpQuery), Common.Ordinal, Common.Ordinal,
Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
MemoryFileSystem.GetFileStreamFactory());
Assert.Throws<ArgumentNullException>(() => rs.SaveAs(
null,
Common.GetFileStreamFactory(new Dictionary<string, byte[]>()),
MemoryFileSystem.GetFileStreamFactory(),
null, null));
}
@@ -41,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// Then: I should get a null argument exception
ResultSet rs = new ResultSet(
GetReader(null, false, Common.NoOpQuery), Common.Ordinal, Common.Ordinal,
Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
MemoryFileSystem.GetFileStreamFactory());
Assert.Throws<ArgumentNullException>(() => rs.SaveAs(
new SaveResultsRequestParams(),
null, null, null));
@@ -54,10 +55,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// Then: I should get an invalid operation exception
ResultSet rs = new ResultSet(
GetReader(null, false, Common.NoOpQuery), Common.Ordinal, Common.Ordinal,
Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
MemoryFileSystem.GetFileStreamFactory());
Assert.Throws<InvalidOperationException>(() => rs.SaveAs(
new SaveResultsRequestParams(),
Common.GetFileStreamFactory(new Dictionary<string, byte[]>()),
MemoryFileSystem.GetFileStreamFactory(),
null, null));
}
@@ -67,16 +68,16 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// Setup:
// ... Create a result set that has been executed
ResultSet rs = new ResultSet(
GetReader(Common.StandardTestDataSet, false, Common.StandardQuery),
GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery),
Common.Ordinal, Common.Ordinal,
Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
MemoryFileSystem.GetFileStreamFactory());
// ... Insert a non-started task into the save as tasks
rs.SaveTasks.AddOrUpdate(Common.OwnerUri, new Task(() => { }), (s, t) => null);
rs.SaveTasks.AddOrUpdate(Constants.OwnerUri, new Task(() => { }), (s, t) => null);
// If: I attempt to save results with the same name as the non-completed task
// Then: I should get an invalid operation exception
var requestParams = new SaveResultsRequestParams {FilePath = Common.OwnerUri};
var requestParams = new SaveResultsRequestParams {FilePath = Constants.OwnerUri};
Assert.Throws<InvalidOperationException>(() => rs.SaveAs(
requestParams, GetMockFactory(GetMockWriter().Object, null),
null, null));
@@ -86,15 +87,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
public async Task SaveAsWithoutRowSelection()
{
// Setup:
// ... Create a fake place to store data
Dictionary<string, byte[]> mockFs = new Dictionary<string, byte[]>();
// ... Create a mock reader/writer for reading the result
IFileStreamFactory resultFactory = Common.GetFileStreamFactory(mockFs);
IFileStreamFactory resultFactory = MemoryFileSystem.GetFileStreamFactory();
// ... Create a result set with dummy data and read to the end
ResultSet rs = new ResultSet(
GetReader(Common.StandardTestDataSet, false, Common.StandardQuery),
GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery),
Common.Ordinal, Common.Ordinal,
resultFactory);
await rs.ReadResultToEnd(CancellationToken.None);
@@ -104,13 +102,13 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
IFileStreamFactory saveFactory = GetMockFactory(saveWriter.Object, resultFactory.GetReader);
// If: I attempt to save results and await completion
rs.SaveAs(new SaveResultsRequestParams {FilePath = Common.OwnerUri}, saveFactory, null, null);
Assert.True(rs.SaveTasks.ContainsKey(Common.OwnerUri));
await rs.SaveTasks[Common.OwnerUri];
rs.SaveAs(new SaveResultsRequestParams {FilePath = Constants.OwnerUri}, saveFactory, null, null);
Assert.True(rs.SaveTasks.ContainsKey(Constants.OwnerUri));
await rs.SaveTasks[Constants.OwnerUri];
// Then:
// ... The task should have completed successfully
Assert.Equal(TaskStatus.RanToCompletion, rs.SaveTasks[Common.OwnerUri].Status);
Assert.Equal(TaskStatus.RanToCompletion, rs.SaveTasks[Constants.OwnerUri].Status);
// ... All the rows should have been written successfully
saveWriter.Verify(
@@ -122,15 +120,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
public async Task SaveAsWithRowSelection()
{
// Setup:
// ... Create a fake place to store data
Dictionary<string, byte[]> mockFs = new Dictionary<string, byte[]>();
// ... Create a mock reader/writer for reading the result
IFileStreamFactory resultFactory = Common.GetFileStreamFactory(mockFs);
IFileStreamFactory resultFactory = MemoryFileSystem.GetFileStreamFactory();
// ... Create a result set with dummy data and read to the end
ResultSet rs = new ResultSet(
GetReader(Common.StandardTestDataSet, false, Common.StandardQuery),
GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery),
Common.Ordinal, Common.Ordinal,
resultFactory);
await rs.ReadResultToEnd(CancellationToken.None);
@@ -142,19 +137,19 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// If: I attempt to save results that has a selection made
var saveParams = new SaveResultsRequestParams
{
FilePath = Common.OwnerUri,
FilePath = Constants.OwnerUri,
RowStartIndex = 1,
RowEndIndex = Common.StandardRows - 2,
ColumnStartIndex = 0, // Column start/end doesn't matter, but are required to be
ColumnEndIndex = 10 // considered a "save selection"
};
rs.SaveAs(saveParams, saveFactory, null, null);
Assert.True(rs.SaveTasks.ContainsKey(Common.OwnerUri));
await rs.SaveTasks[Common.OwnerUri];
Assert.True(rs.SaveTasks.ContainsKey(Constants.OwnerUri));
await rs.SaveTasks[Constants.OwnerUri];
// Then:
// ... The task should have completed successfully
Assert.Equal(TaskStatus.RanToCompletion, rs.SaveTasks[Common.OwnerUri].Status);
Assert.Equal(TaskStatus.RanToCompletion, rs.SaveTasks[Constants.OwnerUri].Status);
// ... All the rows should have been written successfully
saveWriter.Verify(

View File

@@ -6,18 +6,18 @@
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution.SaveResults
{
public class ServiceIntegrationTests
{
@@ -25,7 +25,6 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
[Fact]
public async Task SaveResultsCsvNonExistentQuery()
{
// Given: A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(null);
@@ -34,20 +33,17 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// If: I attempt to save a result set from a query that doesn't exist
SaveResultsAsCsvRequestParams saveParams = new SaveResultsAsCsvRequestParams
{
OwnerUri = Common.OwnerUri // Won't exist because nothing has executed
OwnerUri = Constants.OwnerUri // Won't exist because nothing has executed
};
object error = null;
var requestContext = RequestContextMocks.Create<SaveResultRequestResult>(null)
.AddErrorHandling(o => error = o);
await qes.HandleSaveResultsAsCsvRequest(saveParams, requestContext.Object);
var evf = new EventFlowValidator<SaveResultRequestResult>()
.AddStandardErrorValidator()
.Complete();
await qes.HandleSaveResultsAsCsvRequest(saveParams, evf.Object);
// Then:
// ... An error event should have been fired
// ... No success event should have been fired
VerifyResponseCalls(requestContext, false, true);
Assert.IsType<SaveResultRequestError>(error);
Assert.NotNull(error);
Assert.NotNull(((SaveResultRequestError)error).message);
evf.Validate();
}
[Fact]
@@ -55,22 +51,22 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
{
// Given:
// ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Common.StandardQuery);
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
Dictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, ws, out storage);
// ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Common.OwnerUri };
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await qes.HandleExecuteRequest(executeParams, executeRequest.Object);
await qes.ActiveQueries[Common.OwnerUri].ExecutionTask;
await qes.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// If: I attempt to save a result set and get it to throw because of invalid column selection
SaveResultsAsCsvRequestParams saveParams = new SaveResultsAsCsvRequestParams
{
BatchIndex = 0,
FilePath = "qqq",
OwnerUri = Common.OwnerUri,
OwnerUri = Constants.OwnerUri,
ResultSetIndex = 0,
ColumnStartIndex = -1,
ColumnEndIndex = 100,
@@ -78,10 +74,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
RowEndIndex = 5
};
qes.CsvFileFactory = GetCsvStreamFactory(storage, saveParams);
object error = null;
var requestContext = RequestContextMocks.Create<SaveResultRequestResult>(null)
.AddErrorHandling(e => error = e);
await qes.HandleSaveResultsAsCsvRequest(saveParams, requestContext.Object);
var efv = new EventFlowValidator<SaveResultRequestResult>()
.AddStandardErrorValidator()
.Complete();
await qes.HandleSaveResultsAsCsvRequest(saveParams, efv.Object);
await qes.ActiveQueries[saveParams.OwnerUri]
.Batches[saveParams.BatchIndex]
.ResultSets[saveParams.ResultSetIndex]
@@ -90,10 +88,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// Then:
// ... An error event should have been fired
// ... No success event should have been fired
VerifyResponseCalls(requestContext, false, true);
Assert.IsType<SaveResultRequestError>(error);
Assert.NotNull(error);
Assert.NotNull(((SaveResultRequestError)error).message);
efv.Validate();
}
[Fact]
@@ -101,28 +96,30 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
{
// Given:
// ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Common.StandardQuery);
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
Dictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, ws, out storage);
// ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Common.OwnerUri};
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Constants.OwnerUri};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await qes.HandleExecuteRequest(executeParams, executeRequest.Object);
await qes.ActiveQueries[Common.OwnerUri].ExecutionTask;
await qes.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// If: I attempt to save a result set from a query
SaveResultsAsCsvRequestParams saveParams = new SaveResultsAsCsvRequestParams
{
OwnerUri = Common.OwnerUri,
OwnerUri = Constants.OwnerUri,
FilePath = "qqq",
BatchIndex = 0,
ResultSetIndex = 0
};
qes.CsvFileFactory = GetCsvStreamFactory(storage, saveParams);
SaveResultRequestResult result = null;
var requestContext = RequestContextMocks.Create<SaveResultRequestResult>(r => result = r);
await qes.HandleSaveResultsAsCsvRequest(saveParams, requestContext.Object);
var efv = new EventFlowValidator<SaveResultRequestResult>()
.AddStandardResultValidator()
.Complete();
await qes.HandleSaveResultsAsCsvRequest(saveParams, efv.Object);
await qes.ActiveQueries[saveParams.OwnerUri]
.Batches[saveParams.BatchIndex]
.ResultSets[saveParams.ResultSetIndex]
@@ -131,9 +128,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// Then:
// ... I should have a successful result
// ... There should not have been an error
VerifyResponseCalls(requestContext, true, false);
Assert.NotNull(result);
Assert.Null(result.Messages);
efv.Validate();
}
#endregion
@@ -151,20 +146,17 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// If: I attempt to save a result set from a query that doesn't exist
SaveResultsAsJsonRequestParams saveParams = new SaveResultsAsJsonRequestParams
{
OwnerUri = Common.OwnerUri // Won't exist because nothing has executed
OwnerUri = Constants.OwnerUri // Won't exist because nothing has executed
};
object error = null;
var requestContext = RequestContextMocks.Create<SaveResultRequestResult>(null)
.AddErrorHandling(o => error = o);
await qes.HandleSaveResultsAsJsonRequest(saveParams, requestContext.Object);
var efv = new EventFlowValidator<SaveResultRequestResult>()
.AddStandardErrorValidator()
.Complete();
await qes.HandleSaveResultsAsJsonRequest(saveParams, efv.Object);
// Then:
// ... An error event should have been fired
// ... No success event should have been fired
VerifyResponseCalls(requestContext, false, true);
Assert.IsType<SaveResultRequestError>(error);
Assert.NotNull(error);
Assert.NotNull(((SaveResultRequestError)error).message);
efv.Validate();
}
[Fact]
@@ -172,22 +164,22 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
{
// Given:
// ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Common.StandardQuery);
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
Dictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, ws, out storage);
// ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Common.OwnerUri };
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await qes.HandleExecuteRequest(executeParams, executeRequest.Object);
await qes.ActiveQueries[Common.OwnerUri].ExecutionTask;
await qes.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// If: I attempt to save a result set and get it to throw because of invalid column selection
SaveResultsAsJsonRequestParams saveParams = new SaveResultsAsJsonRequestParams
{
BatchIndex = 0,
FilePath = "qqq",
OwnerUri = Common.OwnerUri,
OwnerUri = Constants.OwnerUri,
ResultSetIndex = 0,
ColumnStartIndex = -1,
ColumnEndIndex = 100,
@@ -195,10 +187,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
RowEndIndex = 5
};
qes.JsonFileFactory = GetJsonStreamFactory(storage, saveParams);
object error = null;
var requestContext = RequestContextMocks.Create<SaveResultRequestResult>(null)
.AddErrorHandling(e => error = e);
await qes.HandleSaveResultsAsJsonRequest(saveParams, requestContext.Object);
var efv = new EventFlowValidator<SaveResultRequestResult>()
.AddStandardErrorValidator()
.Complete();
await qes.HandleSaveResultsAsJsonRequest(saveParams, efv.Object);
await qes.ActiveQueries[saveParams.OwnerUri]
.Batches[saveParams.BatchIndex]
.ResultSets[saveParams.ResultSetIndex]
@@ -207,10 +199,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// Then:
// ... An error event should have been fired
// ... No success event should have been fired
VerifyResponseCalls(requestContext, false, true);
Assert.IsType<SaveResultRequestError>(error);
Assert.NotNull(error);
Assert.NotNull(((SaveResultRequestError)error).message);
efv.Validate();
}
[Fact]
@@ -218,28 +207,29 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
{
// Given:
// ... A working query and workspace service
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Common.StandardQuery);
WorkspaceService<SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
Dictionary<string, byte[]> storage;
QueryExecutionService qes = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, ws, out storage);
// ... The query execution service has executed a query with results
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Common.OwnerUri };
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await qes.HandleExecuteRequest(executeParams, executeRequest.Object);
await qes.ActiveQueries[Common.OwnerUri].ExecutionTask;
await qes.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// If: I attempt to save a result set from a query
SaveResultsAsJsonRequestParams saveParams = new SaveResultsAsJsonRequestParams
{
OwnerUri = Common.OwnerUri,
OwnerUri = Constants.OwnerUri,
FilePath = "qqq",
BatchIndex = 0,
ResultSetIndex = 0
};
qes.JsonFileFactory = GetJsonStreamFactory(storage, saveParams);
SaveResultRequestResult result = null;
var requestContext = RequestContextMocks.Create<SaveResultRequestResult>(r => result = r);
await qes.HandleSaveResultsAsJsonRequest(saveParams, requestContext.Object);
var efv = new EventFlowValidator<SaveResultRequestResult>()
.AddStandardResultValidator()
.Complete();
await qes.HandleSaveResultsAsJsonRequest(saveParams, efv.Object);
await qes.ActiveQueries[saveParams.OwnerUri]
.Batches[saveParams.BatchIndex]
.ResultSets[saveParams.ResultSetIndex]
@@ -248,23 +238,13 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
// Then:
// ... I should have a successful result
// ... There should not have been an error
VerifyResponseCalls(requestContext, true, false);
Assert.NotNull(result);
Assert.Null(result.Messages);
efv.Validate();
}
#endregion
#region Private Helpers
private static void VerifyResponseCalls(Mock<RequestContext<SaveResultRequestResult>> requestContext, bool successCalled, bool errorCalled)
{
requestContext.Verify(rc => rc.SendResult(It.IsAny<SaveResultRequestResult>()),
successCalled ? Times.Once() : Times.Never());
requestContext.Verify(rc => rc.SendError(It.IsAny<object>()),
errorCalled ? Times.Once() : Times.Never());
}
private static IFileStreamFactory GetCsvStreamFactory(IDictionary<string, byte[]> storage, SaveResultsAsCsvRequestParams saveParams)
{
Mock<IFileStreamFactory> mock = new Mock<IFileStreamFactory>();
@@ -297,4 +277,27 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.SaveResults
#endregion
}
public static class SaveResultEventFlowValidatorExtensions
{
public static EventFlowValidator<SaveResultRequestResult> AddStandardErrorValidator(
this EventFlowValidator<SaveResultRequestResult> efv)
{
return efv.AddErrorValidation<SaveResultRequestError>(e =>
{
Assert.NotNull(e);
Assert.NotNull(e.message);
});
}
public static EventFlowValidator<SaveResultRequestResult> AddStandardResultValidator(
this EventFlowValidator<SaveResultRequestResult> efv)
{
return efv.AddResultValidation(r =>
{
Assert.NotNull(r);
Assert.Null(r.Messages);
});
}
}
}

View File

@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
{
public class SettingsTests
{

View File

@@ -4,10 +4,9 @@
//
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
{
public class SpecialActionTests
{

View File

@@ -4,16 +4,16 @@
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.UnitTests.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.QueryExecution
{
public class SubsetTests
{
@@ -64,7 +64,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
// ... I have a resultset that hasn't been executed and I request a valid result set from it
// Then:
// ... It should throw an exception for having not been read
ResultSet rs = new ResultSet(new TestDbDataReader(null), Common.Ordinal, Common.Ordinal, Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
ResultSet rs = new ResultSet(new TestDbDataReader(null), Common.Ordinal, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory());
await Assert.ThrowsAsync<InvalidOperationException>(() => rs.GetSubset(0, 1));
}
@@ -130,15 +130,15 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I have a query that has results (doesn't matter what)
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Common.OwnerUri};
var executeParams = new ExecuteDocumentSelectionParams {QuerySelection = null, OwnerUri = Constants.OwnerUri};
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// ... And I then ask for a valid set of results from it
var subsetParams = new SubsetParams { OwnerUri = Common.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 };
var subsetParams = new SubsetParams { OwnerUri = Constants.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 };
var subsetRequest = new EventFlowValidator<SubsetResult>()
.AddResultValidation(r =>
{
@@ -155,9 +155,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I ask for a set of results for a file that hasn't executed a query
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var subsetParams = new SubsetParams { OwnerUri = Common.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 };
var subsetParams = new SubsetParams { OwnerUri = Constants.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 };
var subsetRequest = new EventFlowValidator<SubsetResult>()
.AddResultValidation(r =>
{
@@ -174,16 +174,16 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I have a query that hasn't finished executing (doesn't matter what)
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Common.OwnerUri };
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
queryService.ActiveQueries[Common.OwnerUri].Batches[0].ResultSets[0].hasBeenRead = false;
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
queryService.ActiveQueries[Constants.OwnerUri].Batches[0].ResultSets[0].hasBeenRead = false;
// ... And I then ask for a valid set of results from it
var subsetParams = new SubsetParams { OwnerUri = Common.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 };
var subsetParams = new SubsetParams { OwnerUri = Constants.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 };
var subsetRequest = new EventFlowValidator<SubsetResult>()
.AddResultValidation(r =>
{
@@ -200,15 +200,15 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution
{
// If:
// ... I have a query that doesn't have any result sets
var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Common.OwnerUri };
var executeParams = new ExecuteDocumentSelectionParams { QuerySelection = null, OwnerUri = Constants.OwnerUri };
var executeRequest = RequestContextMocks.Create<ExecuteRequestResult>(null);
await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);
await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;
await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;
// ... And I then ask for a set of results from it
var subsetParams = new SubsetParams { OwnerUri = Common.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 };
var subsetParams = new SubsetParams { OwnerUri = Constants.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0 };
var subsetRequest = new EventFlowValidator<SubsetResult>()
.AddResultValidation(r =>
{

View File

@@ -9,7 +9,7 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.ServiceHost
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost
{
public class AsyncLockTests
{

View File

@@ -11,7 +11,7 @@ using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.ServiceHost
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost
{
public class AsyncQueueTests
{

View File

@@ -4,11 +4,11 @@
//
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Serializers;
using HostingMessage = Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Contracts.Message;
using Newtonsoft.Json.Linq;
using Xunit;
using HostingMessage = Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Contracts.Message;
namespace Microsoft.SqlTools.ServiceLayer.Test.ServiceHost
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost
{
public class TestMessageContents
{

View File

@@ -8,7 +8,7 @@ using System.Linq;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.ServiceHost
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost
{
/// <summary>
/// Logger test cases

View File

@@ -3,13 +3,11 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Linq;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Microsoft.SqlTools.ServiceLayer.Workspace.Contracts;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.ServiceHost
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost
{
/// <summary>
/// ScriptFile test case

View File

@@ -10,7 +10,7 @@ using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.ServiceHost
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost
{
public class ServiceHostTests
{

View File

@@ -5,7 +5,7 @@
using Microsoft.SqlTools.ServiceLayer.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.ServiceHost
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost
{
/// <summary>
/// ScriptFile test case

View File

@@ -6,7 +6,7 @@
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.LanguageServices
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.SqlContext
{
/// <summary>
/// Tests for the SqlContext settins

View File

@@ -6,7 +6,7 @@
using Microsoft.SqlTools.ServiceLayer.Utility;
using Xunit;
namespace Microsoft.SqlTools.Test.Utility
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
{
/// <summary>
/// Tests for the CommandOptions class

View File

@@ -11,7 +11,7 @@ using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Contracts;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.Utility
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
{
public class EventFlowValidator<TRequestContext>
{

View File

@@ -6,7 +6,7 @@
using Microsoft.SqlTools.ServiceLayer.Utility;
using Xunit;
namespace Microsoft.SqlTools.Test.Utility
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
{
/// <summary>
/// Tests for the LongList class

View File

@@ -7,7 +7,7 @@ using System.Reflection;
using Moq.Language;
using Moq.Language.Flow;
namespace Microsoft.SqlTools.ServiceLayer.Test.Utility
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
{
public static class MoqExtensions
{

View File

@@ -9,7 +9,7 @@ using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Hosting.Protocol.Contracts;
using Moq;
namespace Microsoft.SqlTools.ServiceLayer.Test.Utility
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
{
public static class RequestContextMocks
{

View File

@@ -3,10 +3,9 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.ServiceLayer;
using Xunit;
namespace Microsoft.SqlTools.Test.Utility
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
{
public class SrTests
{
@@ -16,10 +15,10 @@ namespace Microsoft.SqlTools.Test.Utility
[Fact]
public void SrPropertiesTest()
{
Assert.NotNull(SR.QueryServiceSubsetBatchNotCompleted);
Assert.NotNull(SR.QueryServiceFileWrapperWriteOnly);
Assert.NotNull(SR.QueryServiceFileWrapperNotInitialized);
Assert.NotNull(SR.QueryServiceColumnNull);
Assert.NotNull(ServiceLayer.SR.QueryServiceSubsetBatchNotCompleted);
Assert.NotNull(ServiceLayer.SR.QueryServiceFileWrapperWriteOnly);
Assert.NotNull(ServiceLayer.SR.QueryServiceFileWrapperNotInitialized);
Assert.NotNull(ServiceLayer.SR.QueryServiceColumnNull);
}
}
}

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