コード例 #1
0
        public void OnProvidersExecuting_ValidatesChecksum_SkipsValidationWhenMainSourceMissing()
        {
            // Arrange
            var descriptors = new[]
            {
                CreateVersion_2_1_Descriptor("/Pages/About.cshtml", metadata: new object[]
                {
                    new RazorSourceChecksumAttribute("SHA1", GetChecksum("some content"), "/Pages/About.cshtml"),
                    new RazorSourceChecksumAttribute("SHA1", GetChecksum("some import"), "/Pages/_ViewImports.cshtml"),
                }),
            };

            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem("/Pages/_ViewImports.cshtml", "some other import"));

            var provider = CreateProvider(descriptors: descriptors, fileSystem: fileSystem);
            var context  = new PageRouteModelProviderContext();

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(
                context.RouteModels,
                result => Assert.Equal("/Pages/About.cshtml", result.RelativePath));
        }
コード例 #2
0
        public void OnProvidersExecuting_DoesNotAddPagesUnderAreas_WhenFeatureIsDisabled()
        {
            // Arrange
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem("/Areas/Products/Pages/Manage/Categories.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/Areas/Products/Pages/Index.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/Areas/Products/Pages/List.cshtml", "@page \"{sortOrder?}\""));
            fileSystem.Add(new TestRazorProjectItem("/Areas/Products/Pages/_ViewStart.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/Pages/About.cshtml", "@page"));

            var optionsManager = Options.Create(new RazorPagesOptions {
                AllowAreas = false
            });
            var provider = new RazorProjectPageRouteModelProvider(fileSystem, optionsManager, NullLoggerFactory.Instance);
            var context  = new PageRouteModelProviderContext();

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(context.RouteModels,
                              model =>
            {
                Assert.Equal("/Pages/About.cshtml", model.RelativePath);
                Assert.Equal("/About", model.ViewEnginePath);
                Assert.Collection(model.Selectors,
                                  selector => Assert.Equal("About", selector.AttributeRouteModel.Template));
            });
        }
コード例 #3
0
        private static VirtualRazorProjectFileSystem GetVirtualFileSystem(GeneratorExecutionContext context, IReadOnlyList <RazorInputItem> razorFiles, IReadOnlyList <RazorInputItem> cshtmlFiles)
        {
            var fileSystem = new VirtualRazorProjectFileSystem();

            for (var i = 0; i < razorFiles.Count; i++)
            {
                var item = razorFiles[i];
                fileSystem.Add(new SourceGeneratorProjectItem(
                                   basePath: "/",
                                   filePath: item.NormalizedPath,
                                   relativePhysicalPath: item.RelativePath,
                                   fileKind: FileKinds.Component,
                                   item.AdditionalText,
                                   cssScope: item.CssScope,
                                   context: context));
            }

            for (var i = 0; i < cshtmlFiles.Count; i++)
            {
                var item = cshtmlFiles[i];
                fileSystem.Add(new SourceGeneratorProjectItem(
                                   basePath: "/",
                                   filePath: item.NormalizedPath,
                                   relativePhysicalPath: item.RelativePath,
                                   fileKind: FileKinds.Legacy,
                                   item.AdditionalText,
                                   cssScope: item.CssScope,
                                   context: context));
            }

            return(fileSystem);
        }
コード例 #4
0
        public void GetCompilationFailedResult_ReadsContentFromSourceDocuments()
        {
            // Arrange
            var viewPath    = "/Views/Home/Index.cshtml";
            var fileContent =
                @"
@if (User.IsAdmin)
{
    <span>
}
</span>";

            var razorEngine = RazorEngine.Create();
            var fileSystem  = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem(viewPath, fileContent));
            var templateEngine = new MvcRazorTemplateEngine(razorEngine, fileSystem);

            var codeDocument = templateEngine.CreateCodeDocument(viewPath);

            // Act
            var csharpDocument    = templateEngine.GenerateCode(codeDocument);
            var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics);

            // Assert
            var failure = Assert.Single(compilationResult.CompilationFailures);

            Assert.Equal(fileContent, failure.SourceFileContent);
        }
コード例 #5
0
        public void OnProvidersExecuting_ReturnsPagesWithPageDirective()
        {
            // Arrange
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem("/Pages/Home.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/Pages/Test.cshtml", "Hello world"));

            var optionsManager = Options.Create(new RazorPagesOptions());

            optionsManager.Value.RootDirectory = "/";
            var provider = new RazorProjectPageRouteModelProvider(fileSystem, optionsManager, NullLoggerFactory.Instance);
            var context  = new PageRouteModelProviderContext();

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(context.RouteModels,
                              model =>
            {
                Assert.Equal("/Pages/Home.cshtml", model.RelativePath);
                Assert.Equal("/Pages/Home", model.ViewEnginePath);
                Assert.Collection(model.Selectors,
                                  selector => Assert.Equal("Pages/Home", selector.AttributeRouteModel.Template));
                Assert.Collection(model.RouteValues.OrderBy(k => k.Key),
                                  kvp =>
                {
                    Assert.Equal("page", kvp.Key);
                    Assert.Equal("/Pages/Home", kvp.Value);
                });
            });
        }
コード例 #6
0
        public void OnProvidersExecuting_AllowsRouteTemplateWithOverridePattern()
        {
            // Arrange
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem("/Index.cshtml", "@page \"/custom-route\""));

            var optionsManager = Options.Create(new RazorPagesOptions());

            optionsManager.Value.RootDirectory = "/";
            var provider = new RazorProjectPageRouteModelProvider(fileSystem, optionsManager, NullLoggerFactory.Instance);
            var context  = new PageRouteModelProviderContext();

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(
                context.RouteModels,
                model =>
            {
                Assert.Equal("/Index.cshtml", model.RelativePath);
                Assert.Equal("/Index", model.ViewEnginePath);
                Assert.Collection(
                    model.Selectors,
                    selector => Assert.Equal("custom-route", selector.AttributeRouteModel.Template));
            });
        }
コード例 #7
0
        public void OnProvidersExecuting_DoesNotAddPageDirectivesIfItAlreadyExists()
        {
            // Arrange
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem("/Pages/Home.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/Pages/Test.cshtml", "@page"));

            var optionsManager = Options.Create(new RazorPagesOptions());

            optionsManager.Value.RootDirectory = "/";
            var provider  = new RazorProjectPageRouteModelProvider(fileSystem, optionsManager, NullLoggerFactory.Instance);
            var context   = new PageRouteModelProviderContext();
            var pageModel = new PageRouteModel("/Pages/Test.cshtml", "/Pages/Test");

            context.RouteModels.Add(pageModel);

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(context.RouteModels,
                              model => Assert.Same(pageModel, model),
                              model =>
            {
                Assert.Equal("/Pages/Home.cshtml", model.RelativePath);
                Assert.Equal("/Pages/Home", model.ViewEnginePath);
                Assert.Collection(model.Selectors,
                                  selector => Assert.Equal("Pages/Home", selector.AttributeRouteModel.Template));
            });
        }
コード例 #8
0
        private static RazorProjectEngine GetDeclarationProjectEngine(
            SourceGeneratorProjectItem item,
            IEnumerable <SourceGeneratorProjectItem> imports,
            RazorSourceGenerationOptions razorSourceGeneratorOptions)
        {
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(item);
            foreach (var import in imports)
            {
                fileSystem.Add(import);
            }

            var discoveryProjectEngine = RazorProjectEngine.Create(razorSourceGeneratorOptions.Configuration, fileSystem, b =>
            {
                b.Features.Add(new DefaultTypeNameFeature());
                b.Features.Add(new ConfigureRazorCodeGenerationOptions(options =>
                {
                    options.SuppressPrimaryMethodBody = true;
                    options.SuppressChecksum          = true;
                }));

                b.SetRootNamespace(razorSourceGeneratorOptions.RootNamespace);

                CompilerFeatures.Register(b);
                RazorExtensions.Register(b);

                b.SetCSharpLanguageVersion(razorSourceGeneratorOptions.CSharpLanguageVersion);
            });

            return(discoveryProjectEngine);
        }
コード例 #9
0
    public void GetCompilationFailedResult_ReadsRazorErrorsFromPage()
    {
        // Arrange
        var viewPath = "/Views/Home/Index.cshtml";

        var fileSystem  = new VirtualRazorProjectFileSystem();
        var projectItem = new TestRazorProjectItem(viewPath, "<span name=\"@(User.Id\">");

        var razorEngine  = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem).Engine;
        var codeDocument = GetCodeDocument(projectItem);

        // Act
        razorEngine.Process(codeDocument);
        var csharpDocument    = codeDocument.GetCSharpDocument();
        var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics);

        // Assert
        var failure = Assert.Single(compilationResult.CompilationFailures);

        Assert.Equal(viewPath, failure.SourceFilePath);
        var orderedMessages = failure.Messages.OrderByDescending(messages => messages.Message);

        Assert.Collection(orderedMessages,
                          message => Assert.StartsWith(
                              @"Unterminated string literal.",
                              message.Message),
                          message => Assert.StartsWith(
                              @"The explicit expression block is missing a closing "")"" character.",
                              message.Message));
    }
コード例 #10
0
        public void GetCompilationFailedResult_ReadsRazorErrorsFromPage()
        {
            // Arrange
            var viewPath    = "/Views/Home/Index.cshtml";
            var razorEngine = RazorEngine.Create();

            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem(viewPath, "<span name=\"@(User.Id\">"));

            var templateEngine = new MvcRazorTemplateEngine(razorEngine, fileSystem);
            var codeDocument   = templateEngine.CreateCodeDocument(viewPath);

            // Act
            var csharpDocument    = templateEngine.GenerateCode(codeDocument);
            var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics);

            // Assert
            var failure = Assert.Single(compilationResult.CompilationFailures);

            Assert.Equal(viewPath, failure.SourceFilePath);
            Assert.Collection(failure.Messages,
                              message => Assert.StartsWith(
                                  @"Unterminated string literal.",
                                  message.Message),
                              message => Assert.StartsWith(
                                  @"The explicit expression block is missing a closing "")"" character.",
                                  message.Message));
        }
コード例 #11
0
        public void OnProvidersExecuting_DiscoversFilesUnderBasePath()
        {
            // Arrange
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem("/Pages/Index.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/Pages/_Layout.cshtml", ""));
            fileSystem.Add(new TestRazorProjectItem("/NotPages/Index.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/NotPages/_Layout.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/Index.cshtml", "@page"));

            var optionsManager = Options.Create(new RazorPagesOptions());

            optionsManager.Value.RootDirectory = "/Pages";
            var provider = new RazorProjectPageRouteModelProvider(fileSystem, optionsManager, NullLoggerFactory.Instance);
            var context  = new PageRouteModelProviderContext();

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(context.RouteModels,
                              model =>
            {
                Assert.Equal("/Pages/Index.cshtml", model.RelativePath);
            });
        }
コード例 #12
0
        public void OnProvidersExecuting_DoesNotAddAreaAndNonAreaRoutesForAPage()
        {
            // Arrange
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem("/Areas/Products/Pages/Categories.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/About.cshtml", "@page"));
            // We shouldn't add a route for the following paths.
            fileSystem.Add(new TestRazorProjectItem("/Areas/Products/Categories.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/Areas/Home.cshtml", "@page"));

            var optionsManager = Options.Create(new RazorPagesOptions
            {
                RootDirectory = "/",
                AllowAreas    = true,
            });
            var provider = new RazorProjectPageRouteModelProvider(fileSystem, optionsManager, NullLoggerFactory.Instance);
            var context  = new PageRouteModelProviderContext();

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(context.RouteModels,
                              model =>
            {
                Assert.Equal("/Areas/Products/Pages/Categories.cshtml", model.RelativePath);
                Assert.Equal("/Categories", model.ViewEnginePath);
                Assert.Collection(model.Selectors,
                                  selector => Assert.Equal("Products/Categories", selector.AttributeRouteModel.Template));
                Assert.Collection(model.RouteValues.OrderBy(k => k.Key),
                                  kvp =>
                {
                    Assert.Equal("area", kvp.Key);
                    Assert.Equal("Products", kvp.Value);
                },
                                  kvp =>
                {
                    Assert.Equal("page", kvp.Key);
                    Assert.Equal("/Categories", kvp.Value);
                });
            },
                              model =>
            {
                Assert.Equal("/About.cshtml", model.RelativePath);
                Assert.Equal("/About", model.ViewEnginePath);
                Assert.Collection(model.Selectors,
                                  selector => Assert.Equal("About", selector.AttributeRouteModel.Template));
                Assert.Collection(model.RouteValues.OrderBy(k => k.Key),
                                  kvp =>
                {
                    Assert.Equal("page", kvp.Key);
                    Assert.Equal("/About", kvp.Value);
                });
            });
        }
コード例 #13
0
        public void OnProvidersExecuting_CachesViewStartFactories()
        {
            // Arrange
            var descriptor = new PageActionDescriptor
            {
                RelativePath      = "/Home/Path1/File.cshtml",
                ViewEnginePath    = "/Home/Path1/File.cshtml",
                FilterDescriptors = new FilterDescriptor[0],
            };

            var loader = new Mock <IPageLoader>();

            loader
            .Setup(l => l.Load(It.IsAny <PageActionDescriptor>()))
            .Returns(CreateCompiledPageActionDescriptor(descriptor, pageType: typeof(PageWithModel)));

            var razorPageFactoryProvider = new Mock <IRazorPageFactoryProvider>();

            Func <IRazorPage> factory1 = () => null;
            Func <IRazorPage> factory2 = () => null;

            razorPageFactoryProvider
            .Setup(f => f.CreateFactory("/Home/Path1/_ViewStart.cshtml"))
            .Returns(new RazorPageFactoryResult(new CompiledViewDescriptor(), factory1));
            razorPageFactoryProvider
            .Setup(f => f.CreateFactory("/_ViewStart.cshtml"))
            .Returns(new RazorPageFactoryResult(new CompiledViewDescriptor(), factory2));

            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem("/Home/Path1/_ViewStart.cshtml", "content1"));
            fileSystem.Add(new TestRazorProjectItem("/_ViewStart.cshtml", "content2"));

            var invokerProvider = CreateInvokerProvider(
                loader.Object,
                CreateActionDescriptorCollection(descriptor),
                razorPageFactoryProvider: razorPageFactoryProvider.Object,
                fileSystem: fileSystem);

            var context = new ActionInvokerProviderContext(new ActionContext()
            {
                ActionDescriptor = descriptor,
                HttpContext      = new DefaultHttpContext(),
                RouteData        = new RouteData(),
            });

            // Act
            invokerProvider.OnProvidersExecuting(context);

            // Assert
            Assert.NotNull(context.Result);
            var actionInvoker = Assert.IsType <PageActionInvoker>(context.Result);
            var entry         = actionInvoker.CacheEntry;

            Assert.Equal(new[] { factory2, factory1 }, entry.ViewStartFactories);
        }
コード例 #14
0
    public void EnumerateItems_WithNoFilesInRoot_ReturnsEmptySequence()
    {
        // Arrange
        var projectSystem = new VirtualRazorProjectFileSystem();

        // Act
        var result = projectSystem.EnumerateItems("/");

        // Assert
        Assert.Empty(result);
    }
コード例 #15
0
    public void GetItem_ReturnsNotFound_WhenNestedDirectoryDoesNotExist()
    {
        // Arrange
        var projectSystem = new VirtualRazorProjectFileSystem();

        // Act
        var actual = projectSystem.GetItem("/subDirectory/dir3/file.cshtml", fileKind: null);

        // Assert
        Assert.False(actual.Exists);
    }
コード例 #16
0
        public RazorIntegrationTestBase()
        {
            AdditionalSyntaxTrees = new List <SyntaxTree>();
            AdditionalRazorItems  = new List <RazorProjectItem>();

            Configuration    = BlazorExtensionInitializer.DefaultConfiguration;
            FileSystem       = new VirtualRazorProjectFileSystem();
            WorkingDirectory = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ArbitraryWindowsPath : ArbitraryMacLinuxPath;

            DefaultBaseNamespace = "Test"; // Matches the default working directory
            DefaultFileName      = "TestComponent.cshtml";
        }
コード例 #17
0
    public void GetItem_ReturnsNotFound_IfFileDoesNotExistInRoot()
    {
        // Arrange
        var path          = "/root-file.cshtml";
        var projectSystem = new VirtualRazorProjectFileSystem();

        // Act
        projectSystem.Add(new TestRazorProjectItem("/different-file.cshtml"));
        var result = projectSystem.GetItem(path, fileKind: null);

        // Assert
        Assert.False(result.Exists);
    }
コード例 #18
0
    public void GetItem_ReturnsItemAddedToNestedDirectory(string path)
    {
        // Arrange
        var projectSystem = new VirtualRazorProjectFileSystem();
        var projectItem   = new TestRazorProjectItem(path);

        // Act
        projectSystem.Add(projectItem);
        var actual = projectSystem.GetItem(path, fileKind: null);

        // Assert
        Assert.Same(projectItem, actual);
    }
コード例 #19
0
        public void GetCompilationFailedResult_ReadsContentFromImports()
        {
            // Arrange
            var viewPath       = "/Views/Home/Index.cshtml";
            var importsPath    = "/Views/_MyImports.cshtml";
            var fileContent    = "@ ";
            var importsContent = "@(abc";

            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem(viewPath, fileContent));
            fileSystem.Add(new TestRazorProjectItem("/Views/_MyImports.cshtml", importsContent));

            var razorEngine    = RazorEngine.Create();
            var templateEngine = new MvcRazorTemplateEngine(razorEngine, fileSystem)
            {
                Options =
                {
                    ImportsFileName = "_MyImports.cshtml",
                }
            };
            var codeDocument = templateEngine.CreateCodeDocument(viewPath);

            // Act
            var csharpDocument    = templateEngine.GenerateCode(codeDocument);
            var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics);

            // Assert
            Assert.Collection(
                compilationResult.CompilationFailures,
                failure =>
            {
                Assert.Equal(viewPath, failure.SourceFilePath);
                Assert.Collection(failure.Messages,
                                  message =>
                {
                    Assert.Equal(@"A space or line break was encountered after the ""@"" character.  Only valid identifiers, keywords, comments, ""("" and ""{"" are valid at the start of a code block and they must occur immediately following ""@"" with no space in between.",
                                 message.Message);
                });
            },
                failure =>
            {
                Assert.Equal(importsPath, failure.SourceFilePath);
                Assert.Collection(failure.Messages,
                                  message =>
                {
                    Assert.Equal(@"The explicit expression block is missing a closing "")"" character.  Make sure you have a matching "")"" character for all the ""("" characters within this block, and that none of the "")"" characters are being interpreted as markup.",
                                 message.Message);
                });
            });
        }
コード例 #20
0
    public void EnumerateItems_ForNonExistentDirectory_ReturnsEmptySequence()
    {
        // Arrange
        var projectSystem = new VirtualRazorProjectFileSystem();

        projectSystem.Add(new TestRazorProjectItem("/subDirectory/dir2/file1.cshtml"));
        projectSystem.Add(new TestRazorProjectItem("/file2.cshtml"));

        // Act
        var result = projectSystem.EnumerateItems("/dir3");

        // Assert
        Assert.Empty(result);
    }
コード例 #21
0
        public RazorIntegrationTestBase()
        {
            AdditionalSyntaxTrees = new List <SyntaxTree>();
            AdditionalRazorItems  = new List <RazorProjectItem>();

            BaseCompilation  = DefaultBaseCompilation;
            Configuration    = RazorConfiguration.Default;
            FileSystem       = new VirtualRazorProjectFileSystem();
            PathSeparator    = Path.DirectorySeparatorChar.ToString();
            WorkingDirectory = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ArbitraryWindowsPath : ArbitraryMacLinuxPath;

            DefaultRootNamespace = "Test"; // Matches the default working directory
            DefaultFileName      = "TestComponent.cshtml";
        }
コード例 #22
0
    public void GetItem_ReturnsItemAddedToRoot()
    {
        // Arrange
        var path          = "/root-file.cshtml";
        var projectSystem = new VirtualRazorProjectFileSystem();
        var projectItem   = new TestRazorProjectItem(path);

        // Act
        projectSystem.Add(projectItem);
        var actual = projectSystem.GetItem(path, fileKind: null);

        // Assert
        Assert.Same(projectItem, actual);
    }
コード例 #23
0
        private VirtualRazorProjectFileSystem GetVirtualRazorProjectSystem(SourceItem[] inputItems)
        {
            var project = new VirtualRazorProjectFileSystem();

            foreach (var item in inputItems)
            {
                var projectItem = new DefaultRazorProjectItem(
                    basePath: "/",
                    filePath: item.FilePath,
                    relativePhysicalPath: item.RelativePhysicalPath,
                    file: new FileInfo(item.SourcePath));

                project.Add(projectItem);
            }

            return(project);
        }
コード例 #24
0
        private TestCompiledPageRouteModelProvider CreateProvider(
            RazorPagesOptions options = null,
            IList <CompiledViewDescriptor> descriptors = null,
            VirtualRazorProjectFileSystem fileSystem   = null)
        {
            options    = options ?? new RazorPagesOptions();
            fileSystem = fileSystem ?? new VirtualRazorProjectFileSystem();
            var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem);

            var provider = new TestCompiledPageRouteModelProvider(
                new ApplicationPartManager(),
                Options.Create(options),
                projectEngine,
                NullLogger <CompiledPageRouteModelProvider> .Instance);

            provider.Descriptors.AddRange(descriptors ?? Array.Empty <CompiledViewDescriptor>());

            return(provider);
        }
コード例 #25
0
        public RazorIntegrationTestBase(ITestOutputHelper output)
        {
            _output.Value = output;

            AdditionalSyntaxTrees = new List <SyntaxTree>();
            AdditionalRazorItems  = new List <RazorProjectItem>();

            Configuration    = RazorConfiguration.Create(RazorLanguageVersion.Latest, "MVC-3.0", Array.Empty <RazorExtension>());
            FileKind         = FileKinds.Component; // Treat input files as components by default.
            FileSystem       = new VirtualRazorProjectFileSystem();
            PathSeparator    = Path.DirectorySeparatorChar.ToString();
            WorkingDirectory = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ArbitraryWindowsPath : ArbitraryMacLinuxPath;

            // Many of the rendering tests include line endings in the output.
            LineEnding = "\n";
            NormalizeSourceLineEndings = true;

            DefaultBaseNamespace = "Test"; // Matches the default working directory
            DefaultFileName      = "TestComponent.cshtml";
        }
コード例 #26
0
    public void EnumerateItems_AtSubDirectory_ReturnsAllFilesUnderDirectoryHierarchy()
    {
        // Arrange
        var projectSystem = new VirtualRazorProjectFileSystem();
        var file1         = new TestRazorProjectItem("/subDirectory/dir2/file1.cshtml");
        var file2         = new TestRazorProjectItem("/file2.cshtml");
        var file3         = new TestRazorProjectItem("/dir3/file3.cshtml");
        var file4         = new TestRazorProjectItem("/subDirectory/file4.cshtml");

        projectSystem.Add(file1);
        projectSystem.Add(file2);
        projectSystem.Add(file3);
        projectSystem.Add(file4);

        // Act
        var result = projectSystem.EnumerateItems("/subDirectory");

        // Assert
        Assert.Equal(new[] { file4, file1 }, result);
    }
コード例 #27
0
    public void GetHierarchicalItems_Works()
    {
        // Arrange
        var projectSystem = new VirtualRazorProjectFileSystem();
        var viewImport1   = new TestRazorProjectItem("/_ViewImports.cshtml");
        var viewImport2   = new TestRazorProjectItem("/Views/Home/_ViewImports.cshtml");

        projectSystem.Add(viewImport1);
        projectSystem.Add(viewImport2);

        // Act
        var items = projectSystem.FindHierarchicalItems("/", "/Views/Home/Index.cshtml", "_ViewImports.cshtml");

        // Assert
        Assert.Collection(
            items,
            item => Assert.Same(viewImport2, item),
            item => Assert.False(item.Exists),
            item => Assert.Same(viewImport1, item));
    }
コード例 #28
0
    private static RazorCodeDocument GetCodeDocument(TestRazorProjectItem projectItem, TestRazorProjectItem imports = null)
    {
        var sourceDocument = RazorSourceDocument.ReadFrom(projectItem);
        var fileSystem     = new VirtualRazorProjectFileSystem();

        fileSystem.Add(projectItem);

        var codeDocument = RazorCodeDocument.Create(sourceDocument);

        if (imports != null)
        {
            fileSystem.Add(imports);
            codeDocument = RazorCodeDocument.Create(sourceDocument, new[] { RazorSourceDocument.ReadFrom(imports) });
        }

        var razorEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem).Engine;

        razorEngine.Process(codeDocument);
        return(codeDocument);
    }
コード例 #29
0
        private static RazorProjectEngine GetGenerationProjectEngine(
            IReadOnlyList <TagHelperDescriptor> tagHelpers,
            SourceGeneratorProjectItem item,
            IEnumerable <SourceGeneratorProjectItem> imports,
            RazorSourceGenerationOptions razorSourceGeneratorOptions)
        {
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(item);
            foreach (var import in imports)
            {
                fileSystem.Add(import);
            }

            var projectEngine = RazorProjectEngine.Create(razorSourceGeneratorOptions.Configuration, fileSystem, b =>
            {
                b.Features.Add(new DefaultTypeNameFeature());
                b.SetRootNamespace(razorSourceGeneratorOptions.RootNamespace);

                b.Features.Add(new ConfigureRazorCodeGenerationOptions(options =>
                {
                    options.SuppressMetadataSourceChecksumAttributes = !razorSourceGeneratorOptions.GenerateMetadataSourceChecksumAttributes;
                    options.SupportLocalizedComponentNames           = razorSourceGeneratorOptions.SupportLocalizedComponentNames;
                }));

                b.Features.Add(new StaticTagHelperFeature {
                    TagHelpers = tagHelpers
                });
                b.Features.Add(new DefaultTagHelperDescriptorProvider());

                CompilerFeatures.Register(b);
                RazorExtensions.Register(b);

                b.SetCSharpLanguageVersion(razorSourceGeneratorOptions.CSharpLanguageVersion);
            });

            return(projectEngine);
        }
コード例 #30
0
        public void OnProvidersExecuting_AddsMultipleSelectorsForIndexPages()
        {
            // Arrange
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem("/Pages/Index.cshtml", "@page"));
            fileSystem.Add(new TestRazorProjectItem("/Pages/Test.cshtml", "Hello world"));
            fileSystem.Add(new TestRazorProjectItem("/Pages/Admin/Index.cshtml", "@page \"test\""));

            var optionsManager = Options.Create(new RazorPagesOptions());

            optionsManager.Value.RootDirectory = "/";
            var provider = new RazorProjectPageRouteModelProvider(fileSystem, optionsManager, NullLoggerFactory.Instance);
            var context  = new PageRouteModelProviderContext();

            // Act
            provider.OnProvidersExecuting(context);

            // Assert
            Assert.Collection(context.RouteModels,
                              model =>
            {
                Assert.Equal("/Pages/Index.cshtml", model.RelativePath);
                Assert.Equal("/Pages/Index", model.ViewEnginePath);
                Assert.Collection(model.Selectors,
                                  selector => Assert.Equal("Pages/Index", selector.AttributeRouteModel.Template),
                                  selector => Assert.Equal("Pages", selector.AttributeRouteModel.Template));
            },
                              model =>
            {
                Assert.Equal("/Pages/Admin/Index.cshtml", model.RelativePath);
                Assert.Equal("/Pages/Admin/Index", model.ViewEnginePath);
                Assert.Collection(model.Selectors,
                                  selector => Assert.Equal("Pages/Admin/Index/test", selector.AttributeRouteModel.Template),
                                  selector => Assert.Equal("Pages/Admin/test", selector.AttributeRouteModel.Template));
            });
        }