Пример #1
0
        public void GenerateCode_ThrowsIfProjectItemCannotBeFound()
        {
            // Arrange
            var path           = "/Views/Home/Index.cshtml";
            var project        = new TestRazorProject(new RazorProjectItem[] { });
            var razorEngine    = RazorEngine.Create();
            var templateEngine = new RazorTemplateEngine(razorEngine, project);

            // Act & Assert
            var ex = Assert.Throws <InvalidOperationException>(() => templateEngine.GenerateCode(path));

            Assert.Equal($"The item '{path}' could not be found.", ex.Message);
        }
Пример #2
0
        public void GenerateCode_ThrowsIfItemCannotBeFound()
        {
            // Arrange
            var project        = new TestRazorProject(new RazorProjectItem[] { });
            var razorEngine    = RazorEngine.Create();
            var templateEngine = new RazorTemplateEngine(razorEngine, project);

            // Act & Assert
            var ex = Assert.Throws <InvalidOperationException>(
                () => templateEngine.GenerateCode("/does-not-exist.cstml"));

            Assert.Equal("The item '/does-not-exist.cstml' could not be found.", ex.Message);
        }
Пример #3
0
        public void GenerateCode_WithPath()
        {
            // Arrange
            var path           = "/Views/Home/Index.cshtml";
            var projectItem    = new TestRazorProjectItem(path);
            var project        = new TestRazorProject(new[] { projectItem });
            var razorEngine    = RazorEngine.Create();
            var templateEngine = new RazorTemplateEngine(razorEngine, project);

            // Act
            var cSharpDocument = templateEngine.GenerateCode(path);

            // Assert
            Assert.NotNull(cSharpDocument);
            Assert.NotEmpty(cSharpDocument.GeneratedCode);
            Assert.Empty(cSharpDocument.Diagnostics);
        }
        public void Execute_RewritesTagHelpers()
        {
            // Arrange
            var engine = RazorEngine.Create(builder =>
            {
                builder.AddTagHelpers(new[]
                {
                    CreateTagHelperDescriptor(
                        tagName: "form",
                        typeName: "TestFormTagHelper",
                        assemblyName: "TestAssembly"),
                    CreateTagHelperDescriptor(
                        tagName: "input",
                        typeName: "TestInputTagHelper",
                        assemblyName: "TestAssembly"),
                });
            });

            var phase = new DefaultRazorTagHelperBinderPhase()
            {
                Engine = engine,
            };

            var sourceDocument = CreateTestSourceDocument();
            var codeDocument   = RazorCodeDocument.Create(sourceDocument);
            var originalTree   = RazorSyntaxTree.Parse(sourceDocument);

            codeDocument.SetSyntaxTree(originalTree);

            // Act
            phase.Execute(codeDocument);

            // Assert
            var rewrittenTree = codeDocument.GetSyntaxTree();

            Assert.Empty(rewrittenTree.Diagnostics);
            Assert.Equal(3, rewrittenTree.Root.Children.Count);
            var formTagHelper = Assert.IsType <TagHelperBlock>(rewrittenTree.Root.Children[2]);

            Assert.Equal("form", formTagHelper.TagName);
            Assert.Equal(3, formTagHelper.Children.Count);
            var inputTagHelper = Assert.IsType <TagHelperBlock>(formTagHelper.Children[1]);

            Assert.Equal("input", inputTagHelper.TagName);
        }
Пример #5
0
        public void Execute_CanHandleSingleLengthRemoveTagHelperDirective()
        {
            // Arrange
            var engine = RazorEngine.Create(builder =>
            {
                builder.AddTagHelpers(new TagHelperDescriptor[0]);
            });

            var phase = new DefaultRazorTagHelperBinderPhase()
            {
                Engine = engine,
            };
            var expectedDiagnostics = new[]
            {
                RazorDiagnostic.Create(
                    new RazorError(
                        LegacyResources.ParseError_Unterminated_String_Literal,
                        new SourceLocation(17 + Environment.NewLine.Length, 1, 17),
                        length: 1)),
                RazorDiagnostic.Create(
                    new RazorError(
                        Resources.FormatInvalidTagHelperLookupText("\""),
                        new SourceLocation(17 + Environment.NewLine.Length, 1, 17),
                        length: 1))
            };

            var content =
                @"
@removeTagHelper """;
            var sourceDocument = TestRazorSourceDocument.Create(content, fileName: null);
            var codeDocument   = RazorCodeDocument.Create(sourceDocument);
            var originalTree   = RazorSyntaxTree.Parse(sourceDocument);

            codeDocument.SetSyntaxTree(originalTree);

            // Act
            phase.Execute(codeDocument);

            // Assert
            var rewrittenTree  = codeDocument.GetSyntaxTree();
            var directiveValue = rewrittenTree.Root.Children.OfType <Block>().First().Children.Last() as Span;
            var chunkGenerator = Assert.IsType <RemoveTagHelperChunkGenerator>(directiveValue.ChunkGenerator);

            Assert.Equal(expectedDiagnostics, chunkGenerator.Diagnostics);
        }
Пример #6
0
        public void Execute_DirectiveWithError_PreservesDiagnosticsAndRemovesDirectiveNodeFromDocument()
        {
            // Arrange
            var content            = "@custom \"Hello\"";
            var expectedDiagnostic = RazorDiagnostic.Create(new RazorDiagnosticDescriptor("RZ9999", () => "Some diagnostic message.", RazorDiagnosticSeverity.Error), SourceSpan.Undefined);
            var sourceDocument     = TestRazorSourceDocument.Create(content);
            var codeDocument       = RazorCodeDocument.Create(sourceDocument);
            var defaultEngine      = RazorEngine.Create(b =>
            {
                b.AddDirective(DirectiveDescriptor.CreateDirective("custom", DirectiveKind.SingleLine, d => d.AddStringToken()));
            });
            var documentNode = Lower(codeDocument, defaultEngine);

            // Add the diagnostic to the directive node.
            var directiveNode = documentNode.FindDescendantNodes <DirectiveIntermediateNode>().Single();

            directiveNode.Diagnostics.Add(expectedDiagnostic);

            var pass = new DirectiveRemovalOptimizationPass()
            {
                Engine = defaultEngine,
            };

            // Act
            pass.Execute(codeDocument, documentNode);

            // Assert
            var diagnostic = Assert.Single(documentNode.Diagnostics);

            Assert.Equal(expectedDiagnostic, diagnostic);

            Children(documentNode,
                     node => Assert.IsType <NamespaceDeclarationIntermediateNode>(node));
            var @namespace = documentNode.Children[0];

            Children(@namespace,
                     node => Assert.IsType <ClassDeclarationIntermediateNode>(node));
            var @class = @namespace.Children[0];
            var method = SingleChild <MethodDeclarationIntermediateNode>(@class);

            Assert.Empty(method.Children);
        }
Пример #7
0
        public void CreateCodeDocument_ThrowsIfPathCannotBeFound()
        {
            // Arrange
            var projectItem    = new TestRazorProjectItem("/Views/Home/Index.cshtml");
            var project        = new TestRazorProject(new[] { projectItem });
            var razorEngine    = RazorEngine.Create();
            var templateEngine = new RazorTemplateEngine(razorEngine, project)
            {
                Options =
                {
                    ImportsFileName = "MyImport.cshtml",
                }
            };

            // Act & Assert
            var ex = Assert.Throws <InvalidOperationException>(() => templateEngine.CreateCodeDocument("/DoesNotExist.cshtml"));

            // Assert
            Assert.Equal("The item '/DoesNotExist.cshtml' could not be found.", ex.Message);
        }
Пример #8
0
        public void GetImports_CanQueryInformationOnNonExistentFileWithoutImports()
        {
            // Arrange
            var project        = new TestRazorProject();
            var razorEngine    = RazorEngine.Create();
            var templateEngine = new RazorTemplateEngine(razorEngine, project)
            {
                Options =
                {
                    ImportsFileName = "MyImport.cshtml"
                }
            };
            var projectItemToQuery = project.GetItem("/Views/Home/Index.cshtml");

            // Act
            var imports = templateEngine.GetImports(projectItemToQuery);

            // Assert
            Assert.Empty(imports);
        }
Пример #9
0
        public void CreateCodeDocument_WithFileSystemProject_ReturnsCorrectItems()
        {
            // Arrange
            var testFolder = Path.Combine(
                TestProject.GetProjectDirectory(typeof(FileSystemRazorProjectTest)),
                "TestFiles",
                "FileSystemRazorProject");

            var project        = new FileSystemRazorProject(testFolder);
            var razorEngine    = RazorEngine.Create();
            var templateEngine = new RazorTemplateEngine(razorEngine, project)
            {
                Options =
                {
                    ImportsFileName = "_ViewImports.cshtml"
                }
            };

            // Act
            var codeDocument = templateEngine.CreateCodeDocument("/Views/Home/Index.cshtml");

            // Assert
            Assert.Collection(
                codeDocument.Imports,
                item =>
            {
                Assert.Equal(Path.Combine(testFolder, "_ViewImports.cshtml"), item.FilePath);
                Assert.Equal("_ViewImports.cshtml", item.RelativePath);
            },
                item =>
            {
                Assert.Equal(Path.Combine(testFolder, "Views", "_ViewImports.cshtml"), item.FilePath);
                Assert.Equal(Path.Combine("Views", "_ViewImports.cshtml"), item.RelativePath);
            },
                item =>
            {
                Assert.Equal(Path.Combine(testFolder, "Views", "Home", "_ViewImports.cshtml"), item.FilePath);
                Assert.Equal(Path.Combine("Views", "Home", "_ViewImports.cshtml"), item.RelativePath);
            });
        }
        public void Execute_CanHandleSingleLengthTagHelperPrefix()
        {
            // Arrange
            var engine = RazorEngine.Create(builder =>
            {
                builder.AddTagHelpers(new TagHelperDescriptor[0]);
            });

            var phase = new DefaultRazorTagHelperBinderPhase()
            {
                Engine = engine,
            };
            var expectedDiagnostics = new[]
            {
                RazorDiagnosticFactory.CreateParsing_UnterminatedStringLiteral(
                    new SourceSpan(new SourceLocation(17 + Environment.NewLine.Length, 1, 17), contentLength: 1)),
                RazorDiagnosticFactory.CreateParsing_InvalidTagHelperPrefixValue(
                    new SourceSpan(new SourceLocation(17 + Environment.NewLine.Length, 1, 17), contentLength: 1), "tagHelperPrefix", '\"', "\""),
            };

            var content =
                @"
@tagHelperPrefix """;
            var sourceDocument = TestRazorSourceDocument.Create(content, filePath: null);
            var codeDocument   = RazorCodeDocument.Create(sourceDocument);
            var originalTree   = RazorSyntaxTree.Parse(sourceDocument);

            codeDocument.SetSyntaxTree(originalTree);

            // Act
            phase.Execute(codeDocument);

            // Assert
            var rewrittenTree  = codeDocument.GetSyntaxTree();
            var directiveValue = rewrittenTree.Root.Children.OfType <Block>().First().Children.Last() as Span;
            var chunkGenerator = Assert.IsType <TagHelperPrefixDirectiveChunkGenerator>(directiveValue.ChunkGenerator);

            Assert.Equal(expectedDiagnostics, chunkGenerator.Diagnostics);
        }
Пример #11
0
        public void GetImportItems_WithPath_ReturnsAllImportsForFile()
        {
            // Arrange
            var expected       = new[] { "/Views/Home/MyImport.cshtml", "/Views/MyImport.cshtml", "/MyImport.cshtml" };
            var project        = new TestRazorProject();
            var razorEngine    = RazorEngine.Create();
            var templateEngine = new RazorTemplateEngine(razorEngine, project)
            {
                Options =
                {
                    ImportsFileName = "MyImport.cshtml"
                }
            };

            // Act
            var imports = templateEngine.GetImportItems("/Views/Home/Index.cshtml");

            // Assert
            var paths = imports.Select(i => i.FilePath);

            Assert.Equal(expected, paths);
        }
Пример #12
0
        public void CreateCodeDocument_NullImportFileName_IncludesDefaultImportIfNotNull()
        {
            // Arrange
            var projectItem    = new TestRazorProjectItem("/Views/Home/Index.cshtml");
            var project        = new TestRazorProject(new[] { projectItem });
            var razorEngine    = RazorEngine.Create();
            var defaultImport  = RazorSourceDocument.ReadFrom(new MemoryStream(), "Default.cshtml");
            var templateEngine = new RazorTemplateEngine(razorEngine, project)
            {
                Options =
                {
                    DefaultImports = defaultImport,
                }
            };

            // Act
            var codeDocument = templateEngine.CreateCodeDocument(projectItem);

            // Assert
            Assert.Collection(codeDocument.Imports,
                              import => Assert.Same(defaultImport, import));
        }
        public void Execute_NoopsWhenNoTagHelperFeature()
        {
            // Arrange
            var engine = RazorEngine.Create();
            var phase  = new DefaultRazorTagHelperBinderPhase()
            {
                Engine = engine,
            };
            var sourceDocument = CreateTestSourceDocument();
            var codeDocument   = RazorCodeDocument.Create(sourceDocument);
            var originalTree   = RazorSyntaxTree.Parse(sourceDocument);

            codeDocument.SetSyntaxTree(originalTree);

            // Act
            phase.Execute(codeDocument);

            // Assert
            var outputTree = codeDocument.GetSyntaxTree();

            Assert.Empty(outputTree.Diagnostics);
            Assert.Same(originalTree, outputTree);
        }
Пример #14
0
        public void GetImports_CanQueryInformationOnNonExistentFileWithImports()
        {
            // Arrange
            var path           = "/Views/Home/MyImport.cshtml";
            var projectItem    = new TestRazorProjectItem(path);
            var project        = new TestRazorProject(new[] { projectItem });
            var razorEngine    = RazorEngine.Create();
            var templateEngine = new RazorTemplateEngine(razorEngine, project)
            {
                Options =
                {
                    ImportsFileName = "MyImport.cshtml"
                }
            };
            var projectItemToQuery = project.GetItem("/Views/Home/Index.cshtml");

            // Act
            var imports = templateEngine.GetImports(projectItemToQuery);

            // Assert
            var import = Assert.Single(imports);

            Assert.Equal(projectItem.FilePath, import.FilePath);
        }
Пример #15
0
        public void CreateCodeDocument_IncludesImportsIfFileIsPresent()
        {
            // Arrange
            var projectItem    = new TestRazorProjectItem("/Views/Home/Index.cshtml");
            var import1        = new TestRazorProjectItem("/MyImport.cshtml");
            var import2        = new TestRazorProjectItem("/Views/Home/MyImport.cshtml");
            var project        = new TestRazorProject(new[] { import1, import2, projectItem });
            var razorEngine    = RazorEngine.Create();
            var templateEngine = new RazorTemplateEngine(razorEngine, project)
            {
                Options =
                {
                    ImportsFileName = "MyImport.cshtml",
                }
            };

            // Act
            var codeDocument = templateEngine.CreateCodeDocument("/Views/Home/Index.cshtml");

            // Assert
            Assert.Collection(codeDocument.Imports,
                              import => Assert.Equal("/MyImport.cshtml", import.FilePath),
                              import => Assert.Equal("/Views/Home/MyImport.cshtml", import.FilePath));
        }
        private DocumentIntermediateNode Lower(
            RazorCodeDocument codeDocument,
            Action <IRazorEngineBuilder> builder         = null,
            IEnumerable <TagHelperDescriptor> tagHelpers = null,
            bool designTime = false)
        {
            tagHelpers = tagHelpers ?? new TagHelperDescriptor[0];

            Action <IRazorEngineBuilder> configureEngine = b =>
            {
                builder?.Invoke(b);

                FunctionsDirective.Register(b);
                SectionDirective.Register(b);
                b.AddTagHelpers(tagHelpers);
            };

            var engine = designTime ? RazorEngine.CreateDesignTime(configureEngine) : RazorEngine.Create(configureEngine);

            for (var i = 0; i < engine.Phases.Count; i++)
            {
                var phase = engine.Phases[i];
                phase.Execute(codeDocument);

                if (phase is IRazorIntermediateNodeLoweringPhase)
                {
                    break;
                }
            }

            var documentNode = codeDocument.GetDocumentIntermediateNode();

            Assert.NotNull(documentNode);

            return(documentNode);
        }