Example #1
0
        public static async Task AssertNoEnforcementAsync(
            IStyleRule rule, string documentText, Func<OptionSet, OptionSet> applyOptions)
        {
            using (var workspace = new AdhocWorkspace())
            {
                workspace.Options = applyOptions(workspace.Options);

                Project project = workspace.AddProject(BuildProject());
                Document document = workspace.AddDocument(project.Id, "TestFile.cs", SourceText.From(documentText));

                Solution enforcedSolution = await rule.EnforceAsync(document);
                Document enforcedDocument = enforcedSolution.GetDocument(document.Id);

                if (!document.Equals(enforcedDocument))
                {
                    List<TextChange> changes = (await enforcedDocument.GetTextChangesAsync(document)).ToList();
                    if (changes.Count == 0)
                    {
                        Assert.Fail("Solution mutated without document changes");
                    }

                    Console.WriteLine("Document changes:");
                    foreach (TextChange change in changes)
                    {
                        Console.WriteLine($"\t{change}");
                    }

                    Assert.Fail($"Enforced document has {changes.Count} changes; expected none");
                }
            }
        }
        public void CalculateForAllTests_Should_Return_OneCoverage_From_AllTests_When_There_IsOneProject_And_OneLineCoverage()
        {
            // arrange
            var rewrittenItemsByProject = new Dictionary<Project, List<RewrittenDocument>>();
            var workspace = new AdhocWorkspace();
            var project1 = workspace.AddProject("foo1.dll", LanguageNames.CSharp);

            RewriteResult rewriteResult = new RewriteResult(rewrittenItemsByProject);
            var rewrittenTree = CSharpSyntaxTree.ParseText("");

            var rewrittenDocument1 = new RewrittenDocument( rewrittenTree, null, true);
            rewriteResult.Items[project1] = new List<RewrittenDocument>() { rewrittenDocument1 };

            var semanticModel = Substitute.For<ISemanticModel>();
            var compiledItem = Substitute.For<ICompiledItem>();
            string assembly = "assembly path";

            compiledItem.Project.Returns(project1);
            compiledItem.DllPath.Returns(assembly);
            compiledItem.GetSemanticModel(rewrittenDocument1.SyntaxTree).Returns(semanticModel);
            _compiledAllItems.Add(compiledItem);

            var expectedLineCoverage = new[] {new LineCoverage()};
            _testRunnerMock.RunAllTestsInDocument(rewrittenDocument1,
                semanticModel,
                project1,
                Arg.Is<string[]>(x=>assembly==x[0]))
                .Returns(expectedLineCoverage);

            // act
            LineCoverage[] output = _sut.CalculateForAllTests(rewriteResult);

            // assert
            Assert.That(output, Is.EquivalentTo(expectedLineCoverage));
        }
        public void CalculateForAllTests_Should_CompileProvidedDocuments()
        {
            // arrange
            var rewrittenItemsByProject = new Dictionary<Project, List<RewrittenDocument>>();

            var workspace = new AdhocWorkspace();
            var project1 = workspace.AddProject("foo1.dll", LanguageNames.CSharp);

            RewriteResult rewriteResult = new RewriteResult(rewrittenItemsByProject);
            var rewrittenTree = CSharpSyntaxTree.ParseText("");

            var rewrittenDocument1 = new RewrittenDocument( rewrittenTree, null, false);
            rewriteResult.Items[project1] = new List<RewrittenDocument>() { rewrittenDocument1 };

            var compiledItem = Substitute.For<ICompiledItem>();
            compiledItem.Project.Returns(project1);
            _compiledAllItems.Add(compiledItem);

            // act
            _sut.CalculateForAllTests(rewriteResult);

            // assert
            _compilerMock.Received(1).Compile
                (Arg.Is<IEnumerable<CompilationItem>>(x => x.First().SyntaxTrees[0] ==
                rewriteResult.ToCompilationItems().First().SyntaxTrees[0]));
        }
        public void TestInit()
        {
            try
            {
                workspace = new AdhocWorkspace();

                project = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "TestProj", "TestProj", LanguageNames.CSharp)
                    .WithMetadataReferences(new[] {
                        MetadataReference.CreateFromFile(typeof(DotvvmConfiguration).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
                    });
                workspace.AddProject(project);

                workspace.AddDocument(project.Id, "test", SourceText.From("class A {}"));

                context = new DothtmlCompletionContext()
                {
                    Configuration = DotvvmConfiguration.CreateDefault(),
                    RoslynWorkspace = workspace
                };

            }
            catch (ReflectionTypeLoadException ex)
            {
                throw new Exception(string.Join("\r\n", ex.LoaderExceptions.Select(e => e.ToString())));
            }
        }
Example #5
0
        public static async Task AssertEnforcementAsync(
            IStyleRule rule, string originalText, string expectedText, Func<OptionSet, OptionSet> applyOptions)
        {
            using (var workspace = new AdhocWorkspace())
            {
                workspace.Options = applyOptions(workspace.Options);

                Project project = workspace.AddProject(BuildProject());
                Document document = workspace.AddDocument(project.Id, "TestFile.cs", SourceText.From(originalText));

                Solution enforcedSolution = await rule.EnforceAsync(document);
                Document enforcedDocument = enforcedSolution.GetDocument(document.Id);

                if (document.Equals(enforcedDocument))
                {
                    Assert.Fail("Expected enforcement, but no changes were made to the document");
                }

                SyntaxTree enforcedSyntax = await enforcedDocument.GetSyntaxTreeAsync();
                SyntaxTree expectedSyntax = SyntaxFactory.ParseCompilationUnit(expectedText).SyntaxTree;
                List<TextChange> unexpectedChanges = expectedSyntax.GetChanges(enforcedSyntax).ToList();
                if (unexpectedChanges.Count > 0)
                {
                    Console.WriteLine("Unexpected changes:");
                    List<TextChange> changes = (await enforcedDocument.GetTextChangesAsync(document)).ToList();
                    foreach (TextChange change in changes)
                    {
                        Console.WriteLine($"\t{change}");
                    }

                    Assert.Fail($"Enforced document has {changes.Count} unexpected changes");
                }
            }
        }
Example #6
0
 private SyntaxNode FormatSyntaxNode(SyntaxNode node)
 {
     Workspace customWorkspace = new AdhocWorkspace();
     var options = customWorkspace.Options;
     var formattedResult = Formatter.Format(node, customWorkspace, options);
     return formattedResult;
 }
        protected Project CreateProject(Dictionary<string, string> sources)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt = CSharpDefaultFileExt;

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp);

            foreach (var reference in References)
            {
                solution = solution.AddMetadataReference(projectId, reference);
            }

            int count = 0;
            foreach (var source in sources)
            {
                var newFileName = source.Key;
                var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source.Value));
                count++;
            }

            var project = solution.GetProject(projectId)
                .WithCompilationOptions(CompilationOptions);
            return project;
        }
        public async Task UpdaterService()
        {
            var exportProvider = TestHostServices.CreateMinimalExportProvider();

            var workspace = new AdhocWorkspace(TestHostServices.CreateHostServices(exportProvider));
            workspace.Options = workspace.Options.WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1);

            var listener = new Listener();
            var analyzerReference = new AnalyzerFileReference(typeof(object).Assembly.Location, new NullAssemblyAnalyzerLoader());

            var service = CreateRemoteHostClientService(workspace, SpecializedCollections.SingletonEnumerable<AnalyzerReference>(analyzerReference), listener);

            service.Enable();

            // make sure client is ready
            var client = await service.GetRemoteHostClientAsync(CancellationToken.None);

            // add solution
            workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));

            var listeners = exportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>();
            var workspaceListener = listeners.First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter;

            // wait for listener
            await workspaceListener.CreateWaitTask();
            await listener.CreateWaitTask();

            // checksum should already exist
            SolutionStateChecksums checksums;
            Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out checksums));

            service.Disable();
        }
        public void Should_Add_InternalToVisible_To_AllReferencedProjects()
        {
            // arrange
            const string expectedAttribute = @"System.Runtime.CompilerServices.InternalsVisibleTo(""Tests.dll_COVERAGE.dll"")";
            const string sourceCode = "class SampleClass{}";
            SyntaxNode node = CSharpSyntaxTree.ParseText(sourceCode).GetRoot();

            var workspace = new AdhocWorkspace();

            var referencedProject1 = workspace.AddProject("foo2.dll", LanguageNames.CSharp);
            workspace.AddDocument(referencedProject1.Id, "1.cs", SourceText.From(""));

            var testsProject = workspace.AddProject("Tests.dll", LanguageNames.CSharp);

            var solution = workspace.CurrentSolution.AddProjectReference(testsProject.Id, new ProjectReference(referencedProject1.Id));

            _auditVariablesRewriterMock.Rewrite(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<SyntaxNode>()).
                Returns(new RewrittenDocument(node.SyntaxTree, null, false));

            // act
            RewriteResult result = _solutionRewriter.RewriteAllClasses(solution.Projects);
            List<RewrittenDocument> projectItems1 = result.Items.Values.First();
            var attributes = projectItems1[0].SyntaxTree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().ToArray();

            // assert
            Assert.That(result.Items.Count, Is.EqualTo(1));
            Assert.That(projectItems1.Count, Is.EqualTo(1));

            Assert.That(attributes.Length, Is.EqualTo(1));
            Assert.That(attributes[0].ToString(), Is.EqualTo(expectedAttribute));
        }
Example #10
0
        protected Solution CreateSolution(string[] sources, string[] preprocessorSymbols = null, string language = LanguageNames.CSharp)
        {
            string fileExtension = language == LanguageNames.CSharp ? CSharpFileExtension : VBFileExtension;
            var projectId = ProjectId.CreateNewId(TestProjectName);

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .AddMetadataReferences(projectId, GetSolutionMetadataReferences());

            if (preprocessorSymbols != null)
            {
                var project = solution.Projects.Single();
                project = project.WithParseOptions(
                    ((CSharpParseOptions)project.ParseOptions).WithPreprocessorSymbols(preprocessorSymbols));

                solution = project.Solution;
            }

            int count = 0;
            foreach (var source in sources)
            {
                var fileName = FileNamePrefix + count + fileExtension;
                var documentId = DocumentId.CreateNewId(projectId, fileName);
                solution = solution.AddDocument(documentId, fileName, SourceText.From(source));
            }

            return solution;
        }
        public override sealed async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            //  var syntaxNode = root.FindNode(diagnosticSpan);
            //var declaration = root.FindToken(diagnosticSpan.Start);
            // var firstToken = declaration.GetFirstToken();
            // var leadingTrivia = firstToken.LeadingTrivia;
            // var trimmedLocal = declaration.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty));
            var cw = new AdhocWorkspace();
            OptionSet options = cw.Options;
            options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInMethods, false);
            options = options.WithChangedOption(CSharpFormattingOptions.IndentBlock, false);
            context.RegisterCodeFix(
     CodeAction.Create(
         Title,
        async c =>
         {
             var oldNode = root.FindTrivia(diagnosticSpan.Start);
             var newRoot = root.ReplaceTrivia(oldNode, SyntaxTriviaList.Empty);
             newRoot = newRoot.WithAdditionalAnnotations(Formatter.Annotation);
             newRoot = Formatter.Format(newRoot, new AdhocWorkspace(),options);
             //TODO:Need to remove empty line if it followed by a comment(Formatting).
             return await Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
         }),
     context.Diagnostics);
        }
        public void ImplementProperty_GenerateLineBreaks()
        {
            WithSourceFiles(Files.ChildClass, Files.Mixin);

            var typeSymbol = Substitute.For<ITypeSymbol>();
            var mixin = Substitute.For<MixinReference>();
            mixin.Name.Returns("_mixin");

            var property = new Property("Name", typeSymbol, true, true);

            var implementPropertyStrategy = new ImplementPropertyForwarding(
                mixin, Semantic, new Settings(avoidLineBreaksInProperties:false));

            var memberDeclaration = implementPropertyStrategy.ImplementMember(property, 0);

            // Assert:
            // let the formatting engine format the output source and ensure
            // that the text has only 6 lines:
            // <empty line>
            // public Name
            // { 
            //    get
            //    {
            //        ...
            //    }
            //    <empty line>
            //    ...
            // }

            var workspace = new AdhocWorkspace();
            memberDeclaration = (MemberDeclarationSyntax)Formatter.Format(memberDeclaration, workspace);
            var sourceText = SourceText.From(memberDeclaration.ToFullString());
            Assert.AreEqual(13, sourceText.Lines.Count);
        }
Example #13
0
        public static void VerifyAnalyzer(string path, DiagnosticAnalyzer diagnosticAnalyzer, ParseOptions options = null,
            params MetadataReference[] additionalReferences)
        {
            var file = new FileInfo(path);
            var parseOptions = GetParseOptionsAlternatives(options, file);

            using (var workspace = new AdhocWorkspace())
            {
                var document = GetDocument(file, GeneratedAssemblyName, workspace, additionalReferences);
                var project = document.Project;

                foreach (var parseOption in parseOptions)
                {
                    if (parseOption != null)
                    {
                        project = project.WithParseOptions(parseOption);
                    }

                    var compilation = project.GetCompilationAsync().Result;
                    var diagnostics = GetDiagnostics(compilation, diagnosticAnalyzer);
                    var expected = ExpectedIssues(compilation.SyntaxTrees.First()).ToList();

                    foreach (var diagnostic in diagnostics)
                    {
                        var line = diagnostic.GetLineNumberToReport();
                        expected.Should().Contain(line);
                        expected.Remove(line);
                    }

                    expected.Should().BeEquivalentTo(Enumerable.Empty<int>());
                }
            }
        }
Example #14
0
		internal static Document CreateDocument(string code, string fileName,
			Func<Solution, ProjectId, Solution> modifySolution)
		{
			var projectName = "Test";
			var projectId = ProjectId.CreateNewId(projectName);

			var solution = new AdhocWorkspace()
				 .CurrentSolution
				 .AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location))
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location))
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location));

			var documentId = DocumentId.CreateNewId(projectId);
			solution = solution.AddDocument(documentId, fileName, SourceText.From(code));

			if(modifySolution != null)
			{
				solution = modifySolution(solution, projectId);
			}

			return solution.GetProject(projectId).Documents.First();
		}
        public void Should_RewriteOneDocument()
        {
            // arrange
            const string sourceCode = "class SampleClass{}";
            SyntaxNode node = CSharpSyntaxTree.ParseText(sourceCode).GetRoot();

            var workspace = new AdhocWorkspace();
            var project = workspace.AddProject("foo.dll", LanguageNames.CSharp);
            string documentPath = "c:\\helloworld.cs";
            DocumentInfo documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "HelloWorld.cs",
                filePath: documentPath);
            Document document = workspace.AddDocument(documentInfo);

            _auditVariablesRewriterMock.Rewrite(Arg.Any<string>(), documentPath, Arg.Any<SyntaxNode>()).
                Returns(new RewrittenDocument(node.SyntaxTree, null, false));

            // act
            RewriteResult result = _solutionRewriter.RewriteAllClasses(workspace.CurrentSolution.Projects);

            // assert
            Assert.That(result.Items.Count, Is.EqualTo(1));
            Assert.That(result.Items.Keys.First().Id, Is.EqualTo(project.Id));

            Assert.That(result.Items.Values.First().Count, Is.EqualTo(1));
        }
        public async Task UpdaterService()
        {
            var workspace = new AdhocWorkspace(TestHostServices.CreateHostServices());
            workspace.Options = workspace.Options.WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1);

            var analyzerReference = new AnalyzerFileReference(typeof(object).Assembly.Location, new NullAssemblyAnalyzerLoader());
            var service = CreateRemoteHostClientService(workspace, SpecializedCollections.SingletonEnumerable<AnalyzerReference>(analyzerReference));

            service.Enable();

            // make sure client is ready
            var client = await service.GetRemoteHostClientAsync(CancellationToken.None);

            // add solution
            workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));

            // TODO: use waiter to make sure workspace events and updater is ready.
            //       this delay is temporary until I set all .Next unit test hardness to setup correctly
            await Task.Delay(TimeSpan.FromSeconds(1));

            // checksum should already exist
            SolutionStateChecksums checksums;
            Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out checksums));

            service.Disable();
        }
        public async Task UpdaterService()
        {
            var workspace = new AdhocWorkspace(TestHostServices.CreateHostServices());
            workspace.Options = workspace.Options.WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1);

            var analyzerReference = new AnalyzerFileReference(typeof(object).Assembly.Location, new NullAssemblyAnalyzerLoader());
            var service = CreateRemoteHostClientService(workspace, SpecializedCollections.SingletonEnumerable<AnalyzerReference>(analyzerReference));

            service.Enable();

            // make sure client is ready
            var client = await service.GetRemoteHostClientAsync(CancellationToken.None);

            // add solution
            workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));

            // TODO: use waiter to make sure workspace events and updater is ready.
            //       this delay is temporary until I set all .Next unit test hardness to setup correctly
            await Task.Delay(TimeSpan.FromSeconds(1));

            var checksumService = workspace.Services.GetService<ISolutionChecksumService>();

            Checksum checksum;
            using (var scope = await checksumService.CreateChecksumAsync(workspace.CurrentSolution, CancellationToken.None))
            {
                // create solution checksum and hold onto the checksum and let it go
                checksum = scope.SolutionChecksum.Checksum;
            }

            // there should be one held in memory by solution checksum updator
            var solutionObject = checksumService.GetChecksumObject(checksum, CancellationToken.None);
            Assert.Equal(solutionObject.Checksum, checksum);

            service.Disable();
        }
        private Workspace CreateWorkspace(string[] sources, string language = LanguageNames.CSharp)
        {
            string fileExtension = language == LanguageNames.CSharp ? CSharpFileExtension : VBFileExtension;
            var projectId = ProjectId.CreateNewId(TestProjectName);

            var workspace = new AdhocWorkspace();

            var solution = workspace
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .AddMetadataReferences(projectId, GetSolutionMetadataReferences());

            int count = 0;
            foreach (var source in sources)
            {
                var fileName = FileNamePrefix + count + fileExtension;
                var documentId = DocumentId.CreateNewId(projectId, fileName);
                solution = solution.AddDocument(documentId, fileName, SourceText.From(source));
                count++;
            }

            workspace.TryApplyChanges(solution);

            return workspace;
        }
        public RoslynGenerator(Job job)
        {
            _namespace = job.DestinationNamespace;
            _customAnnotations = job.CustomAnnotations;
            _nullableClasses = job.NullableClasses;

            _workspace = new AdhocWorkspace();
            _generator = SyntaxGenerator.GetGenerator(_workspace, LanguageNames.CSharp);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CsvCompilerModule"/> class.
 /// </summary>
 public CSharpCompilerModule(Bootstrapper bootstrapper)
     : base(bootstrapper)
 {
     compiler = new CSharpCompiler();
     workspace = new AdhocWorkspace();
     project = workspace.AddProject("CSharpProject", LanguageNames.CSharp);
     document = project.AddDocument("current", "");
     context = new CompilationContext(workspace, document);
 }
        public void Setup()
        {
            _solutionCoverageEngineMock = Substitute.For<ISolutionCoverageEngine>();
            _coverageStoreMock = Substitute.For<ICoverageStore>();

            Workspace workspace = new AdhocWorkspace();
            _sut = new VsSolutionTestCoverage(workspace,
                _solutionCoverageEngineMock,
                _coverageStoreMock);
        }
 public static Solution GetSolutionFromText(string text)
 {
     using (var workspace = new AdhocWorkspace())
     {
         return workspace.CurrentSolution.AddProject("foo", "foo.dll", LanguageNames.CSharp)
             .AddMetadataReference(MetadataReference.CreateFromFile(typeof (object).Assembly.Location))
             .AddDocument("foo.cs", text)
             .Project
             .Solution;
     }
 }
Example #23
0
 public static void VerifyNoExceptionThrown(string path,
     IEnumerable<DiagnosticAnalyzer> diagnosticAnalyzers)
 {
     using (var workspace = new AdhocWorkspace())
     {
         var document = GetDocument(path, GeneratedAssemblyName, workspace);
         var compilation = document.Project.GetCompilationAsync().Result;
         var diagnostics = GetAllDiagnostics(compilation, diagnosticAnalyzers);
         VerifyNoExceptionThrown(diagnostics);
     }
 }
 public static Solution GetSolutionWithEmptyFile()
 {
     using (var workspace = new AdhocWorkspace())
     {
         return workspace.CurrentSolution.AddProject("foo", "foo.dll", LanguageNames.CSharp)
             .AddMetadataReference(SystemMetadataReference)
             .AddDocument("foo.cs", string.Empty)
             .Project
             .Solution;
     }
 }
Example #25
0
        private Document CreateSolutionDocument(string sourceText)
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var solution = new AdhocWorkspace().CurrentSolution
                    .AddProject(pid, "test", "test", LanguageNames.CSharp)
                    .AddMetadataReference(pid, TestReferences.NetFx.v4_0_30319.mscorlib)
                    .AddDocument(did, "foo.cs", SourceText.From(sourceText));

            return solution.GetDocument(did);
        }
 public static Solution GetSolutionWithEmptyFile(AnalyzerLanguage language)
 {
     using (var workspace = new AdhocWorkspace())
     {
         var lang = language == AnalyzerLanguage.CSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic;
         return workspace.CurrentSolution.AddProject("foo", "foo.dll", lang)
             .AddMetadataReference(SystemMetadataReference)
             .AddDocument($"foo.{language.GetFileExtension()}", string.Empty)
             .Project
             .Solution;
     }
 }
Example #27
0
        public TestHelper(string source)
        {
            Workspace = new AdhocWorkspace();

            string projName = "NewProject";
            var projectId = ProjectId.CreateNewId();
            var versionStamp = VersionStamp.Create();
            var projectInfo = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
            var newProject = Workspace.AddProject(projectInfo);
            var sourceText = SourceText.From(source);
            Document = Workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText);
        }
        public async Task TestCodeGeneration(string resourceBaseName, Language language)
        {
            var inputResourceName = "BrightstarDB.CodeGeneration.Tests.GeneratorTestsResources." + resourceBaseName + "Input_" + language.ToString() + ".txt";
            var outputResourceName = "BrightstarDB.CodeGeneration.Tests.GeneratorTestsResources." + resourceBaseName + "Output_" + language.ToString() + ".txt";

            using (var inputStream = this.GetType().Assembly.GetManifestResourceStream(inputResourceName))
            using (var outputStream = this.GetType().Assembly.GetManifestResourceStream(outputResourceName))
            using (var outputStreamReader = new StreamReader(outputStream))
            {
                var workspace = new AdhocWorkspace();
                var projectId = ProjectId.CreateNewId();
                var versionStamp = VersionStamp.Create();
                var projectInfo = ProjectInfo.Create(
                    projectId,
                    versionStamp,
                    "AdhocProject",
                    "AdhocProject",
                    language.ToSyntaxGeneratorLanguageName(),
                    metadataReferences: new[]
                    {
                        MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(BrightstarException).Assembly.Location)
                    });
                var project = workspace.AddProject(projectInfo);
                workspace.AddDocument(projectId, "Source.cs", SourceText.From(inputStream));
                var solution = workspace.CurrentSolution;

                var results = await Generator
                    .GenerateAsync(
                        language,
                        solution,
                        "BrightstarDB.CodeGeneration.Tests",
                        interfacePredicate: x => true);
                var result = results
                    .Aggregate(
                        new StringBuilder(),
                        (current, next) => current.AppendLine(next.ToString()),
                        x => x.ToString());

                var expectedCode = outputStreamReader.ReadToEnd();

                // make sure version changes don't break the tests
                expectedCode = expectedCode.Replace("$VERSION$", typeof(BrightstarException).Assembly.GetName().Version.ToString());

                //// useful when converting generated code to something that can be pasted into an expectation file
                //var sanitisedResult = result.Replace("1.10.0.0", "$VERSION$");
                //System.Diagnostics.Debug.WriteLine(sanitisedResult);

                Assert.AreEqual(expectedCode, result);
            }
        }
Example #29
0
        static (AdhocWorkspace, Project) CreateWorkspace()
        {
            var workspace = new Microsoft.CodeAnalysis.AdhocWorkspace();

            workspace.WorkspaceFailed += (s, e) => { Console.WriteLine(e.Diagnostic); };

            var projName     = "NewProject";
            var projectId    = ProjectId.CreateNewId();
            var versionStamp = VersionStamp.Create();
            var projectInfo  = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
            var newProject   = workspace.AddProject(projectInfo);

            return(workspace, newProject);
        }
Example #30
0
        public static void Verify(string path, DiagnosticAnalyzer diagnosticAnalyzer)
        {
            var file = new FileInfo(path);

            using (var workspace = new AdhocWorkspace())
            {
                var document = workspace.CurrentSolution.AddProject("foo", "foo.dll", LanguageNames.CSharp)
                    .AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                    .AddMetadataReference(MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location))
                    .AddDocument(file.Name, File.ReadAllText(file.FullName, Encoding.UTF8));

                Verify(document.Project, diagnosticAnalyzer);
            }
        }
Example #31
0
        // TODO: VB is totally borked - calls to syntaxGenerator.WithStatements don't seem to add the statements! Will need to look into this at a later date
        //[InlineData("SimpleInterface", Language.VisualBasic)]
        //[InlineData("InterfaceWithGenericMethods", Language.VisualBasic)]
        //[InlineData("GenericInterface", Language.VisualBasic)]
        //[InlineData("InterfaceWithNonMockableMembers", Language.VisualBasic)]
        //[InlineData("PartialInterface", Language.VisualBasic)]
        //[InlineData("InheritingInterface", Language.VisualBasic)]
        public async Task can_generate_simple_mock(string resourceBaseName, Language language)
        {
            var inputResourceName = "PCLMock.UnitTests.CodeGeneration.GeneratorFixtureResources." + resourceBaseName + "Input_" + language.ToString() + ".txt";
            var outputResourceName = "PCLMock.UnitTests.CodeGeneration.GeneratorFixtureResources." + resourceBaseName + "Output_" + language.ToString() + ".txt";

            using (var inputStream = this.GetType().Assembly.GetManifestResourceStream(inputResourceName))
            using (var outputStream = this.GetType().Assembly.GetManifestResourceStream(outputResourceName))
            using (var outputStreamReader = new StreamReader(outputStream))
            {
                var workspace = new AdhocWorkspace();
                var projectId = ProjectId.CreateNewId();
                var versionStamp = VersionStamp.Create();
                var projectInfo = ProjectInfo.Create(
                    projectId,
                    versionStamp,
                    "AdhocProject",
                    "AdhocProject",
                    language.ToSyntaxGeneratorLanguageName(),
                    metadataReferences: new[]
                    {
                        MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(MockBase<>).Assembly.Location)
                    });
                var project = workspace.AddProject(projectInfo);
                workspace.AddDocument(projectId, "Source.cs", SourceText.From(inputStream));
                var solution = workspace.CurrentSolution;

                var results =
                    (await Generator.GenerateMocksAsync(
                        language,
                        solution,
                        x => true,
                        x => "The.Namespace",
                        x => "Mock"));
                var result = results
                    .Single()
                    .ToString();

                var expectedCode = outputStreamReader.ReadToEnd();

                // make sure version changes don't break the tests
                expectedCode = expectedCode.Replace("$VERSION$", typeof(MockBase<>).Assembly.GetName().Version.ToString());

                // useful when converting generated code to something that can be pasted into an expectation file
                var sanitisedResult = result.Replace(typeof(MockBase<>).Assembly.GetName().Version.ToString(), "$VERSION$");

                Assert.Equal(expectedCode, result);
            }
        }