Beispiel #1
0
        public async Task <bool> TryInstallRelease(Release release)
        {
            try
            {
                _installerMutex.WaitOne();
                var downloadPath = Path.Combine(Path.GetTempPath(), "AxoCover." + release.Version + ".vsix");

                try
                {
                    if (File.Exists(downloadPath))
                    {
                        File.Delete(downloadPath);
                    }
                }
                catch
                {
                    _editorContext.WriteToLog($"Cannot write to {downloadPath}. Maybe another installation is in progress?");
                    return(false);
                }

                using (var webClient = new WebClient())
                {
                    await webClient.DownloadFileTaskAsync(release.AlternativeUri ?? release.Uri, downloadPath);
                }

                return(await Task.Run(async() =>
                {
                    try
                    {
                        InstallVsix(downloadPath);
                        return true;
                    }
                    catch (Exception e)
                    {
                        await _telemetryManager.UploadExceptionAsync(e);
                        return false;
                    }
                }));
            }
            catch
            {
                return(false);
            }
            finally
            {
                _installerMutex.ReleaseMutex();
            }
        }
        private async void UploadException()
        {
            if (Exception == null)
            {
                return;
            }

            State = TelemetryUploadState.InProgress;
            if (await _telemetryManager.UploadExceptionAsync(Exception, true))
            {
                State = TelemetryUploadState.Completed;
            }
            else
            {
                State = TelemetryUploadState.Failed;
            }
        }
Beispiel #3
0
        private void OnTestsFinished(object sender, EventArgs <TestReport> e)
        {
            if (e.Value.CoverageReport != null)
            {
                _report = e.Value.CoverageReport;

                var testMethods = e.Value.TestResults
                                  .Select(p => p.Method)
                                  .GroupBy(p => (p.Kind == CodeItemKind.Data ? p.Parent.FullName : p.FullName).CleanPath(true))
                                  .ToDictionary(p => p.Key, p => p.ToArray());

                _trackedMethods = _report.Modules
                                  .SelectMany(p => p.TrackedMethods)
                                  .Select(p => new { Id = p.Id, NameMatch = _visitorNameRegex.Match(p.Name), Name = p.Name })
                                  .DoIf(p => !p.NameMatch.Success, p => _telemetryManager.UploadExceptionAsync(new Exception("Could not parse tracked method name: " + p.Name)))
                                  .Where(p => p.NameMatch.Success)
                                  .ToDictionary(p => p.Id, p => testMethods.TryGetValue(p.NameMatch.Groups["visitorName"].Value.Replace("::", ".")) ?? new TestMethod[0]);

                CoverageUpdated?.Invoke(this, EventArgs.Empty);
            }
        }
Beispiel #4
0
        protected override TestReport RunTests(TestItem testItem, bool isCovering, bool isDebugging)
        {
            List <TestResult> testResults = new List <TestResult>();

            try
            {
                var sessionId       = _sessionId++;
                var outputDirectory = _storageController.CreateTestRunDirectory();

                var testMethods = testItem
                                  .Flatten(p => p.Children)
                                  .OfType <TestMethod>()
                                  .Where(p => p.Case != null)
                                  .ToArray();

                var testExecutionTasks = testMethods
                                         .GroupBy(p => p.TestAdapterName)
                                         .Distinct()
                                         .Select(p => new TestExecutionTask()
                {
                    TestCases          = p.Where(q => q.Case != null).Select(q => q.Case).ToArray(),
                    TestAdapterOptions = _testAdapterRepository.Adapters[p.Key]
                                         .GetLoadingOptions()
                                         .Do(q => q.IsRedirectingAssemblies = _options.IsRedirectingFrameworkAssemblies)
                })
                                         .ToArray();

                var testMethodsById = testMethods.ToDictionary(p => p.Case.Id);

                IHostProcessInfo hostProcessInfo = null;

                var solution = testItem.GetParent <TestSolution>();
                if (isCovering)
                {
                    var openCoverOptions = new OpenCoverOptions()
                    {
                        CodeAssemblies                = solution.CodeAssemblies,
                        TestAssemblies                = solution.TestAssemblies,
                        CoverageReportPath            = Path.Combine(outputDirectory, "coverageReport.xml"),
                        IsCoveringByTest              = _options.IsCoveringByTest,
                        IsIncludingSolutionAssemblies = _options.IsIncludingSolutionAssemblies,
                        IsExcludingTestAssemblies     = _options.IsExcludingTestAssemblies,
                        IsMergingByHash               = _options.IsMergingByHash,
                        IsSkippingAutoProps           = _options.IsSkippingAutoProps,
                        ExcludeAttributes             = _options.ExcludeAttributes,
                        ExcludeDirectories            = _options.ExcludeDirectories,
                        ExcludeFiles          = _options.ExcludeFiles,
                        Filters               = _options.Filters,
                        IsVisitorCountLimited = _options.IsVisitorCountLimited,
                        VisitorCountLimit     = _options.VisitorCountLimit
                    };
                    hostProcessInfo = new OpenCoverProcessInfo(openCoverOptions);
                }

                _executionProcess = ExecutionProcess.Create(AdapterExtensions.GetTestPlatformAssemblyPaths(_options.TestAdapterMode), hostProcessInfo, _options);
                _executionProcess.MessageReceived += (o, e) => OnTestLogAdded(e.Value);
                _executionProcess.TestStarted     += (o, e) =>
                {
                    var testMethod = testMethodsById.TryGetValue(e.Value.Id);
                    if (testMethod != null)
                    {
                        OnTestStarted(testMethod);
                    }
                };
                _executionProcess.TestResult += (o, e) =>
                {
                    var testMethod = testMethodsById.TryGetValue(e.Value.TestCase.Id);
                    if (testMethod != null)
                    {
                        var testResult = e.Value.ToTestResult(testMethod, sessionId);
                        testResults.Add(testResult);
                        OnTestExecuted(testResult);
                    }
                };
                _executionProcess.OutputReceived += (o, e) => OnTestLogAdded(e.Value);

                if (isDebugging)
                {
                    var debuggerAttachedEvent = new ManualResetEvent(false);
                    _executionProcess.DebuggerAttached += (o, e) => debuggerAttachedEvent.Set();

                    OnTestLogAdded(Resources.DebuggerAttaching);
                    if (_editorContext.AttachToProcess(_executionProcess.ProcessId) &&
                        debuggerAttachedEvent.WaitOne(TimeSpan.FromSeconds(_options.DebuggerTimeout)))
                    {
                        OnTestLogAdded(Resources.DebuggerAttached);
                        OnDebuggingStarted();
                    }
                    else
                    {
                        OnTestLogAdded(Resources.DebuggerFailedToAttach);
                    }
                }

                var options = new TestExecutionOptions()
                {
                    RunSettingsPath = _ioProvider.GetAbsolutePath(_options.TestSettings),
                    ApartmentState  = _options.TestApartmentState,
                    OutputPath      = outputDirectory,
                    SolutionPath    = solution.FilePath
                };

                _executionProcess.RunTests(testExecutionTasks, options);

                if (!_isAborting)
                {
                    if (isDebugging)
                    {
                        _editorContext.DetachFromProcess(_executionProcess.ProcessId);
                    }

                    OnTestLogAdded(Resources.ShuttingDown);
                    if (!_executionProcess.TryShutdown())
                    {
                        OnTestLogAdded(Resources.ShutdownFailed);
                    }
                    if (isCovering)
                    {
                        OnTestLogAdded(Resources.GeneratingCoverageReport);
                    }
                }

                _executionProcess.WaitForExit();

                if (_isAborting)
                {
                    return(null);
                }

                if (isCovering)
                {
                    var coverageReportPath = (hostProcessInfo as OpenCoverProcessInfo).CoverageReportPath;
                    if (System.IO.File.Exists(coverageReportPath))
                    {
                        var coverageReport = GenericExtensions.ParseXml <CoverageSession>(coverageReportPath);
                        return(new TestReport(testResults, coverageReport));
                    }
                }
                else
                {
                    return(new TestReport(testResults, null));
                }
            }
            catch (RemoteException exception) when(exception.RemoteReason != null)
            {
                _telemetryManager.UploadExceptionAsync(exception.RemoteReason);
                throw;
            }
            finally
            {
                if (_executionProcess != null)
                {
                    _executionProcess.Dispose();
                    _executionProcess = null;
                }
            }

            return(null);
        }
Beispiel #5
0
        public async Task <TestSolution> GetTestSolutionAsync(Solution solution, string testSettings)
        {
            try
            {
                Interlocked.Increment(ref _sessionCount);
                ScanningStarted?.Invoke(this, EventArgs.Empty);

                var testSolution = new TestSolution(solution.Properties.Item("Name").Value as string, solution.FileName);

                var testAdapters     = new HashSet <ITestAdapter>();
                var testAdapterModes = new HashSet <TestAdapterMode>();
                var projects         = solution.GetProjects();
                foreach (Project project in projects)
                {
                    var assemblyName = project.GetAssemblyName();

                    if (assemblyName == null)
                    {
                        continue;
                    }

                    var isTestSource     = false;
                    var testAdapterNames = new List <string>();
                    foreach (var testAdapter in _testAdapterRepository.Adapters.Values)
                    {
                        if (testAdapter.IsTestSource(project))
                        {
                            testAdapters.Add(testAdapter);
                            testAdapterModes.Add(testAdapter.Mode);
                            testAdapterNames.Add(testAdapter.Name);
                            isTestSource = true;
                        }
                    }

                    if (isTestSource)
                    {
                        var outputFilePath = project.GetOutputDllPath();
                        var testProject    = new TestProject(testSolution, project.Name, outputFilePath, testAdapterNames.ToArray());

                        testSolution.TestAssemblies.Add(assemblyName);
                    }
                    else
                    {
                        testSolution.CodeAssemblies.Add(assemblyName);
                    }
                }

                if (testAdapterModes.Count == 1)
                {
                    _options.TestAdapterMode = testAdapterModes.First();
                }

                foreach (var testAdapter in testAdapters.ToArray())
                {
                    if (testAdapter.Mode != _options.TestAdapterMode)
                    {
                        testAdapters.Remove(testAdapter);
                    }
                }

                await Task.Run(() =>
                {
                    try
                    {
                        var testDiscoveryTasks = testAdapters
                                                 .Select(p => new TestDiscoveryTask()
                        {
                            TestAssemblyPaths = testSolution.Children
                                                .OfType <TestProject>()
                                                .Where(q => q.TestAdapters.Contains(p.Name))
                                                .Select(q => q.OutputFilePath)
                                                .ToArray(),
                            TestAdapterOptions = p
                                                 .GetLoadingOptions()
                                                 .Do(q => q.IsRedirectingAssemblies = _options.IsRedirectingFrameworkAssemblies)
                        })
                                                 .ToArray();

                        using (var discoveryProcess = DiscoveryProcess.Create(AdapterExtensions.GetTestPlatformAssemblyPaths(_options.TestAdapterMode)))
                        {
                            _editorContext.WriteToLog(Resources.TestDiscoveryStarted);
                            discoveryProcess.MessageReceived += (o, e) => _editorContext.WriteToLog(e.Value);
                            discoveryProcess.OutputReceived  += (o, e) => _editorContext.WriteToLog(e.Value);

                            var discoveryResults = discoveryProcess.DiscoverTests(testDiscoveryTasks, testSettings);

                            var testCasesByAssembly = discoveryResults
                                                      .Distinct(_testCaseEqualityComparer)
                                                      .GroupBy(p => p.Source)
                                                      .ToDictionary(p => p.Key, p => p.ToArray(), StringComparer.OrdinalIgnoreCase);

                            foreach (TestProject testProject in testSolution.Children.ToArray())
                            {
                                var testCases = testCasesByAssembly.TryGetValue(testProject.OutputFilePath);
                                if (testCases != null)
                                {
                                    LoadTests(testProject, testCases);
                                }

                                var isEmpty = !testProject
                                              .Flatten <TestItem>(p => p.Children, false)
                                              .Any(p => p.Kind == CodeItemKind.Method);
                                if (isEmpty)
                                {
                                    testProject.Remove();
                                }
                            }

                            _editorContext.WriteToLog(Resources.TestDiscoveryFinished);
                        }
                    }
                    catch (RemoteException exception) when(exception.RemoteReason != null)
                    {
                        _editorContext.WriteToLog(Resources.TestDiscoveryFailed);
                        _telemetryManager.UploadExceptionAsync(exception.RemoteReason);
                    }
                    catch (Exception exception)
                    {
                        _editorContext.WriteToLog(Resources.TestDiscoveryFailed);
                        _telemetryManager.UploadExceptionAsync(exception);
                    }
                });

                ScanningFinished?.Invoke(this, EventArgs.Empty);

                return(testSolution);
            }
            finally
            {
                Interlocked.Decrement(ref _sessionCount);
            }
        }
        private async void UpdateAnchors()
        {
            try
            {
                if (!TryInitilaizeDocument() || _testSolution == null)
                {
                    return;
                }

                var projectItem = _editorContext
                                  .Solution
                                  .FindProjectItem(_textDocument.FilePath);
                if (projectItem == null || projectItem.ContainingProject == null || projectItem.FileCodeModel == null)
                {
                    return;
                }

                var projectModel = projectItem.ContainingProject;
                var testProject  = _testSolution.Children.FirstOrDefault(p => p.CodeItem.Name == projectModel.Name);
                if (testProject == null)
                {
                    return;
                }

                var testAnchors = new Dictionary <int, TestItemViewModel>();
                var classModels = projectItem.FileCodeModel.CodeElements.GetClasses();
                foreach (var classModel in classModels)
                {
                    var path   = classModel.FullName.Split('.');
                    var target = testProject;
                    foreach (var segment in path)
                    {
                        target = target.Children.FirstOrDefault(p => p.CodeItem.Name == segment);
                        if (target == null)
                        {
                            break;
                        }
                    }

                    if (target == null || target.CodeItem.Kind != CodeItemKind.Class)
                    {
                        continue;
                    }

                    var methodModels = classModel.GetMethods();
                    var testMethods  = target.Children;
                    foreach (var testMehod in testMethods)
                    {
                        var methodModel = methodModels.FirstOrDefault(p => p.Name == testMehod.CodeItem.Name);
                        if (methodModel == null)
                        {
                            continue;
                        }

                        testAnchors[methodModel.StartPoint.Line - 1] = testMehod;
                    }
                }
                _testAnchors       = testAnchors;
                _testAnchorMapping = new LineMapping(_textView.TextSnapshot.LineCount);
                UpdateAllLines();
            }
            catch (Exception e)
            {
                await _telemetryManager.UploadExceptionAsync(e);
            }
        }