Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,30 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
using System.Web.Compilation;
using System.Web.WebPages.TestUtils;
using Xunit;
namespace System.Web.WebPages.Razor.Test
{
public class PreApplicationStartCodeTest
{
[Fact]
public void StartTest()
{
AppDomainUtils.RunInSeparateAppDomain(() =>
{
AppDomainUtils.SetPreAppStartStage();
PreApplicationStartCode.Start();
var buildProviders = typeof(BuildProvider).GetField("s_dynamicallyRegisteredProviders", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
Assert.Equal(2, buildProviders.GetType().GetProperty("Count", BindingFlags.Public | BindingFlags.Instance).GetValue(buildProviders, new object[] { }));
});
}
[Fact]
public void TestPreAppStartClass()
{
PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));
}
}
}

View File

@ -0,0 +1,36 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("System.Web.WebPages.Razor.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("System.Web.WebPages.Razor.Test")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,249 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using ASP;
using Microsoft.CSharp;
using Moq;
using Xunit;
namespace ASP
{
public class _Page_Foo_Test_cshtml
{
}
}
namespace System.Web.WebPages.Razor.Test
{
public class RazorBuildProviderTest
{
private class MockAssemblyBuilder : IAssemblyBuilder
{
public BuildProvider BuildProvider { get; private set; }
public CodeCompileUnit CompileUnit { get; private set; }
public string LastTypeFactoryGenerated { get; private set; }
public void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit)
{
BuildProvider = buildProvider;
CompileUnit = compileUnit;
}
public void GenerateTypeFactory(string typeName)
{
LastTypeFactoryGenerated = typeName;
}
}
[Fact]
public void CodeCompilerTypeReturnsTypeFromCodeLanguage()
{
// Arrange
WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml");
RazorBuildProvider provider = CreateBuildProvider("foo @bar baz");
provider.Host = host;
// Act
CompilerType type = provider.CodeCompilerType;
// Assert
Assert.Equal(typeof(CSharpCodeProvider), type.CodeDomProviderType);
}
[Fact]
public void CodeCompilerTypeSetsDebugFlagInFullTrust()
{
// Arrange
WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml");
RazorBuildProvider provider = CreateBuildProvider("foo @bar baz");
provider.Host = host;
// Act
CompilerType type = provider.CodeCompilerType;
// Assert
Assert.True(type.CompilerParameters.IncludeDebugInformation);
}
[Fact]
public void GetGeneratedTypeUsesNameAndNamespaceFromHostToExtractType()
{
// Arrange
WebPageRazorHost host = new WebPageRazorHost("~/Foo/Test.cshtml", @"C:\Foo\Test.cshtml");
RazorBuildProvider provider = new RazorBuildProvider() { Host = host };
CompilerResults results = new CompilerResults(new TempFileCollection());
results.CompiledAssembly = typeof(_Page_Foo_Test_cshtml).Assembly;
// Act
Type typ = provider.GetGeneratedType(results);
// Assert
Assert.Equal(typeof(_Page_Foo_Test_cshtml), typ);
}
[Fact]
public void GenerateCodeCoreAddsGeneratedCodeToAssemblyBuilder()
{
// Arrange
WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml");
RazorBuildProvider provider = new RazorBuildProvider();
CodeCompileUnit ccu = new CodeCompileUnit();
MockAssemblyBuilder asmBuilder = new MockAssemblyBuilder();
provider.Host = host;
provider.GeneratedCode = ccu;
// Act
provider.GenerateCodeCore(asmBuilder);
// Assert
Assert.Same(provider, asmBuilder.BuildProvider);
Assert.Same(ccu, asmBuilder.CompileUnit);
Assert.Equal("ASP._Page_Foo_Baz_cshtml", asmBuilder.LastTypeFactoryGenerated);
}
[Fact]
public void CodeGenerationStartedTest()
{
// Arrange
WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml");
RazorBuildProvider provider = CreateBuildProvider("foo @bar baz");
provider.Host = host;
// Expected original base dependencies
var baseDependencies = new ArrayList();
baseDependencies.Add("/Samples/Foo/Baz.cshtml");
// Expected list of dependencies after GenerateCode is called
var dependencies = new ArrayList();
dependencies.Add(baseDependencies[0]);
dependencies.Add("/Samples/Foo/Foo.cshtml");
// Set up the event handler
provider.CodeGenerationStartedInternal += (sender, e) =>
{
var bp = sender as RazorBuildProvider;
bp.AddVirtualPathDependency("/Samples/Foo/Foo.cshtml");
};
// Set up the base dependency
MockAssemblyBuilder builder = new MockAssemblyBuilder();
typeof(BuildProvider).GetField("_virtualPath", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(provider, CreateVirtualPath("/Samples/Foo/Baz.cshtml"));
// Test that VirtualPathDependencies returns the original dependency before GenerateCode is called
Assert.True(baseDependencies.OfType<string>().SequenceEqual(provider.VirtualPathDependencies.OfType<string>()));
// Act
provider.GenerateCodeCore(builder);
// Assert
Assert.NotNull(provider.AssemblyBuilderInternal);
Assert.Equal(builder, provider.AssemblyBuilderInternal);
Assert.True(dependencies.OfType<string>().SequenceEqual(provider.VirtualPathDependencies.OfType<string>()));
Assert.Equal("/Samples/Foo/Baz.cshtml", provider.VirtualPath);
}
[Fact]
public void AfterGeneratedCodeEventGetsExecutedAtCorrectTime()
{
// Arrange
WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml");
RazorBuildProvider provider = CreateBuildProvider("foo @bar baz");
provider.Host = host;
provider.CodeGenerationCompletedInternal += (sender, e) =>
{
Assert.Equal("~/Foo/Baz.cshtml", e.VirtualPath);
e.GeneratedCode.Namespaces.Add(new CodeNamespace("DummyNamespace"));
};
// Act
CodeCompileUnit generated = provider.GeneratedCode;
// Assert
Assert.NotNull(generated.Namespaces
.OfType<CodeNamespace>()
.SingleOrDefault(ns => String.Equals(ns.Name, "DummyNamespace")));
}
[Fact]
public void GeneratedCodeThrowsHttpParseExceptionForLastParserError()
{
// Arrange
WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml");
RazorBuildProvider provider = CreateBuildProvider("foo @{ if( baz");
provider.Host = host;
// Act
Assert.Throws<HttpParseException>(() => { CodeCompileUnit ccu = provider.GeneratedCode; });
}
[Fact]
public void BuildProviderFiresEventToAlterHostBeforeBuildingPath()
{
// Arrange
WebPageRazorHost expected = new TestHost("~/Foo/Boz.cshtml", @"C:\Foo\Boz.cshtml");
WebPageRazorHost expectedBefore = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml");
RazorBuildProvider provider = CreateBuildProvider("foo");
typeof(BuildProvider).GetField("_virtualPath", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(provider, CreateVirtualPath("/Samples/Foo/Baz.cshtml"));
Mock.Get(provider).Setup(p => p.GetHostFromConfig()).Returns(expectedBefore);
bool called = false;
EventHandler<CompilingPathEventArgs> handler = (sender, args) =>
{
Assert.Equal("/Samples/Foo/Baz.cshtml", args.VirtualPath);
Assert.Same(expectedBefore, args.Host);
args.Host = expected;
called = true;
};
RazorBuildProvider.CompilingPath += handler;
try
{
// Act
CodeCompileUnit ccu = provider.GeneratedCode;
// Assert
Assert.Equal("Test", ccu.Namespaces[0].Name);
Assert.Same(expected, provider.Host);
Assert.True(called);
}
finally
{
RazorBuildProvider.CompilingPath -= handler;
}
}
private static object CreateVirtualPath(string path)
{
var vPath = typeof(BuildProvider).Assembly.GetType("System.Web.VirtualPath");
var method = vPath.GetMethod("CreateNonRelative", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
return method.Invoke(null, new object[] { path });
}
private static RazorBuildProvider CreateBuildProvider(string razorContent)
{
Mock<RazorBuildProvider> mockProvider = new Mock<RazorBuildProvider>()
{
CallBase = true
};
mockProvider.Setup(p => p.InternalOpenReader())
.Returns(() => new StringReader(razorContent));
return mockProvider.Object;
}
private class TestHost : WebPageRazorHost
{
public TestHost(string virtualPath, string physicalPath) : base(virtualPath, physicalPath) { }
public override void PostProcessGeneratedCode(Web.Razor.Generator.CodeGeneratorContext context)
{
context.CompileUnit.Namespaces.Insert(0, new CodeNamespace("Test"));
}
}
}
}

View File

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\tools\WebStack.settings.targets" />
<PropertyGroup>
<!-- Temporarily disable Obsolete Warnings as Errors -->
<WarningsNotAsErrors>618</WarningsNotAsErrors>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{66A74F3C-A106-4C1E-BAA0-001908FEA2CA}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>System.Web.WebPages.Razor.Test</RootNamespace>
<AssemblyName>System.Web.WebPages.Razor.Test</AssemblyName>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Debug\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Release\Test\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'CodeCoverage' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\CodeCoverage\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="PreApplicationStartCodeTest.cs" />
<Compile Include="RazorBuildProviderTest.cs" />
<Compile Include="WebCodeRazorEngineHostTest.cs" />
<Compile Include="WebPageRazorEngineHostTest.cs" />
<Compile Include="WebRazorHostFactoryTest.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Moq, Version=4.0.10827.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\..\packages\Moq.4.0.10827\lib\NET40\Moq.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Web" />
<Reference Include="xunit">
<HintPath>..\..\packages\xunit.1.9.0.1566\lib\xunit.dll</HintPath>
</Reference>
<Reference Include="xunit.extensions">
<HintPath>..\..\packages\xunit.extensions.1.9.0.1566\lib\xunit.extensions.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.Web.WebPages\System.Web.WebPages.csproj">
<Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>
<Name>System.Web.WebPages</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Web.Razor\System.Web.Razor.csproj">
<Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>
<Name>System.Web.Razor</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Web.WebPages.Razor\System.Web.WebPages.Razor.csproj">
<Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>
<Name>System.Web.WebPages.Razor</Name>
</ProjectReference>
<ProjectReference Include="..\Microsoft.TestCommon\Microsoft.TestCommon.csproj">
<Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>
<Name>Microsoft.TestCommon</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup />
<ItemGroup>
<None Include="app.config">
<SubType>Designer</SubType>
</None>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,112 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.CodeDom;
using System.Linq;
using System.Web.Razor.Generator;
using Xunit;
namespace System.Web.WebPages.Razor.Test
{
public class WebCodeRazorEngineHostTest
{
[Fact]
public void ConstructorWithMalformedVirtualPathSetsDefaultProperties()
{
// Act
WebCodeRazorHost host = new WebCodeRazorHost(@"~/Foo/App_Code\Bar\Baz\Qux.cshtml");
// Assert
Assert.Equal("System.Web.WebPages.HelperPage", host.DefaultBaseClass);
Assert.Equal("ASP.Bar.Baz", host.DefaultNamespace);
Assert.Equal("Qux", host.DefaultClassName);
Assert.False(host.DefaultDebugCompilation);
Assert.True(host.StaticHelpers);
}
[Fact]
public void ConstructorWithFileOnlyVirtualPathSetsDefaultProperties()
{
// Act
WebCodeRazorHost host = new WebCodeRazorHost(@"Foo.cshtml");
// Assert
Assert.Equal("System.Web.WebPages.HelperPage", host.DefaultBaseClass);
Assert.Equal("ASP", host.DefaultNamespace);
Assert.Equal("Foo", host.DefaultClassName);
Assert.False(host.DefaultDebugCompilation);
}
[Fact]
public void ConstructorWithVirtualPathSetsDefaultProperties()
{
// Act
WebCodeRazorHost host = new WebCodeRazorHost("~/Foo/App_Code/Bar/Baz/Qux.cshtml");
// Assert
Assert.Equal("System.Web.WebPages.HelperPage", host.DefaultBaseClass);
Assert.Equal("ASP.Bar.Baz", host.DefaultNamespace);
Assert.Equal("Qux", host.DefaultClassName);
Assert.False(host.DefaultDebugCompilation);
}
[Fact]
public void ConstructorWithVirtualAndPhysicalPathSetsDefaultProperties()
{
// Act
WebCodeRazorHost host = new WebCodeRazorHost("~/Foo/App_Code/Bar/Baz/Qux.cshtml", @"C:\Qux.doodad");
// Assert
Assert.Equal("System.Web.WebPages.HelperPage", host.DefaultBaseClass);
Assert.Equal("ASP.Bar.Baz", host.DefaultNamespace);
Assert.Equal("Qux", host.DefaultClassName);
Assert.False(host.DefaultDebugCompilation);
}
[Fact]
public void PostProcessGeneratedCodeRemovesExecuteMethod()
{
// Arrange
WebCodeRazorHost host = new WebCodeRazorHost("Foo.cshtml");
CodeGeneratorContext context = CodeGeneratorContext.Create(
host,
() => new CSharpCodeWriter(),
"TestClass",
"TestNamespace",
"TestFile.cshtml",
shouldGenerateLinePragmas: true);
// Act
host.PostProcessGeneratedCode(context);
// Assert
Assert.Equal(0, context.GeneratedClass.Members.OfType<CodeMemberMethod>().Count());
}
[Fact]
public void PostProcessGeneratedCodeAddsStaticApplicationInstanceProperty()
{
// Arrange
WebCodeRazorHost host = new WebCodeRazorHost("Foo.cshtml");
CodeGeneratorContext context =
CodeGeneratorContext.Create(
host,
() => new CSharpCodeWriter(),
"TestClass",
"TestNamespace",
"Foo.cshtml",
shouldGenerateLinePragmas: true);
// Act
host.PostProcessGeneratedCode(context);
// Assert
CodeMemberProperty appInstance = context.GeneratedClass
.Members
.OfType<CodeMemberProperty>()
.Where(p => p.Name.Equals("ApplicationInstance"))
.SingleOrDefault();
Assert.NotNull(appInstance);
Assert.True(appInstance.Attributes.HasFlag(MemberAttributes.Static));
}
}
}

View File

@ -0,0 +1,102 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Razor;
using System.Web.Razor.Generator;
using Microsoft.CSharp;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.WebPages.Razor.Test
{
public class WebPageRazorEngineHostTest
{
[Fact]
public void ConstructorRequiresNonNullOrEmptyVirtualPath()
{
Assert.ThrowsArgumentNullOrEmptyString(() => new WebPageRazorHost(null), "virtualPath");
Assert.ThrowsArgumentNullOrEmptyString(() => new WebPageRazorHost(String.Empty), "virtualPath");
Assert.ThrowsArgumentNullOrEmptyString(() => new WebPageRazorHost(null, "foo"), "virtualPath");
Assert.ThrowsArgumentNullOrEmptyString(() => new WebPageRazorHost(String.Empty, "foo"), "virtualPath");
}
[Fact]
public void ConstructorWithVirtualPathUsesItToDetermineBaseClassClassNameAndLanguage()
{
// Act
WebPageRazorHost host = new WebPageRazorHost("~/Foo/Bar.cshtml");
// Assert
Assert.Equal("_Page_Foo_Bar_cshtml", host.DefaultClassName);
Assert.Equal("System.Web.WebPages.WebPage", host.DefaultBaseClass);
Assert.IsType<CSharpRazorCodeLanguage>(host.CodeLanguage);
Assert.False(host.StaticHelpers);
}
[Fact]
public void PostProcessGeneratedCodeAddsGlobalImports()
{
// Arrange
WebPageRazorHost.AddGlobalImport("Foo.Bar");
WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml");
CodeGeneratorContext context = CodeGeneratorContext.Create(
host,
() => new CSharpCodeWriter(),
"TestClass",
"TestNs",
"TestFile.cshtml",
shouldGenerateLinePragmas: true);
// Act
host.PostProcessGeneratedCode(context);
// Assert
Assert.True(context.Namespace.Imports.OfType<CodeNamespaceImport>().Any(import => String.Equals("Foo.Bar", import.Namespace)));
}
[Fact]
public void PostProcessGeneratedCodeAddsApplicationInstanceProperty()
{
const string expectedPropertyCode = @"
protected Foo.Bar ApplicationInstance {
get {
return ((Foo.Bar)(Context.ApplicationInstance));
}
}
";
// Arrange
WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml")
{
GlobalAsaxTypeName = "Foo.Bar"
};
CodeGeneratorContext context = CodeGeneratorContext.Create(
host,
() => new CSharpCodeWriter(),
"TestClass",
"TestNs",
"TestFile.cshtml",
shouldGenerateLinePragmas: true);
// Act
host.PostProcessGeneratedCode(context);
// Assert
CodeMemberProperty property = context.GeneratedClass.Members[0] as CodeMemberProperty;
Assert.NotNull(property);
CSharpCodeProvider provider = new CSharpCodeProvider();
StringBuilder builder = new StringBuilder();
using (StringWriter writer = new StringWriter(builder))
{
provider.GenerateCodeFromMember(property, writer, new CodeGeneratorOptions());
}
Assert.Equal(expectedPropertyCode, builder.ToString());
}
}
}

View File

@ -0,0 +1,388 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Configuration;
using System.Reflection;
using System.Web.Configuration;
using System.Web.WebPages.Razor.Configuration;
using System.Web.WebPages.Razor.Resources;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.WebPages.Razor.Test
{
public class WebRazorHostFactoryTest
{
public class TestFactory : WebRazorHostFactory
{
public override WebPageRazorHost CreateHost(string virtualPath, string physicalPath = null)
{
return new TestHost();
}
}
public class TestHost : WebPageRazorHost
{
public TestHost()
: base("Foo.cshtml")
{
}
public new void RegisterSpecialFile(string fileName, Type baseType)
{
base.RegisterSpecialFile(fileName, baseType);
}
public new void RegisterSpecialFile(string fileName, string baseType)
{
base.RegisterSpecialFile(fileName, baseType);
}
}
[Fact]
public void CreateHostReturnsWebPageHostWithWebPageAsBaseClassIfVirtualPathIsNormalPage()
{
// Act
WebPageRazorHost host = new WebRazorHostFactory().CreateHost("~/Foo/Bar/Baz.cshtml", null);
// Assert
Assert.IsType<WebPageRazorHost>(host);
Assert.Equal(WebPageRazorHost.PageBaseClass, host.DefaultBaseClass);
}
[Fact]
public void CreateHostReturnsWebPageHostWithInitPageAsBaseClassIfVirtualPathIsPageStart()
{
// Act
WebPageRazorHost host = new WebRazorHostFactory().CreateHost("~/Foo/Bar/_pagestart.cshtml", null);
// Assert
Assert.IsType<WebPageRazorHost>(host);
Assert.Equal(typeof(StartPage).FullName, host.DefaultBaseClass);
}
[Fact]
public void CreateHostReturnsWebPageHostWithStartPageAsBaseClassIfVirtualPathIsAppStart()
{
// Act
WebPageRazorHost host = new WebRazorHostFactory().CreateHost("~/Foo/Bar/_appstart.cshtml", null);
// Assert
Assert.IsType<WebPageRazorHost>(host);
Assert.Equal(typeof(ApplicationStartPage).FullName, host.DefaultBaseClass);
}
[Fact]
public void CreateHostPassesPhysicalPathOnToWebCodeRazorHost()
{
// Act
WebPageRazorHost host = new WebRazorHostFactory().CreateHost("~/Foo/Bar/Baz/App_Code/Bar", @"C:\Foo.cshtml");
// Assert
Assert.Equal(@"C:\Foo.cshtml", host.PhysicalPath);
}
[Fact]
public void CreateHostPassesPhysicalPathOnToWebPageRazorHost()
{
// Act
WebPageRazorHost host = new WebRazorHostFactory().CreateHost("~/Foo/Bar/Baz/Bar", @"C:\Foo.cshtml");
// Assert
Assert.Equal(@"C:\Foo.cshtml", host.PhysicalPath);
}
[Fact]
public void CreateHostFromConfigRequiresNonNullVirtualPath()
{
Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(virtualPath: null,
physicalPath: "foo"), "virtualPath");
Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(config: new RazorWebSectionGroup(),
virtualPath: null,
physicalPath: "foo"), "virtualPath");
}
[Fact]
public void CreateHostFromConfigRequiresNonEmptyVirtualPath()
{
Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(virtualPath: String.Empty,
physicalPath: "foo"), "virtualPath");
Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(config: new RazorWebSectionGroup(),
virtualPath: String.Empty,
physicalPath: "foo"), "virtualPath");
}
[Fact]
public void CreateHostFromConfigRequiresNonNullSectionGroup()
{
Assert.ThrowsArgumentNull(() => WebRazorHostFactory.CreateHostFromConfig(config: (RazorWebSectionGroup)null,
virtualPath: String.Empty,
physicalPath: "foo"), "config");
}
[Fact]
public void CreateHostFromConfigReturnsWebCodeHostIfVirtualPathStartsWithAppCode()
{
// Act
WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfigCore(null, "~/App_Code/Bar.cshtml", null);
// Assert
Assert.IsType<WebCodeRazorHost>(host);
}
[Fact]
public void CreateHostFromConfigUsesDefaultFactoryIfNoRazorWebSectionGroupFound()
{
// Act
WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfigCore(null, "/Foo/Bar.cshtml", null);
// Assert
Assert.IsType<WebPageRazorHost>(host);
}
[Fact]
public void CreateHostFromConfigUsesDefaultFactoryIfNoHostSectionFound()
{
// Arrange
RazorWebSectionGroup config = new RazorWebSectionGroup()
{
Host = null,
Pages = null
};
// Act
WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null);
// Assert
Assert.IsType<WebPageRazorHost>(host);
}
[Fact]
public void CreateHostFromConfigUsesDefaultFactoryIfNullFactoryType()
{
// Arrange
RazorWebSectionGroup config = new RazorWebSectionGroup()
{
Host = new HostSection()
{
FactoryType = null
},
Pages = null
};
// Act
WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null);
// Assert
Assert.IsType<WebPageRazorHost>(host);
}
[Fact]
public void CreateHostFromConfigUsesFactorySpecifiedInConfig()
{
// Arrange
RazorWebSectionGroup config = new RazorWebSectionGroup()
{
Host = new HostSection()
{
FactoryType = typeof(TestFactory).FullName
},
Pages = null
};
WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);
// Act
WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null);
// Assert
Assert.IsType<TestHost>(host);
}
[Fact]
public void CreateHostFromConfigThrowsInvalidOperationExceptionIfFactoryTypeNotFound()
{
// Arrange
RazorWebSectionGroup config = new RazorWebSectionGroup()
{
Host = new HostSection()
{
FactoryType = "Foo"
},
Pages = null
};
WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);
// Act
Assert.Throws<InvalidOperationException>(
() => WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null),
String.Format(RazorWebResources.Could_Not_Locate_FactoryType, "Foo"));
}
[Fact]
public void CreateHostFromConfigAppliesBaseTypeFromConfigToHost()
{
// Arrange
RazorWebSectionGroup config = new RazorWebSectionGroup()
{
Host = null,
Pages = new RazorPagesSection()
{
PageBaseType = "System.Foo.Bar"
}
};
WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);
// Act
WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null);
// Assert
Assert.Equal("System.Foo.Bar", host.DefaultBaseClass);
}
[Fact]
public void CreateHostFromConfigIgnoresBaseTypeFromConfigIfPageIsPageStart()
{
// Arrange
RazorWebSectionGroup config = new RazorWebSectionGroup()
{
Host = null,
Pages = new RazorPagesSection()
{
PageBaseType = "System.Foo.Bar"
}
};
WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);
// Act
WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/_pagestart.cshtml", null);
// Assert
Assert.Equal(typeof(StartPage).FullName, host.DefaultBaseClass);
}
[Fact]
public void CreateHostFromConfigIgnoresBaseTypeFromConfigIfPageIsAppStart()
{
// Arrange
RazorWebSectionGroup config = new RazorWebSectionGroup()
{
Host = null,
Pages = new RazorPagesSection()
{
PageBaseType = "System.Foo.Bar"
}
};
WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);
// Act
WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/_appstart.cshtml", null);
// Assert
Assert.Equal(typeof(ApplicationStartPage).FullName, host.DefaultBaseClass);
}
[Fact]
public void CreateHostFromConfigMergesNamespacesFromConfigToHost()
{
// Arrange
RazorWebSectionGroup config = new RazorWebSectionGroup()
{
Host = null,
Pages = new RazorPagesSection()
{
Namespaces = new NamespaceCollection()
{
new NamespaceInfo("System"),
new NamespaceInfo("Foo")
}
}
};
WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);
// Act
WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null);
// Assert
Assert.True(host.NamespaceImports.Contains("System"));
Assert.True(host.NamespaceImports.Contains("Foo"));
}
[Fact]
public void HostFactoryTypeIsCorrectlyLoadedFromConfig()
{
// Act
RazorWebSectionGroup group = GetRazorGroup();
HostSection host = (HostSection)group.Host;
// Assert
Assert.NotNull(host);
Assert.Equal("System.Web.WebPages.Razor.Test.TestRazorHostFactory, System.Web.WebPages.Razor.Test", host.FactoryType);
}
[Fact]
public void PageBaseTypeIsCorrectlyLoadedFromConfig()
{
// Act
RazorWebSectionGroup group = GetRazorGroup();
RazorPagesSection pages = (RazorPagesSection)group.Pages;
// Assert
Assert.NotNull(pages);
Assert.Equal("System.Web.WebPages.Razor.Test.TestPageBase, System.Web.WebPages.Razor.Test", pages.PageBaseType);
}
[Fact]
public void NamespacesAreCorrectlyLoadedFromConfig()
{
// Act
RazorWebSectionGroup group = GetRazorGroup();
RazorPagesSection pages = (RazorPagesSection)group.Pages;
// Assert
Assert.NotNull(pages);
Assert.Equal(1, pages.Namespaces.Count);
Assert.Equal("System.Text.RegularExpressions", pages.Namespaces[0].Namespace);
}
[Fact]
public void RegisterSpecialFile_ThrowsOnNullFileName()
{
TestHost host = new TestHost();
Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(null, typeof(string)), "fileName");
Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(null, "string"), "fileName");
}
[Fact]
public void RegisterSpecialFile_ThrowsOnEmptyFileName()
{
TestHost host = new TestHost();
Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(String.Empty, typeof(string)), "fileName");
Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(String.Empty, "string"), "fileName");
}
[Fact]
public void RegisterSpecialFile_ThrowsOnNullBaseType()
{
TestHost host = new TestHost();
Assert.ThrowsArgumentNull(() => host.RegisterSpecialFile("file", (Type)null), "baseType");
}
[Fact]
public void RegisterSpecialFile_ThrowsOnNullBaseTypeName()
{
TestHost host = new TestHost();
Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile("file", (string)null), "baseTypeName");
}
[Fact]
public void RegisterSpecialFile_ThrowsOnEmptyBaseTypeName()
{
TestHost host = new TestHost();
Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile("file", String.Empty), "baseTypeName");
}
private static RazorWebSectionGroup GetRazorGroup()
{
return (RazorWebSectionGroup)ConfigurationManager.OpenExeConfiguration(null).GetSectionGroup(RazorWebSectionGroup.GroupName);
}
}
}

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.WebPages.Razor.Test.TestRazorHostFactory, System.Web.WebPages.Razor.Test" />
<pages pageBaseType="System.Web.WebPages.Razor.Test.TestPageBase, System.Web.WebPages.Razor.Test">
<namespaces>
<add namespace="System.IO.Packaging" />
<clear />
<add namespace="System.Security" />
<add namespace="System.Text.RegularExpressions" />
<remove namespace="System.Security" />
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Moq" version="4.0.10827" />
<package id="xunit" version="1.9.0.1566" />
<package id="xunit.extensions" version="1.9.0.1566" />
</packages>