コード例 #1
0
        public void TestRefactoringMultipCompilations(string inputSource, string expected, string auxiliary, Action <SyntaxNode, NUnitToMSTestRewriter> afterTest, bool rewriteAsserts)
        {
            try
            {
                var workspace = new AdhocWorkspace();
                var solution  = TestSupport.CreateSolutionWithTwoCSharpProjects(workspace, nameof(auxiliary), auxiliary, nameof(inputSource), inputSource);

                bool seen = false;
                foreach (var project in solution.Projects)
                {
                    var comp   = project.GetCompilationAsync().Result;
                    var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
                    if (errors.Any())
                    {
                        Assert.Fail("Test cannot run, project {0}: {1}", project.Name,
                                    string.Join(Environment.NewLine, errors));
                    }

                    if (project.Name == nameof(inputSource))
                    {
                        foreach (var tree in comp.SyntaxTrees)
                        {
                            seen = true;
                            var sm   = comp.GetSemanticModel(tree);
                            var root = tree.GetRoot();

                            var rw     = new NUnitToMSTestRewriter(sm, rewriteAsserts);
                            var result = rw.Visit(root);

                            afterTest(result, rw);
                        }
                    }
                }

                if (!seen)
                {
                    Assert.Fail("Test produced no SyntaxTrees to compare.");
                }
            }
            catch (AssertFailedException)
            {
                Console.WriteLine(
                    "------------ Original Source -------------------" + Environment.NewLine +
                    inputSource + Environment.NewLine +
                    "------------------------------------------------");

                if (auxiliary != null)
                {
                    Console.WriteLine(
                        "------------ Auxiliary Source ------------------" + Environment.NewLine +
                        auxiliary + Environment.NewLine +
                        "------------------------------------------------");
                }

                throw;
            }
        }
コード例 #2
0
        private bool ProcessDiagnostics(NUnitToMSTestRewriter rw, DTEProject selectedProject)
        {
            foreach (var diag in rw.Diagnostics)
            {
                OutputMessage(diag.ToString(), null);
                m_errorListProvider.AddTask(diag, selectedProject);
                return(true);
            }

            return(false);
        }
コード例 #3
0
        public void TestRefactoringCore(string inputSource, string expected, string auxiliary, Action <SyntaxNode, NUnitToMSTestRewriter> afterTest, bool rewriteAsserts)
        {
            try
            {
                Compilation comp = auxiliary != null?
                                   TestSupport.CreateCompilationWithTestReferences(inputSource, auxiliary) :
                                       TestSupport.CreateCompilationWithTestReferences(inputSource);

                // TODO: Some unit test sources need to fixed first.
                //var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
                //if (errors.Any())
                //{
                //    Assert.Fail("Test cannot run, project: {0}", string.Join(Environment.NewLine, errors));
                //}

                bool seen = false;
                foreach (var tree in comp.SyntaxTrees)
                {
                    seen = true;
                    var sm   = comp.GetSemanticModel(tree);
                    var root = tree.GetRoot();

                    var rw     = new NUnitToMSTestRewriter(sm, rewriteAsserts);
                    var result = rw.Visit(root);

                    afterTest(result, rw);
                }

                if (!seen)
                {
                    Assert.Fail("Test produced no SyntaxTrees to compare.");
                }
            }
            catch (AssertFailedException)
            {
                Console.WriteLine(
                    "------------ Original Source -------------------" + Environment.NewLine +
                    inputSource + Environment.NewLine +
                    "------------------------------------------------");

                if (auxiliary != null)
                {
                    Console.WriteLine(
                        "------------ Auxiliary Source ------------------" + Environment.NewLine +
                        auxiliary + Environment.NewLine +
                        "------------------------------------------------");
                }

                throw;
            }
        }
コード例 #4
0
        private static async Task <List <TreeResult> > RewriteSourcesAsync(IEnumerable <Document> documents)
        {
            var results = new List <TreeResult>();

            foreach (var document in documents)
            {
                var semanticModel = await document.GetSemanticModelAsync();

                var tree = await document.GetSyntaxTreeAsync();

                var rw         = new NUnitToMSTestRewriter(semanticModel);
                var result     = rw.Visit(tree.GetRoot());
                var treeResult = new TreeResult(tree.FilePath, tree.Encoding, result, rw.Diagnostics, rw.Changed);
                results.Add(treeResult);
            }

            return(results);
        }
コード例 #5
0
        private static List <TreeResult> RewriteSources(Compilation compilation)
        {
            var resultsLock = new object();
            var results     = new List <TreeResult>();

            var p = Parallel.ForEach(
                compilation.SyntaxTrees,
                () => new List <TreeResult>(),
                (tree, state, local) =>
            {
                if (!state.ShouldExitCurrentIteration)
                {
                    try
                    {
                        var semanticModel = compilation.GetSemanticModel(tree);
                        var rw            = new NUnitToMSTestRewriter(semanticModel);
                        var result        = rw.Visit(tree.GetRoot());
                        var treeResult    = new TreeResult(tree.FilePath, tree.Encoding, result, rw.Diagnostics, rw.Changed);
                        local.Add(treeResult);
                    }
                    catch (Exception ex)
                    {
                        Error(ex.ToString());
                        state.Stop();
                    }
                }

                return(local);
            },
                local =>
            {
                lock (resultsLock)
                {
                    results.AddRange(local);
                }
            });

            if (DumpDiagnostics(results) || !p.IsCompleted)
            {
                return(null);
            }

            return(results);
        }
コード例 #6
0
        public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            var document = context.Document;

            if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
            {
                return;
            }
            if (context.CancellationToken.IsCancellationRequested)
            {
                return;
            }

            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            if (!(root.FindNode(context.Span) is UsingDirectiveSyntax node))
            {
                return;
            }
            if (!node.Name.ToFullString().Contains("NUnit"))
            {
                return;
            }

            var options = Options.Instance;

            context.RegisterRefactoring(CodeAction.Create(
                                            "Convert Tests to MSTest V2",
                                            async c =>
            {
                var tree          = await document.GetSyntaxTreeAsync(c);
                var semanticModel = await document.GetSemanticModelAsync(c);
                var rw            = new NUnitToMSTestRewriter(semanticModel, options.TransformAsserts);
                var result        = rw.Visit(tree.GetRoot());

                return(document.WithSyntaxRoot(result));
            }));
        }
コード例 #7
0
        /// <summary>
        /// Shows the tool window when the menu item is clicked.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event args.</param>
        private async TPL.Task InvokeRefactoring(object sender, EventArgs e)
        {
            using (var statusbar = new StatusbarContext(m_statusbar))
            {
                try
                {
                    bool diagnosticsWritten = false;
                    m_errorListProvider.Tasks.Clear();
                    statusbar.Clear();

                    var workspace   = ServiceProvider.GetRoslynVisualStudioWorkspace();
                    var solution    = workspace.CurrentSolution;
                    var newSolution = solution;

                    var selectedProject = VSExtensions.GetSelectedProject();
                    if (selectedProject != null)
                    {
                        var project = solution.Projects.FirstOrDefault(p => p.Name == selectedProject.Name);

                        if (project != null && IsSupportedProject(project))
                        {
                            //var hierarchyItem = GetProjectHierarchyItem(selectedProject);
                            var documentIds = GetSupportedDocumentIds(project);
                            int total       = CalculateStatusbarTotal(documentIds.Count());
                            int complete    = 1;

                            OutputMessage($"Updating project {project.FilePath}.", statusbar);

                            foreach (var documentId in documentIds)
                            {
                                var document = project.Documents.First(d => d.Id == documentId);
                                OutputMessage($"Processing {document.FilePath}", statusbar, complete, total);

                                var semanticModel = await document.GetSemanticModelAsync();

                                var tree = await document.GetSyntaxTreeAsync();

                                var rw     = new NUnitToMSTestRewriter(semanticModel, m_options.TransformAsserts);
                                var result = rw.Visit(tree.GetRoot());

                                if (rw.Changed)
                                {
                                    OutputMessage($"Saving changes in {document.FilePath}", statusbar, complete, total);
                                    var newDocument = document.WithSyntaxRoot(result);
                                    project     = newDocument.Project;
                                    newSolution = project.Solution;
                                }

                                if (ProcessDiagnostics(rw, selectedProject))
                                {
                                    diagnosticsWritten = true;
                                }

                                complete++;
                            }

                            if (newSolution != solution)
                            {
                                if (m_options.MakeSureProjectFileHasUnitTestType)
                                {
                                    OutputMessage("Ensuring project compatibility", statusbar, ++complete, total);
                                    project     = new ProjectUpdater(project).Update();
                                    newSolution = project.Solution;
                                }

                                if (!workspace.TryApplyChanges(newSolution))
                                {
                                    ServiceProvider.ShowErrorBox("Changes not saved.");
                                }

                                // This has to happen after "workspace.TryApplyChanges()", or some internal state
                                // is off, and the apply changes fails. This is because the following modify the
                                // project also/again.
                                AddMSTestPackages(selectedProject, statusbar, ref complete, total);
                                RemoveNUnitPackages(selectedProject, statusbar, ref complete, total);
                            }
                        }
                    }

                    if (diagnosticsWritten)
                    {
                        m_errorListProvider.Show();
                    }
                }
                catch (Exception ex)
                {
                    ServiceProvider.ShowErrorBox(ex.ToString());
                }
            }
        }