public void QueryStatus_NonCriticalErrorSuppressed()
        {
            // Arrange
            docLocatorMock.Setup(x => x.FindActiveDocument()).Throws(new InvalidOperationException("exception xxx"));

            // Act - should not throw
            var _ = testSubject.OleStatus;

            logger.AssertPartialOutputStringExists("exception xxx");
        }
        public async Task GetConfigForFile_FailedToProcessTsConfig_ParsingError_TsConfigIsSkipped()
        {
            const string testedFileName      = "tested\\file";
            var          tsConfigsInSolution = new[] { "config1", "config2" };
            var          tsConfigsLocator    = SetupTsConfigsLocator(testedFileName, tsConfigsInSolution);

            var eslintBridgeClient = new Mock <ITypeScriptEslintBridgeClient>();
            var parsingError       = new ParsingError {
                Code = ParsingErrorCode.UNSUPPORTED_TYPESCRIPT, Message = "some message", Line = 5555
            };

            SetupEslintBridgeResponse(eslintBridgeClient, new Dictionary <string, TSConfigResponse>
            {
                {
                    "config1", new TSConfigResponse
                    {
                        ParsingError = parsingError,
                        Files        = new[] { testedFileName } // should be ignored
                    }
                },
                { "config2", new TSConfigResponse() }
            });

            var logger      = new TestLogger();
            var testSubject = CreateTestSubject(tsConfigsLocator.Object, eslintBridgeClient.Object, logger: logger);
            var result      = await testSubject.GetConfigForFile(testedFileName, CancellationToken.None);

            result.Should().BeNull();

            eslintBridgeClient.Verify(x => x.TsConfigFiles("config1", CancellationToken.None), Times.Once);
            eslintBridgeClient.Verify(x => x.TsConfigFiles("config2", CancellationToken.None), Times.Once);
            eslintBridgeClient.VerifyNoOtherCalls();

            logger.AssertPartialOutputStringExists(parsingError.Message, parsingError.Code.ToString(), parsingError.Line.ToString());
        }
        [DataRow("PROJECT=p&SERVER=http://s", "hotspot")]                   // lookup is not case sensitive -> only hotspot is missing
        public async Task ProcessRequest_MissingParameter_Returns400StatusCode(string wholeQueryString, string missingParamList)
        {
            var testLogger     = new TestLogger(logToConsole: true);
            var apiHandlerMock = new Mock <IOpenInIDERequestHandler>();

            var context = CreateContext(wholeQueryString);

            var testSubject = new ShowHotspotOwinRequestHandler(apiHandlerMock.Object, testLogger);

            // Act
            await testSubject.ProcessRequest(context);

            context.Response.StatusCode.Should().Be(400);

            // Note: passing a variable number of items to a test is messy. Here, it's
            // simpler to pass a string and split it.
            var missingParamNames = missingParamList.Split(';');

            foreach (var paramName in missingParamNames)
            {
                testLogger.AssertPartialOutputStringExists(paramName);
            }

            CheckApiHandlerNotCalled(apiHandlerMock);
        }
        public async Task GetRules_AbortIfCancellationRequested()
        {
            // Arrange
            var testLogger = new TestLogger();

            CancellationTokenSource cts = new CancellationTokenSource();

            var serviceMock = new Mock <ISonarQubeService>();

            serviceMock.Setup(x => x.GetRulesAsync(It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(() =>
            {
                cts.Cancel();
                return(new List <SonarQubeRule>());
            });

            var testSubject = new CFamilyBindingConfigProvider(serviceMock.Object, testLogger);

            // Act
            var result = await testSubject.GetConfigurationAsync(CreateQp(), null, Language.Cpp, cts.Token);

            // Assert
            result.Should().BeNull();
            testLogger.AssertPartialOutputStringExists(CoreStrings.SonarQubeRequestTimeoutOrCancelled);
        }
Esempio n. 5
0
        public void DisableExcludedRules_CustomRulesAndExcludedRulesExist_CustomRulesAreUnchangedExcludedRulesAreDisabled()
        {
            // Arrange
            var testLogger = new TestLogger();

            var excluded = new string[] { "excluded1", "excluded2", "excluded3", "excluded4" };
            var custom   = new RulesSettings()
                           .AddRule("xxx", RuleLevel.On)
                           .AddRule("excluded1", RuleLevel.On)
                           .AddRule("yyy", RuleLevel.Off)
                           .AddRule("excluded2", RuleLevel.Off)
                           .AddRule("excluded4", RuleLevel.On);

            // Act
            var result = DynamicCFamilyRulesConfig.DisableExcludedRules(custom, excluded, testLogger);

            // Assert
            result.Should().NotBeSameAs(custom);
            custom.Rules.Count.Should().BeLessThan(result.Rules.Count);

            result.Rules.Keys.Should().BeEquivalentTo("xxx", "excluded1", "yyy", "excluded2", "excluded3", "excluded4");
            result.Rules["xxx"].Level.Should().Be(RuleLevel.On);
            result.Rules["excluded1"].Level.Should().Be(RuleLevel.Off); // changed from On to Off
            result.Rules["yyy"].Level.Should().Be(RuleLevel.Off);
            result.Rules["excluded2"].Level.Should().Be(RuleLevel.Off); // unchanged - still Off
            result.Rules["excluded4"].Level.Should().Be(RuleLevel.Off); // changed from On to Off

            testLogger.AssertPartialOutputStringExists("excluded1", "excluded2", "excluded3", "excluded4");
        }
Esempio n. 6
0
        public void GetBindAction_LoggerWritten()
        {
            var bindAction = testSubject.GetBindAction(null, new ProjectMock("c:\\test.csproj"), CancellationToken.None);

            bindAction.Should().NotBeNull();
            logger.AssertPartialOutputStringExists("test.csproj");
        }
        public async Task Analyze_EslintBridgeClientNotInitializedResponse_FollowedByParsingError_ParsingErrorIsLogged()
        {
            var logger = new TestLogger();
            var linterNotInitializedResponse = CreateLinterNotInitializedResponse();
            var parsingErrorResponse         = new AnalysisResponse
            {
                ParsingError = new ParsingError
                {
                    Code    = ParsingErrorCode.MISSING_TYPESCRIPT,
                    Line    = 5,
                    Message = "some message"
                }
            };

            var client = new Mock <IEslintBridgeClient>();

            client
            .SetupSequence(x => x.Analyze("some path", "some config", CancellationToken.None))
            .ReturnsAsync(linterNotInitializedResponse)
            .ReturnsAsync(parsingErrorResponse);

            var testSubject = CreateTestSubject(client.Object, logger: logger);
            await testSubject.Analyze("some path", "some config", CancellationToken.None);

            logger.AssertPartialOutputStringExists(Resources.ERR_ParsingError_MissingTypescript);
        }
        public void AnalysisFailed_AggregateException_LogToOutputWindow()
        {
            var exception = new AggregateException(
                new List <Exception>
            {
                new ArgumentNullException("this is a test1"),
                new NotImplementedException("this is a test2")
            });

            var filePath = "c:\\test\\foo-started.cpp";

            testSubject.AnalysisFailed(filePath, exception);

            logger.AssertPartialOutputStringExists("this is a test1");
            logger.AssertPartialOutputStringExists("this is a test2");
            logger.OutputStrings.Count.Should().Be(1);
        }
        public async Task Analyze_ResponseWithParsingError_ParsingErrorLogged(int errorCode)
        {
            var logger = new TestLogger();

            var parsingError = new ParsingError
            {
                Code    = (ParsingErrorCode)errorCode,
                Line    = 5,
                Message = "some message"
            };

            await SetupAnalysisWithParsingError(parsingError, logger);

            logger.AssertPartialOutputStringExists(parsingError.Code.ToString());
            logger.AssertPartialOutputStringExists(parsingError.Message);
            logger.AssertPartialOutputStringExists(parsingError.Line.ToString());
        }
Esempio n. 10
0
        public void LifeCycle_ProgressChanged_NonCriticalException_Suppressed()
        {
            // Arrange
            bool opExecuted = false;

            dummyStatusBar.ProgressOperation = () =>
            {
                opExecuted = true;
                throw new InvalidOperationException("xxx");
            };

            var progressHandler = new StatusBarDownloadProgressHandler(dummyStatusBar, dummyInstaller, logger);

            // Act and Assert: exception should be suppressed
            dummyInstaller.SimulateProgressChanged(new InstallationProgressChangedEventArgs(0, 1000));
            opExecuted.Should().BeTrue();

            logger.AssertPartialOutputStringExists("xxx");
        }
Esempio n. 11
0
        private void VerifyExceptionCaughtAndLogged(Exception setupException, IAnalysisIssueLocationVisualization location)
        {
            var    result = true;
            Action act    = () => result = testSubject.TryNavigate(location);

            act.Should().NotThrow();

            result.Should().BeFalse();

            logger.AssertPartialOutputStringExists(setupException.Message);
        }
        public void Ctor_FailsToRetrieveFileIcon_BlankIcon()
        {
            var location = CreateMockLocation("c:\\test\\c1.c", KnownMonikers.CFile, new NotImplementedException("this is a test"));

            var testSubject = CreateTestSubject(location.Object);

            testSubject.Icon.Should().BeEquivalentTo(KnownMonikers.Blank, c => c.ComparingByMembers <ImageMoniker>());

            logger.AssertPartialOutputStringExists("this is a test");
            logger.OutputStrings.Count.Should().Be(1);
        }
Esempio n. 13
0
        public void HttpRequestException_NoInnerException_IsHandledAndLogged()
        {
            // Arrange
            var testLogger = new TestLogger();

            // Act
            WebServiceHelper.SafeServiceCallAsync <bool>(() => throw new HttpRequestException("outer message"),
                                                         testLogger).Wait();

            // Assert
            testLogger.AssertPartialOutputStringExists("outer message");
        }
Esempio n. 14
0
        public void BringToFront_NonCriticalExceptions_IsSuppressed()
        {
            var testSubject = new IDEWindowService(nativeMock.Object, processMock.Object, logger);

            nativeMock.Setup(x => x.SetForegroundWindow(ValidHandle))
            .Throws(new InvalidOperationException("thrown from test code"));

            // Act
            testSubject.BringToFront();

            logger.AssertPartialOutputStringExists("thrown from test code");
        }
Esempio n. 15
0
        public void NonCriticalException_IsSuppressed()
        {
            // Arrange
            var testLogger = new TestLogger();

            // Act
            WebServiceHelper.SafeServiceCallAsync <bool>(() => throw new ArgumentNullException("dummy error message"),
                                                         testLogger).Wait();

            // Assert
            testLogger.AssertPartialOutputStringExists("dummy error message");
        }
        public void NonCriticalErrorInListener_IsSuppressedAndLogged()
        {
            var logger      = new TestLogger();
            var testSubject = new AnalysisRequester(logger);

            testSubject.AnalysisRequested += (s, e) => throw new ArgumentException("XXX yyy");

            // Act
            testSubject.RequestAnalysis();

            // Assert
            logger.AssertPartialOutputStringExists("XXX yyy");
        }
        public async Task ProcessRequest_UnrecognisedPath_Returns404(string requestedPath)
        {
            var testLogger = new TestLogger(logToConsole: true);
            var context    = CreateOwinContext(requestedPath);

            var handler     = CreateHandler("/sonarlint/api/handled");
            var testSubject = new OwinPipelineProcessor(new[] { handler }, testLogger);

            await testSubject.ProcessRequest(context.Environment).ConfigureAwait(false);

            context.Response.StatusCode.Should().Be(404);
            CheckCorsHeader(context);
            testLogger.AssertPartialOutputStringExists(requestedPath);
        }
        private void VerifyValidationFailed(TestConfigurationSetup solutionTestConfigurationSetup, string failureReasonString)
        {
            var configProvider = solutionTestConfigurationSetup == null
                ? SetupConfigurationProvider(BindingConfiguration.Standalone)
                : SetupConfigurationProvider(CreateBindingConfiguration(solutionTestConfigurationSetup));

            var logger = new TestLogger();

            var testSubject = new OpenInIdeStateValidator(configProvider, logger);
            var result      = testSubject.CanHandleOpenInIDERequest(new Uri(RequestConfiguration.ServerUrl), RequestConfiguration.ProjectKey, RequestConfiguration.OrganizationKey);

            result.Should().BeFalse();
            logger.AssertPartialOutputStringExists(failureReasonString);
        }
Esempio n. 19
0
        public async Task SynchronizeWithServer_SonarQubeServerNotYetConnected_StoreCleared()
        {
            var converter    = new Mock <ITaintIssueToIssueVisualizationConverter>();
            var taintStore   = new Mock <ITaintStore>();
            var sonarService = CreateSonarService(isConnected: false);
            var logger       = new TestLogger();

            var testSubject = CreateTestSubject(taintStore.Object, converter.Object, sonarService: sonarService.Object, logger: logger);
            await testSubject.SynchronizeWithServer();

            logger.AssertPartialOutputStringExists("not yet established");
            CheckIssuesAreNotFetched(sonarService);
            CheckStoreIsCleared(taintStore);
        }
        public async Task Analyze_ResponseWithParsingError_UnsupportedTypescript_ParsingErrorLogged()
        {
            var logger = new TestLogger();

            var parsingError = new ParsingError
            {
                Code    = ParsingErrorCode.UNSUPPORTED_TYPESCRIPT,
                Line    = 5,
                Message = "some message"
            };

            await SetupAnalysisWithParsingError(parsingError, logger);

            logger.AssertPartialOutputStringExists(TypeScript.Analyzer.Resources.ERR_ParsingError_UnsupportedTypescript);
        }
        public void Execute_NonCriticalException_IsSuppressed()
        {
            var logger = new TestLogger(logToConsole: true);
            var toolwindowServiceMock = new Mock <IToolWindowService>();

            toolwindowServiceMock.Setup(x => x.Show(ValidToolWindowId)).Throws(new InvalidOperationException("thrown by test"));

            var testSubject = new ShowToolWindowCommand(ValidCommandId, ValidToolWindowId, toolwindowServiceMock.Object, Mock.Of <IMenuCommandService>(), logger);

            // Act
            testSubject.Execute(null, null);

            toolwindowServiceMock.Verify(x => x.Show(ValidToolWindowId), Times.Once);
            logger.AssertPartialOutputStringExists(ValidToolWindowId.ToString(), "thrown by test");
        }
        public async Task ExecuteAnalysis_ResponseWithParsingError_MissingTypescript_ParsingErrorLogged()
        {
            var logger = new TestLogger();

            var parsingError = new ParsingError
            {
                Code    = ParsingErrorCode.MISSING_TYPESCRIPT,
                Line    = 5,
                Message = "some message"
            };

            await SetupAnalysisWithParsingError(parsingError, logger);

            logger.AssertPartialOutputStringExists(TypeScript.Analyzer.Resources.ERR_ParsingError_MissingTypescript);
        }
Esempio n. 23
0
        public async Task SynchronizeWithServer_UnsupportedServerVersion_StoreCleared(string versionString)
        {
            const uint cookie          = 999;
            var        sonarQubeServer = CreateSonarService(isConnected: true, serverType: ServerType.SonarQube, versionString);
            var        taintStore      = new Mock <ITaintStore>();
            var        monitorMock     = CreateMonitorSelectionMock(cookie);
            var        logger          = new TestLogger();

            var testSubject = CreateTestSubject(
                taintStore: taintStore.Object,
                sonarService: sonarQubeServer.Object,
                mode: SonarLintMode.Connected,
                vsMonitor: monitorMock.Object,
                logger: logger);

            await testSubject.SynchronizeWithServer();

            logger.AssertPartialOutputStringExists("requires SonarQube v8.6 or later");
            logger.AssertPartialOutputStringExists($"Connected SonarQube version: v{versionString}");

            CheckIssuesAreNotFetched(sonarQubeServer);
            CheckStoreIsCleared(taintStore);
            CheckUIContextUpdated(monitorMock, cookie, 0);
        }
        public void ProcessRequest_ExceptionInHandler_IsLoggedAndRethrown()
        {
            var          testLogger         = new TestLogger(logToConsole: true);
            const string handledRequestPath = "/path";
            var          context            = CreateOwinContext(handledRequestPath);

            const string expectedErrorMessage = "exception thrown by test";
            var          handler     = CreateHandler(handledRequestPath, processOp: () => throw new IndexOutOfRangeException(expectedErrorMessage));
            var          testSubject = new OwinPipelineProcessor(new[] { handler }, testLogger);

            Func <Task> act = () => testSubject.ProcessRequest(context.Environment);

            act.Should().ThrowExactly <IndexOutOfRangeException>().And.Message.Should().Be(expectedErrorMessage);
            CheckCorsHeader(context);
            testLogger.AssertPartialOutputStringExists(expectedErrorMessage);
        }
        public async Task ProcessRequest_RecognisedPath_ReturnsStatusSetByHandler()
        {
            var          testLogger         = new TestLogger(logToConsole: true);
            const int    expectedStatusCode = 12345;
            const string handledRequestPath = "/sonarlint/api/handled";
            var          context            = CreateOwinContext(handledRequestPath);

            var handler     = CreateHandler(handledRequestPath, expectedStatusCode);
            var testSubject = new OwinPipelineProcessor(new[] { handler }, testLogger);

            await testSubject.ProcessRequest(context.Environment).ConfigureAwait(false);

            context.Response.StatusCode.Should().Be(expectedStatusCode);
            CheckCorsHeader(context);
            testLogger.AssertPartialOutputStringExists(handledRequestPath);
        }
        public async Task Analyze_EslintBridgeClientNotInitializedResponse_FollowedByAnotherNotInitializedResponse_GeneralParsingError()
        {
            var logger = new TestLogger();
            var linterNotInitializedResponse = CreateLinterNotInitializedResponse();
            var client = new Mock <IEslintBridgeClient>();

            client
            .SetupSequence(x => x.Analyze("some path", "some config", CancellationToken.None))
            .ReturnsAsync(linterNotInitializedResponse)
            .ReturnsAsync(linterNotInitializedResponse);

            var testSubject = CreateTestSubject(client.Object, logger: logger);
            var result      = await testSubject.Analyze("some path", "some config", CancellationToken.None);

            logger.AssertPartialOutputStringExists(linterNotInitializedResponse.ParsingError.Message);
        }
Esempio n. 27
0
        public void Save_NonCriticalError_IsSquashed()
        {
            // Arrange
            var fileSystemMock = new Mock <IFileSystem>();

            fileSystemMock.Setup(x => x.File.WriteAllText("settings.file", It.IsAny <string>())).Throws(new System.InvalidOperationException("custom error message"));

            var logger      = new TestLogger(logToConsole: true);
            var testSubject = new RulesSettingsSerializer(fileSystemMock.Object, logger);

            // Act - should not throw
            testSubject.SafeSave("settings.file", new RulesSettings());

            // Assert
            logger.AssertPartialOutputStringExists("settings.file", "custom error message");
        }
        public void Execute_NonCriticalError_IsSuppressed()
        {
            // Arrange
            var userSettingsProvider = CreateDummyUserSettingsProvider("d:\\a\\file.txt");
            var testLogger           = new TestLogger();
            var testSubject          = new TestableOpenSettingsFileWpfCommand(new ConfigurableServiceProvider(), userSettingsProvider, null, testLogger)
            {
                OpenDocOp = () => throw new InvalidOperationException("dummy execute exception")
            };

            // Act - should not throw
            testSubject.Execute(null);

            // Assert
            testLogger.AssertPartialOutputStringExists("dummy execute exception");
        }
        public void Ctor_ErrorLoadingSettings_ErrorSquashed_AndEmptySettingsReturned()
        {
            // Arrange
            var fileSystemMock = new Mock <IFileSystem>();

            fileSystemMock.Setup(x => x.File.Exists("settings.file")).Returns(true);
            fileSystemMock.Setup(x => x.File.ReadAllText("settings.file")).Throws(new System.InvalidOperationException("custom error message"));

            var logger = new TestLogger(logToConsole: true);

            // Act
            var testSubject = new UserSettingsProvider(logger, fileSystemMock.Object, CreateMockFileMonitor("settings.file").Object);

            // Assert
            CheckSettingsAreEmpty(testSubject.UserSettings);
            logger.AssertPartialOutputStringExists("custom error message");
        }
        public async Task ProcessRequest_InvalidServerParameter_Returns400StatusCode()
        {
            const string invalidUrl     = "NOT_A_URL";
            var          testLogger     = new TestLogger(logToConsole: true);
            var          apiHandlerMock = new Mock <IOpenInIDERequestHandler>();

            var context = CreateContext($"server={invalidUrl}&project=any&hotspot=&any");

            var testSubject = new ShowHotspotOwinRequestHandler(apiHandlerMock.Object, testLogger);

            // Act
            await testSubject.ProcessRequest(context);

            context.Response.StatusCode.Should().Be(400);
            testLogger.AssertPartialOutputStringExists(invalidUrl);
            CheckApiHandlerNotCalled(apiHandlerMock);
        }