Example #1
0
        public async Task QueryExecuteMissingSelectionTest()
        {
            // Given:
            // ... A workspace with a standard query is configured
            var workspaceService = Common.GetPrimedWorkspaceService(string.Empty);

            // If:
            // ... I request to execute a query with a missing query string
            var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var queryParams  = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = null
            };

            object errorResult    = null;
            var    requestContext = RequestContextMocks.Create <QueryExecuteResult>(null)
                                    .AddErrorHandling(error => errorResult = error);
            await queryService.HandleExecuteRequest(queryParams, requestContext.Object);


            // Then:
            // ... Am error should have been sent
            // ... No result should have been sent
            // ... No completion events should have been fired
            // ... An active query should not have been added
            VerifyQueryExecuteCallCount(requestContext, Times.Never(), Times.Never(), Times.Never(), Times.Never(), Times.Never(), Times.Once());
            Assert.NotNull(errorResult);
            Assert.IsType <string>(errorResult);
            Assert.DoesNotContain(Common.OwnerUri, queryService.ActiveQueries.Keys);

            // ... There should not be an active query
            Assert.Empty(queryService.ActiveQueries);
        }
Example #2
0
        public async void SubsetServiceOutOfRangeSubsetTest()
        {
            // If:
            // ... I have a query that doesn't have any result sets
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var executeParams    = new QueryExecuteParams {
                QuerySelection = null, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            // ... And I then ask for a set of results from it
            var subsetParams = new QueryExecuteSubsetParams {
                OwnerUri = Common.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0
            };
            QueryExecuteSubsetResult result = null;
            var subsetRequest = GetQuerySubsetResultContextMock(qesr => result = qesr, null);

            queryService.HandleResultSubsetRequest(subsetParams, subsetRequest.Object).Wait();

            // Then:
            // ... I should get an error result
            // ... There should not be rows
            // ... There should not be any error calls
            VerifyQuerySubsetCallCount(subsetRequest, Times.Once(), Times.Never());
            Assert.NotNull(result.Message);
            Assert.Null(result.ResultSubset);
        }
        public async Task CancelExecutedQueryTest()
        {
            // If:
            // ... I request a query (doesn't matter what kind) and wait for execution
            var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
            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[Constants.OwnerUri].ExecutionTask;

            // ... And then I request to cancel the query
            var cancelParams = new QueryCancelParams {
                OwnerUri = Constants.OwnerUri
            };
            var cancelRequest = new EventFlowValidator <QueryCancelResult>()
                                .AddResultValidation(r =>
            {
                Assert.False(string.IsNullOrWhiteSpace(r.Messages));
            }).Complete();

            await queryService.HandleCancelRequest(cancelParams, cancelRequest.Object);

            // Then:
            // ... The query should not have been disposed
            Assert.NotEmpty(queryService.ActiveQueries);
            cancelRequest.Validate();
        }
Example #4
0
        private async Task <SessionCreatedParameters> CreateSession()
        {
            ConnectionDetails details = new ConnectionDetails()
            {
                UserName     = "******",
                Password     = "******",
                DatabaseName = "msdb",
                ServerName   = "serverName"
            };

            SessionCreatedParameters sessionResult = null;

            serviceHostMock.AddEventHandling(CreateSessionCompleteNotification.Type, (et, p) => sessionResult = p);
            CreateSessionResponse result = default(CreateSessionResponse);
            var contextMock = RequestContextMocks.Create <CreateSessionResponse>(r => result = r).AddErrorHandling(null);

            connectionServiceMock.Setup(c => c.Connect(It.IsAny <ConnectParams>()))
            .Returns((ConnectParams connectParams) => Task.FromResult(GetCompleteParamsForConnection(connectParams.OwnerUri, details)));

            ConnectionInfo connectionInfo       = new ConnectionInfo(null, null, null);
            string         fakeConnectionString = "Data Source=server;Initial Catalog=database;Integrated Security=False;User Id=user";

            connectionInfo.AddConnection("Default", new SqlConnection(fakeConnectionString));
            connectionServiceMock.Setup((c => c.TryFindConnection(It.IsAny <string>(), out connectionInfo))).
            OutCallback((string t, out ConnectionInfo v) => v = connectionInfo)
            .Returns(true);

            connectionServiceMock.Setup(c => c.Disconnect(It.IsAny <DisconnectParams>())).Returns(true);
            await service.HandleCreateSessionRequest(details, contextMock.Object);

            await service.CreateSessionTask;

            return(sessionResult);
        }
        public async Task QueryExecuteInProgressTest()
        {
            // If:
            // ... I request to execute a query
            var workspaceService = GetDefaultWorkspaceService(Common.StandardQuery);
            var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var queryParams = new ExecuteDocumentSelectionParams { OwnerUri = Common.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
            var efv = new EventFlowValidator<ExecuteRequestResult>()
                .AddErrorValidation<string>(Assert.NotEmpty)
                .Complete();
            await Common.AwaitExecution(queryService, queryParams, efv.Object);

            // Then:
            // ... All events should have been called as per their flow validator
            efv.Validate();

            // ... There should only be one active query
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
        private async Task RunAndVerifyTelemetryTest(
            Action preRunSetup,
            Func <RequestContext <TextEdit[]>, Task> test,
            Action <TextEdit[], TelemetryParams> verify)
        {
            SemaphoreSlim   semaphore    = new SemaphoreSlim(0, 1);
            TelemetryParams actualParams = null;

            TextEdit[] result      = null;
            var        contextMock = RequestContextMocks.Create <TextEdit[]>(r =>
            {
                result = r;
            })
                                     .AddErrorHandling(null)
                                     .AddEventHandling(TelemetryNotification.Type, (e, p) =>
            {
                actualParams = p;
                semaphore.Release();
            });

            // Given a document that we want to format
            SetupScriptFile(defaultSqlContents);

            // When format document is called
            await RunAndVerify <TextEdit[]>(
                test : test,
                contextMock : contextMock,
                verify : () =>
            {
                // Wait for the telemetry notification to be processed on a background thread
                semaphore.Wait(TimeSpan.FromSeconds(10));
                verify(result, actualParams);
            });
        }
Example #7
0
        public async Task SubsetServiceUnexecutedQueryTest()
        {
            // If:
            // ... I have a query that hasn't finished executing (doesn't matter what)
            var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(Common.StandardTestDataSet, true, false, workspaceService);
            var executeParams    = new ExecuteDocumentSelectionParams {
                QuerySelection = null, OwnerUri = Constants.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <ExecuteRequestResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            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 = Constants.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0
            };
            var subsetRequest = new EventFlowValidator <SubsetResult>()
                                .AddStandardErrorValidation()
                                .Complete();
            await queryService.HandleResultSubsetRequest(subsetParams, subsetRequest.Object);

            subsetRequest.Validate();
        }
Example #8
0
        public async void QueryExecuteInProgressTest()
        {
            // Given:
            // ... A workspace with a standard query is configured
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);

            // If:
            // ... I request to execute a query
            var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var queryParams  = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument
            };

            // Note, we don't care about the results of the first request
            var firstRequestContext = RequestContextMocks.Create <QueryExecuteResult>(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
            object error = null;
            var    secondRequestContext = RequestContextMocks.Create <QueryExecuteResult>(null)
                                          .AddErrorHandling(e => error = e);
            await Common.AwaitExecution(queryService, queryParams, secondRequestContext.Object);

            // Then:
            // ... An error should have been sent
            // ... A result should have not have been sent
            // ... No completion event should have been fired
            // ... A batch completion event should have fired, but not a resultset event
            // ... There should only be one active query
            VerifyQueryExecuteCallCount(secondRequestContext, Times.Never(), Times.AtMostOnce(), Times.AtMostOnce(), Times.AtMostOnce(), Times.Never(), Times.Once());
            Assert.IsType <string>(error);
            Assert.NotEmpty((string)error);
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
        public async Task QueryExecuteCompletedTest()
        {
            // If:
            // ... I request to execute a query
            var workspaceService = GetDefaultWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
            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 after waiting for the first to complete
            var efv = new EventFlowValidator <ExecuteRequestResult>()
                      .AddStandardQueryResultValidator()
                      .AddStandardBatchStartValidator()
                      .AddStandardBatchCompleteValidator()
                      .AddStandardQueryCompleteValidator(1)
                      .Complete();

            await Common.AwaitExecution(queryService, queryParams, efv.Object);

            // Then:
            // ... All events should have been called as per their flow validator
            efv.Validate();

            // ... There should only be one active query
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
Example #10
0
        public async Task SaveResultsCsvNonExistentQuery()

        {
            // Given: A working query and workspace service
            WorkspaceService <SqlToolsSettings> ws = Common.GetPrimedWorkspaceService(null);
            QueryExecutionService qes = Common.GetPrimedExecutionService(null, false, false, ws);

            // 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
            };
            object error          = null;
            var    requestContext = RequestContextMocks.Create <SaveResultRequestResult>(null)
                                    .AddErrorHandling(o => error = o);
            await qes.HandleSaveResultsAsCsvRequest(saveParams, requestContext.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);
        }
        public async Task ExecutionPlanServiceUnexecutedQueryTest()
        {
            // If:
            // ... I have a query that hasn't finished executing (doesn't matter what)
            var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, false, workspaceService);
            var executeParams    = new ExecuteDocumentSelectionParams
            {
                QuerySelection       = null,
                OwnerUri             = Constants.OwnerUri,
                ExecutionPlanOptions = new ExecutionPlanOptions
                {
                    IncludeActualExecutionPlanXml    = false,
                    IncludeEstimatedExecutionPlanXml = true
                }
            };
            var executeRequest = RequestContextMocks.Create <ExecuteRequestResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            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 = Constants.OwnerUri, ResultSetIndex = 0, BatchIndex = 0
            };
            var executionPlanRequest = new EventFlowValidator <QueryExecutionPlanResult>()
                                       .AddStandardErrorValidation()
                                       .Complete();
            await queryService.HandleExecutionPlanRequest(executionPlanParams, executionPlanRequest.Object);

            executionPlanRequest.Validate();
        }
        public async Task ExecutionPlanServiceOutOfRangeSubsetTest()
        {
            // If:
            // ... I have a query that doesn't have any result sets
            var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
            var executeParams    = new ExecuteDocumentSelectionParams
            {
                QuerySelection       = null,
                OwnerUri             = Constants.OwnerUri,
                ExecutionPlanOptions = new ExecutionPlanOptions
                {
                    IncludeActualExecutionPlanXml    = false,
                    IncludeEstimatedExecutionPlanXml = true
                }
            };
            var executeRequest = RequestContextMocks.Create <ExecuteRequestResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;

            // ... And I then ask for an execution plan from a result set
            var executionPlanParams = new QueryExecutionPlanParams {
                OwnerUri = Constants.OwnerUri, ResultSetIndex = 0, BatchIndex = 0
            };
            var executionPlanRequest = new EventFlowValidator <QueryExecutionPlanResult>()
                                       .AddStandardErrorValidation()
                                       .Complete();
            await queryService.HandleExecutionPlanRequest(executionPlanParams, executionPlanRequest.Object);

            executionPlanRequest.Validate();
        }
Example #13
0
        public async void VerifyExternalLanguageStatusRequest()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                ExternalLanguageStatusResponseParams result = null;
                var requestContext = RequestContextMocks.Create <ExternalLanguageStatusResponseParams>(r => result = r).AddErrorHandling(null);

                ExternalLanguageStatusRequestParams requestParams = new ExternalLanguageStatusRequestParams
                {
                    OwnerUri     = connectionResult.ConnectionInfo.OwnerUri,
                    LanguageName = "Python"
                };

                await ExternalLanguageService.Instance.HandleExternalLanguageStatusRequest(requestParams, requestContext.Object);

                Assert.NotNull(result);

                ExternalLanguageService.Instance.ConnectionServiceInstance.Disconnect(new DisconnectParams
                {
                    OwnerUri = queryTempFile.FilePath,
                    Type     = ServiceLayer.Connection.ConnectionType.Default
                });
            }
        }
        public async Task ExecutionPlanServiceValidTest()
        {
            // If:
            // ... I have a query that has results in the form of an execution plan
            var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, false, workspaceService);
            var executeParams    = new ExecuteDocumentSelectionParams
            {
                QuerySelection       = null,
                OwnerUri             = Constants.OwnerUri,
                ExecutionPlanOptions = new ExecutionPlanOptions
                {
                    IncludeActualExecutionPlanXml    = false,
                    IncludeEstimatedExecutionPlanXml = true
                }
            };
            var executeRequest = RequestContextMocks.Create <ExecuteRequestResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;

            // ... And I then ask for a valid execution plan
            var executionPlanParams = new QueryExecutionPlanParams {
                OwnerUri = Constants.OwnerUri, BatchIndex = 0, ResultSetIndex = 0
            };
            var executionPlanRequest = new EventFlowValidator <QueryExecutionPlanResult>()
                                       .AddResultValidation(r =>
            {
                // Then: Messages should be null and execution plan should not be null
                Assert.NotNull(r.ExecutionPlan);
            }).Complete();
            await queryService.HandleExecutionPlanRequest(executionPlanParams, executionPlanRequest.Object);

            executionPlanRequest.Validate();
        }
Example #15
0
        public async Task CancelInProgressQueryTest()
        {
            // If:
            // ... I request a query (doesn't matter what kind) and execute it
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var executeParams    = new ExecuteDocumentSelectionParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.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

            // ... And then I request to cancel the query
            var cancelParams = new QueryCancelParams {
                OwnerUri = Common.OwnerUri
            };
            var cancelRequest = new EventFlowValidator <QueryCancelResult>()
                                .AddResultValidation(r =>
            {
                Assert.Null(r.Messages);
            }).Complete();
            await queryService.HandleCancelRequest(cancelParams, cancelRequest.Object);

            // Then:
            // ... The query should not have been disposed
            Assert.Equal(1, queryService.ActiveQueries.Count);
            cancelRequest.Validate();
        }
        public async void SaveResultsAsCsvExceptionTest()
        {
            // Execute a query
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(new[] { Common.StandardTestData }, true, false, workspaceService);
            var executeParams    = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await Common.AwaitExecution(queryService, executeParams, executeRequest.Object);

            // Request to save the results as csv with incorrect filepath
            var saveParams = new SaveResultsAsCsvRequestParams
            {
                OwnerUri       = Common.OwnerUri,
                ResultSetIndex = 0,
                BatchIndex     = 0,
                FilePath       = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "G:\\test.csv" : "/test.csv"
            };

            SaveResultRequestError errMessage = null;
            var saveRequest = GetSaveResultsContextMock(null, err => errMessage = (SaveResultRequestError)err);

            // Call save results and wait on the save task
            await queryService.HandleSaveResultsAsCsvRequest(saveParams, saveRequest.Object);

            ResultSet selectedResultSet = queryService.ActiveQueries[saveParams.OwnerUri].Batches[saveParams.BatchIndex].ResultSets[saveParams.ResultSetIndex];
            await selectedResultSet.GetSaveTask(saveParams.FilePath);

            // Expect to see error message
            VerifySaveResultsCallCount(saveRequest, Times.Never(), Times.Once());
            Assert.NotNull(errMessage);
            Assert.False(File.Exists(saveParams.FilePath));
        }
Example #17
0
        public async Task ServiceDispose()
        {
            // Setup:
            // ... We need a workspace service that returns a file
            var fileMock = new Mock <ScriptFile>();

            fileMock.SetupGet(file => file.Contents).Returns(Common.StandardQuery);
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);
            // ... We need a query service
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true,
                                                                      workspaceService.Object);

            // If:
            // ... I execute some bogus query
            var queryParams = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };
            var requestContext = RequestContextMocks.Create <QueryExecuteResult>(null);
            await queryService.HandleExecuteRequest(queryParams, requestContext.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            // ... And it sticks around as an active query
            Assert.Equal(1, queryService.ActiveQueries.Count);

            // ... The query execution service is disposed, like when the service is shutdown
            queryService.Dispose();

            // Then:
            // ... There should no longer be an active query
            Assert.Empty(queryService.ActiveQueries);
        }
        public async Task DisposeExecutedQuery()
        {
            // If:
            // ... I request a query (doesn't matter what kind)
            var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);
            var executeParams    = new ExecuteDocumentSelectionParams {
                QuerySelection = null, OwnerUri = Constants.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <ExecuteRequestResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.WorkTask;
            await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;

            // ... And then I dispose of the query
            var disposeParams = new QueryDisposeParams {
                OwnerUri = Constants.OwnerUri
            };
            var disposeRequest = new EventFlowValidator <QueryDisposeResult>()
                                 .AddStandardQueryDisposeValidator()
                                 .Complete();
            await queryService.HandleDisposeRequest(disposeParams, disposeRequest.Object);

            // Then:
            // ... And the active queries should be empty
            disposeRequest.Validate();
            Assert.Empty(queryService.ActiveQueries);
        }
Example #19
0
        private async Task <SessionCreatedParameters> CreateSession()
        {
            SessionCreatedParameters sessionResult = null;

            serviceHostMock.AddEventHandling(CreateSessionCompleteNotification.Type, (et, p) => sessionResult = p);
            CreateSessionResponse result = default(CreateSessionResponse);
            var contextMock = RequestContextMocks.Create <CreateSessionResponse>(r => result = r).AddErrorHandling(null);

            connectionServiceMock.Setup(c => c.Connect(It.IsAny <ConnectParams>()))
            .Returns((ConnectParams connectParams) => Task.FromResult(GetCompleteParamsForConnection(connectParams.OwnerUri, details)));

            ConnectionInfo connectionInfo = new ConnectionInfo(null, null, details);

            connectionInfo.AddConnection("Default", new SqlConnection(fakeConnectionString));
            connectionServiceMock.Setup((c => c.TryFindConnection(It.IsAny <string>(), out connectionInfo))).
            OutCallback((string t, out ConnectionInfo v) => v = connectionInfo)
            .Returns(true);

            connectionServiceMock.Setup(c => c.Disconnect(It.IsAny <DisconnectParams>())).Returns(true);
            await service.HandleCreateSessionRequest(details, contextMock.Object);

            await service.CreateSessionTask;

            return(sessionResult);
        }
        public async Task ServiceDispose()
        {
            // Setup:
            // ... We need a query service
            var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(null, true, false, false, workspaceService);

            // If:
            // ... I execute some bogus query
            var queryParams = new ExecuteDocumentSelectionParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Constants.OwnerUri
            };
            var requestContext = RequestContextMocks.Create <ExecuteRequestResult>(null);
            await queryService.HandleExecuteRequest(queryParams, requestContext.Object);

            await queryService.WorkTask;
            await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;

            // ... And it sticks around as an active query
            Assert.Equal(1, queryService.ActiveQueries.Count);

            // ... The query execution service is disposed, like when the service is shutdown
            queryService.Dispose();

            // Then:
            // ... There should no longer be an active query
            Assert.Empty(queryService.ActiveQueries);
        }
Example #21
0
        public async void QueryExecuteUnconnectedUriTest()
        {
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();
            // If:
            // ... I request to execute a query using a file URI that isn't connected
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), false, workspaceService.Object);

            var queryParams = new QueryExecuteParams {
                OwnerUri = "notConnected", QuerySelection = Common.WholeDocument
            };

            object error          = null;
            var    requestContext = RequestContextMocks.Create <QueryExecuteResult>(null)
                                    .AddErrorHandling(e => error = e);
            await queryService.HandleExecuteRequest(queryParams, requestContext.Object);

            // Then:
            // ... An error should have been returned
            // ... No result should have been returned
            // ... No completion event should have been fired
            // ... There should be no active queries
            VerifyQueryExecuteCallCount(requestContext, Times.Never(), Times.Never(), Times.Once());
            Assert.IsType <string>(error);
            Assert.NotEmpty((string)error);
            Assert.Empty(queryService.ActiveQueries);
        }
Example #22
0
        public async Task SubsetServiceOutOfRangeSubsetTest()
        {
            // If:
            // ... I have a query that doesn't have any result sets
            var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var executeParams    = new ExecuteDocumentSelectionParams {
                QuerySelection = null, OwnerUri = Constants.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <ExecuteRequestResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;

            // ... And I then ask for a set of results from it
            var subsetParams = new SubsetParams {
                OwnerUri = Constants.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0
            };
            var subsetRequest = new EventFlowValidator <SubsetResult>()
                                .AddStandardErrorValidation()
                                .Complete();
            await queryService.HandleResultSubsetRequest(subsetParams, subsetRequest.Object);

            subsetRequest.Validate();
        }
Example #23
0
        public async Task SubsetServiceUnexecutedQueryTest()
        {
            // If:
            // ... I have a query that hasn't finished executing (doesn't matter what)
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(new[] { Common.StandardTestData }, true, false, workspaceService);
            var executeParams    = new QueryExecuteParams {
                QuerySelection = null, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            queryService.ActiveQueries[Common.OwnerUri].Batches[0].ResultSets[0].hasBeenRead = false;

            // ... And I then ask for a valid set of results from it
            var subsetParams = new QueryExecuteSubsetParams {
                OwnerUri = Common.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0
            };
            QueryExecuteSubsetResult result = null;
            var subsetRequest = GetQuerySubsetResultContextMock(qesr => result = qesr, null);
            await queryService.HandleResultSubsetRequest(subsetParams, subsetRequest.Object);

            // Then:
            // ... I should get an error result
            // ... There should not be rows
            // ... There should not be any error calls
            VerifyQuerySubsetCallCount(subsetRequest, Times.Once(), Times.Never());
            Assert.NotNull(result.Message);
            Assert.Null(result.ResultSubset);
        }
Example #24
0
        public async Task SubsetServiceValidTest()
        {
            // If:
            // ... I have a query that has results (doesn't matter what)
            var workspaceService = Common.GetPrimedWorkspaceService(Constants.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(Common.ExecutionPlanTestDataSet, true, false, workspaceService);
            var executeParams    = new ExecuteDocumentSelectionParams {
                QuerySelection = null, OwnerUri = Constants.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <ExecuteRequestResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Constants.OwnerUri].ExecutionTask;

            // ... And I then ask for a valid set of results from it
            var subsetParams = new SubsetParams {
                OwnerUri = Constants.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0
            };
            var subsetRequest = new EventFlowValidator <SubsetResult>()
                                .AddResultValidation(r =>
            {
                // Then: Subset should not be null
                Assert.NotNull(r.ResultSubset);
            }).Complete();
            await queryService.HandleResultSubsetRequest(subsetParams, subsetRequest.Object);

            subsetRequest.Validate();
        }
Example #25
0
 private static Mock <RequestContext <QueryExecuteSubsetResult> > GetQuerySubsetResultContextMock(
     Action <QueryExecuteSubsetResult> resultCallback,
     Action <object> errorCallback)
 {
     return(RequestContextMocks.Create(resultCallback)
            .AddErrorHandling(errorCallback));
 }
Example #26
0
        public async void QueryExecuteSingleBatchSingleResultTest()
        {
            // Given:
            // ... A workspace with a standard query is configured
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);

            // If:
            // ... I request to execute a valid query with results
            var queryService = Common.GetPrimedExecutionService(new[] { Common.StandardTestData }, true, false, workspaceService);
            var queryParams  = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument
            };

            QueryExecuteResult                  result               = null;
            QueryExecuteCompleteParams          completeParams       = null;
            QueryExecuteBatchNotificationParams batchStartParams     = null;
            QueryExecuteBatchNotificationParams batchCompleteParams  = null;
            QueryExecuteResultSetCompleteParams resultCompleteParams = null;
            var requestContext = RequestContextMocks.Create <QueryExecuteResult>(qer => result = qer)
                                 .AddEventHandling(QueryExecuteCompleteEvent.Type, (et, p) => completeParams                = p)
                                 .AddEventHandling(QueryExecuteBatchStartEvent.Type, (et, p) => batchStartParams            = p)
                                 .AddEventHandling(QueryExecuteBatchCompleteEvent.Type, (et, p) => batchCompleteParams      = p)
                                 .AddEventHandling(QueryExecuteResultSetCompleteEvent.Type, (et, p) => resultCompleteParams = p);
            await Common.AwaitExecution(queryService, queryParams, requestContext.Object);

            // Then:
            // ... No errors should have been sent
            // ... A successful result should have been sent without messages
            // ... A completion event should have been fired with one result
            // ... A batch completion event should have been fired
            // ... A resultset completion event should have been fired
            VerifyQueryExecuteCallCount(requestContext, Times.Once(), Times.Once(), Times.Once(), Times.Once(), Times.Once(), Times.Never());
            Assert.Null(result.Messages);

            Assert.Equal(1, completeParams.BatchSummaries.Length);
            Assert.NotEmpty(completeParams.BatchSummaries[0].ResultSetSummaries);
            Assert.NotEmpty(completeParams.BatchSummaries[0].Messages);
            Assert.False(completeParams.BatchSummaries[0].HasError);

            // ... Batch start summary should not contain result sets, messages, but should contain owner URI
            Assert.NotNull(batchStartParams);
            Assert.NotNull(batchStartParams.BatchSummary);
            Assert.Null(batchStartParams.BatchSummary.Messages);
            Assert.Null(batchStartParams.BatchSummary.ResultSetSummaries);
            Assert.Equal(Common.OwnerUri, batchStartParams.OwnerUri);

            Assert.NotNull(batchCompleteParams);
            Assert.NotEmpty(batchCompleteParams.BatchSummary.ResultSetSummaries);
            Assert.NotEmpty(batchCompleteParams.BatchSummary.Messages);
            Assert.Equal(Common.OwnerUri, batchCompleteParams.OwnerUri);

            Assert.NotNull(resultCompleteParams);
            Assert.Equal(Common.StandardColumns, resultCompleteParams.ResultSetSummary.ColumnInfo.Length);
            Assert.Equal(Common.StandardRows, resultCompleteParams.ResultSetSummary.RowCount);
            Assert.Equal(Common.OwnerUri, resultCompleteParams.OwnerUri);

            // ... There should be one active query
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
        protected async Task RunAndVerify <T>(Func <RequestContext <T>, Task> test, Action <T> verify)
        {
            T   result      = default(T);
            var contextMock = RequestContextMocks.Create <T>(r => result = r).AddErrorHandling(null);

            await test(contextMock.Object);

            VerifyResult <T>(contextMock, verify, result);
        }
        /// <summary>
        /// Mock the requestContext for saving a result set
        /// </summary>
        /// <param name="resultCallback"></param>
        /// <param name="errorCallback"></param>
        /// <returns></returns>
        private static Mock <RequestContext <SaveResultRequestResult> > GetSaveResultsContextMock(
            Action <SaveResultRequestResult> resultCallback,
            Action <object> errorCallback)
        {
            var requestContext = RequestContextMocks.Create(resultCallback)
                                 .AddErrorHandling(errorCallback);

            return(requestContext);
        }
Example #29
0
        public async void QueryExecuteSingleBatchNoResultsTest()
        {
            // Given:
            // ... Default settings are stored in the workspace service
            // ... A workspace with a standard query is configured
            WorkspaceService <SqlToolsSettings> .Instance.CurrentSettings = new SqlToolsSettings();
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);

            // If:
            // ... I request to execute a valid query with no results
            var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var queryParams  = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };

            QueryExecuteResult                  result              = null;
            QueryExecuteCompleteParams          completeParams      = null;
            QueryExecuteBatchNotificationParams batchStartParams    = null;
            QueryExecuteBatchNotificationParams batchCompleteParams = null;
            var requestContext = RequestContextMocks.Create <QueryExecuteResult>(qer => result = qer)
                                 .AddEventHandling(QueryExecuteCompleteEvent.Type, (et, p) => completeParams           = p)
                                 .AddEventHandling(QueryExecuteBatchStartEvent.Type, (et, p) => batchStartParams       = p)
                                 .AddEventHandling(QueryExecuteBatchCompleteEvent.Type, (et, p) => batchCompleteParams = p)
                                 .AddEventHandling(QueryExecuteResultSetCompleteEvent.Type, null);
            await Common.AwaitExecution(queryService, queryParams, requestContext.Object);

            // Then:
            // ... No Errors should have been sent
            // ... A successful result should have been sent with messages on the first batch
            // ... A completion event should have been fired with empty results
            // ... A batch completion event should have been fired with empty results
            // ... A result set completion event should not have been fired
            VerifyQueryExecuteCallCount(requestContext, Times.Once(), Times.Once(), Times.Once(), Times.Once(), Times.Never(), Times.Never());
            Assert.Null(result.Messages);

            Assert.Equal(1, completeParams.BatchSummaries.Length);
            Assert.Empty(completeParams.BatchSummaries[0].ResultSetSummaries);
            Assert.NotEmpty(completeParams.BatchSummaries[0].Messages);

            // ... Batch start summary should not contain result sets, messages, but should contain owner URI
            Assert.NotNull(batchStartParams);
            Assert.NotNull(batchStartParams.BatchSummary);
            Assert.Null(batchStartParams.BatchSummary.Messages);
            Assert.Null(batchStartParams.BatchSummary.ResultSetSummaries);
            Assert.Equal(Common.OwnerUri, batchStartParams.OwnerUri);

            // ... Batch completion summary should contain result sets, messages, and the owner URI
            Assert.NotNull(batchCompleteParams);
            Assert.NotNull(batchCompleteParams.BatchSummary);
            Assert.Empty(batchCompleteParams.BatchSummary.ResultSetSummaries);
            Assert.NotEmpty(batchCompleteParams.BatchSummary.Messages);
            Assert.Equal(Common.OwnerUri, batchCompleteParams.OwnerUri);

            // ... There should be one active query
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
Example #30
0
        public async Task SaveCredentialThrowsIfPasswordMissing()
        {
            string errorResponse = null;
            var    contextMock   = RequestContextMocks.Create <bool>(null).AddErrorHandling((msg, code) => errorResponse = msg);

            await service.HandleSaveCredentialRequest(new Credential(CredentialId), contextMock.Object);

            TestUtils.VerifyErrorSent(contextMock);
            Assert.True(errorResponse.Contains("ArgumentException") || errorResponse.Contains("ArgumentNullException"));
        }