Revert "Temp8 tinymce"

This commit is contained in:
Warren Buckley
2018-11-22 14:05:51 +00:00
committed by GitHub
parent 2a0748fc1e
commit 54a2aa00a7
6677 changed files with 646351 additions and 410535 deletions

View File

@@ -1,169 +1,172 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="umbracoConfiguration">
<section name="FileSystemProviders" type="Umbraco.Core.Configuration.FileSystemProvidersSection, Umbraco.Core" requirePermission="false"/>
</sectionGroup>
</configSections>
<umbracoConfiguration>
<FileSystemProviders>
<Provider alias="media" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="Media\"/>
<add key="rootUrl" value="/Media/"/>
</Parameters>
</Provider>
<!-- Macros -->
<Provider alias="macros" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="App_Data\Macros"/>
<add key="rootUrl" value="/Macros/"/>
</Parameters>
</Provider>
<!-- Scripts -->
<Provider alias="scripts" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="scripts\"/>
<add key="rootUrl" value="/scripts/"/>
</Parameters>
</Provider>
<!-- Stylesheets -->
<Provider alias="stylesheets" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="css\"/>
<add key="rootUrl" value="/css/"/>
</Parameters>
</Provider>
<!-- Templates -->
<Provider alias="masterpages" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="masterpages\"/>
<add key="rootUrl" value="/masterpages/"/>
</Parameters>
</Provider>
<Provider alias="views" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="views\"/>
<add key="rootUrl" value="/views/"/>
</Parameters>
</Provider>
</FileSystemProviders>
</umbracoConfiguration>
<appSettings>
<add key="umbracoConfigurationStatus" value="6.0.0"/>
<add key="umbracoReservedUrls" value="~/config/splashes/booting.aspx,~/install/default.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,~/.well-known" />
<add key="umbracoReservedPaths" value="~/install/"/>
<add key="umbracoPath" value="~/umbraco"/>
<add key="umbracoHideTopLevelNodeFromPath" value="true"/>
<add key="umbracoUseDirectoryUrls" value="false"/>
<add key="umbracoTimeOutInMinutes" value="20"/>
<add key="umbracoDefaultUILanguage" value="en"/>
<add key="umbracoUseHttps" value="false"/>
<add key="dataAnnotations:dataTypeAttribute:disableRegEx" value="false"/>
</appSettings>
<connectionStrings>
<add name="umbracoDbDSN" connectionString="Datasource=|DataDirectory|UmbracoNPocoTests.sdf;Flush Interval=1;" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0"/>
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
<remove invariant="MySql.Data.MySqlClient"/>
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.6.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</DbProviderFactories>
</system.data>
<system.web>
<httpRuntime targetFramework="4.5"/>
<compilation defaultLanguage="c#" debug="true" batch="false" targetFramework="4.0"></compilation>
<machineKey validationKey="5E7B955FCE36F5F2A867C2A0D85DC61E7FEA9E15F1561E8386F78BFE9EE23FF18B21E6A44AA17300B3B9D5DBEB37AA61A2C73884A5BBEDA6D3B14BA408A7A8CD" decryptionKey="116B853D031219E404E088FCA0986D6CF2DFA77E1957B59FCC9404B8CA3909A1" validation="SHA1" decryption="AES"/>
<!--<trust level="Medium" originUrl=".*"/>-->
<!-- Sitemap provider-->
<siteMap defaultProvider="UmbracoSiteMapProvider" enabled="true">
<providers>
<clear/>
<add name="UmbracoSiteMapProvider" type="umbraco.presentation.nodeFactory.UmbracoSiteMapProvider" defaultDescriptionAlias="description" securityTrimmingEnabled="true"/>
</providers>
</siteMap>
<!-- Membership Provider -->
<membership defaultProvider="UmbracoMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="UmbracoMembershipProvider" type="Umbraco.Web.Security.Providers.MembersMembershipProvider, Umbraco.Web" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="4" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Member" passwordFormat="Hashed"/>
<add name="UsersMembershipProvider" type="Umbraco.Web.Security.Providers.UsersMembershipProvider, Umbraco.Web" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="4" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed" allowManuallyChangingPassword="false"/>
</providers>
</membership>
</system.web>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.CodeAnalysis" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-2.8.0.0" newVersion="2.8.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.CodeAnalysis.CSharp" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-2.8.0.0" newVersion="2.8.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-1.2.2.0" newVersion="1.2.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Reflection.Metadata" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-1.4.2.0" newVersion="1.4.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Encoding.CodePages" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="umbracoConfiguration">
<section name="FileSystemProviders" type="Umbraco.Core.Configuration.FileSystemProvidersSection, Umbraco.Core" requirePermission="false" />
</sectionGroup>
</configSections>
<umbracoConfiguration>
<FileSystemProviders>
<Provider alias="media" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="Media\" />
<add key="rootUrl" value="/Media/" />
</Parameters>
</Provider>
<!-- Macros -->
<Provider alias="macros" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="App_Data\Macros" />
<add key="rootUrl" value="/Macros/" />
</Parameters>
</Provider>
<!-- Scripts -->
<Provider alias="scripts" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="scripts\" />
<add key="rootUrl" value="/scripts/" />
</Parameters>
</Provider>
<!-- Stylesheets -->
<Provider alias="stylesheets" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="css\" />
<add key="rootUrl" value="/css/" />
</Parameters>
</Provider>
<!-- Templates -->
<Provider alias="masterpages" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="masterpages\" />
<add key="rootUrl" value="/masterpages/" />
</Parameters>
</Provider>
<Provider alias="views" type="Umbraco.Core.IO.PhysicalFileSystem, Umbraco.Core">
<Parameters>
<add key="rootPath" value="views\" />
<add key="rootUrl" value="/views/" />
</Parameters>
</Provider>
</FileSystemProviders>
</umbracoConfiguration>
<appSettings>
<add key="umbracoConfigurationStatus" value="6.0.0" />
<add key="umbracoReservedUrls" value="~/config/splashes/booting.aspx,~/install/default.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,~/.well-known" />
<add key="umbracoReservedPaths" value="~/install/" />
<add key="umbracoPath" value="~/umbraco" />
<add key="umbracoHideTopLevelNodeFromPath" value="true" />
<add key="umbracoUseDirectoryUrls" value="false" />
<add key="umbracoTimeOutInMinutes" value="20" />
<add key="umbracoDefaultUILanguage" value="en" />
<add key="umbracoUseSSL" value="false" />
</appSettings>
<connectionStrings>
<add name="umbracoDbDSN" connectionString="Datasource=|DataDirectory|UmbracoPetaPocoTests.sdf;Flush Interval=1;" providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.6.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation defaultLanguage="c#" debug="true" batch="false" targetFramework="4.0"></compilation>
<machineKey validationKey="5E7B955FCE36F5F2A867C2A0D85DC61E7FEA9E15F1561E8386F78BFE9EE23FF18B21E6A44AA17300B3B9D5DBEB37AA61A2C73884A5BBEDA6D3B14BA408A7A8CD" decryptionKey="116B853D031219E404E088FCA0986D6CF2DFA77E1957B59FCC9404B8CA3909A1" validation="SHA1" decryption="AES" />
<!--<trust level="Medium" originUrl=".*"/>-->
<!-- Sitemap provider-->
<siteMap defaultProvider="UmbracoSiteMapProvider" enabled="true">
<providers>
<clear />
<add name="UmbracoSiteMapProvider" type="umbraco.presentation.nodeFactory.UmbracoSiteMapProvider, umbraco" defaultDescriptionAlias="description" securityTrimmingEnabled="true" />
</providers>
</siteMap>
<!-- Membership Provider -->
<membership defaultProvider="UmbracoMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="UmbracoMembershipProvider" type="Umbraco.Web.Security.Providers.MembersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="4" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Member" passwordFormat="Hashed" />
<add name="UsersMembershipProvider" type="Umbraco.Web.Security.Providers.UsersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="4" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed" allowManuallyChangingPassword="false" />
</providers>
</membership>
</system.web>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="MiniProfiler" publicKeyToken="b44f9351044011a3" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="NuGet.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.11220.104" newVersion="1.0.11220.104" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.8.0" newVersion="2.0.8.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@@ -0,0 +1,125 @@
using System;
using System.Configuration;
using Moq;
using NUnit.Framework;
using Semver;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Profiling;
using Umbraco.Core.Scoping;
using Umbraco.Core.Services;
namespace Umbraco.Tests
{
[TestFixture]
public class ApplicationContextTests
{
[Test]
public void Is_Configured()
{
ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", UmbracoVersion.GetSemanticVersion().ToSemanticString());
var migrationEntryService = new Mock<IMigrationEntryService>();
migrationEntryService.Setup(x => x.FindEntry(It.IsAny<string>(), It.IsAny<SemVersion>()))
.Returns(Mock.Of<IMigrationEntry>());
var dbCtx = new Mock<DatabaseContext>(Mock.Of<IScopeProviderInternal>(), Mock.Of<ILogger>(), new SqlCeSyntaxProvider(), "test");
dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(true);
dbCtx.Setup(x => x.CanConnect).Returns(true);
var appCtx = new ApplicationContext(
dbCtx.Object,
new ServiceContext(migrationEntryService:migrationEntryService.Object),
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
Assert.IsTrue(appCtx.IsConfigured);
}
[Test]
public void Is_Not_Configured_By_Migration_Not_Found()
{
ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", UmbracoVersion.GetSemanticVersion().ToSemanticString());
var migrationEntryService = new Mock<IMigrationEntryService>();
migrationEntryService.Setup(x => x.FindEntry(It.IsAny<string>(), It.IsAny<SemVersion>()))
.Returns((IMigrationEntry)null);
var dbCtx = new Mock<DatabaseContext>(Mock.Of<IScopeProviderInternal>(), Mock.Of<ILogger>(), new SqlCeSyntaxProvider(), "test");
dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(true);
dbCtx.Setup(x => x.CanConnect).Returns(true);
var appCtx = new ApplicationContext(
dbCtx.Object,
new ServiceContext(migrationEntryService: migrationEntryService.Object),
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
Assert.IsFalse(appCtx.IsConfigured);
}
[Test]
public void Is_Not_Configured_By_Configuration()
{
ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", new SemVersion(UmbracoVersion.Current.Major - 1, 0, 0).ToString());
var migrationEntryService = new Mock<IMigrationEntryService>();
var dbCtx = new Mock<DatabaseContext>(Mock.Of<IScopeProviderInternal>(), Mock.Of<ILogger>(), new SqlCeSyntaxProvider(), "test");
dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(true);
dbCtx.Setup(x => x.CanConnect).Returns(true);
var appCtx = new ApplicationContext(
dbCtx.Object,
new ServiceContext(migrationEntryService: migrationEntryService.Object),
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
Assert.IsFalse(appCtx.IsConfigured);
}
[Test]
public void Is_Not_Configured_By_Database_Not_Configured()
{
ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", new SemVersion(UmbracoVersion.Current.Major - 1, 0, 0).ToString());
var migrationEntryService = new Mock<IMigrationEntryService>();
var dbCtx = new Mock<DatabaseContext>(Mock.Of<IScopeProviderInternal>(), Mock.Of<ILogger>(), new SqlCeSyntaxProvider(), "test");
dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(false);
dbCtx.Setup(x => x.CanConnect).Returns(true);
var appCtx = new ApplicationContext(
dbCtx.Object,
new ServiceContext(migrationEntryService: migrationEntryService.Object),
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
Assert.IsFalse(appCtx.IsConfigured);
}
[Test]
public void Is_Not_Configured_By_Database_Cannot_Connect()
{
ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", new SemVersion(UmbracoVersion.Current.Major - 1, 0, 0).ToString());
var migrationEntryService = new Mock<IMigrationEntryService>();
var dbCtx = new Mock<DatabaseContext>(Mock.Of<IScopeProviderInternal>(), Mock.Of<ILogger>(), new SqlCeSyntaxProvider(), "test");
dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(true);
dbCtx.Setup(x => x.CanConnect).Returns(false);
var appCtx = new ApplicationContext(
dbCtx.Object,
new ServiceContext(migrationEntryService: migrationEntryService.Object),
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
Assert.IsFalse(appCtx.IsConfigured);
}
}
}

View File

@@ -0,0 +1,304 @@
using System.Configuration;
using System.IO;
using System.Linq;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Core.ObjectResolution;
using Umbraco.Core.Profiling;
using Umbraco.Core.Sync;
using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests
{
[TestFixture]
public class ApplicationUrlHelperTests
{
private ILogger _logger;
// note: in tests, read appContext._umbracoApplicationUrl and not the property,
// because reading the property does run some code, as long as the field is null.
[TestFixtureSetUp]
public void InitializeFixture()
{
_logger = new Logger(new FileInfo(TestHelper.MapPathForTest("~/unit-test-log4net.config")));
}
private static void Initialize(IUmbracoSettingsSection settings)
{
ServerRegistrarResolver.Current = new ServerRegistrarResolver(new ConfigServerRegistrar(settings.DistributedCall));
Resolution.Freeze();
}
[TearDown]
public void Reset()
{
ServerRegistrarResolver.Reset();
}
[Test]
public void NoApplicationUrlByDefault()
{
var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
Assert.IsNull(appCtx._umbracoApplicationUrl);
}
[Test]
public void SetApplicationUrlViaProvider()
{
// no applicable settings, but a provider
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>())
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>());
ApplicationUrlHelper.ApplicationUrlProvider = request => "http://server1.com/umbraco";
Initialize(settings);
var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here
ApplicationUrlHelper.EnsureApplicationUrl(appCtx, settings: settings);
Assert.AreEqual("http://server1.com/umbraco", appCtx._umbracoApplicationUrl);
}
[Test]
public void SetApplicationUrlWhenNoSettings()
{
// no applicable settings, cannot set url
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>())
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>());
Initialize(settings);
var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here
ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings);
// still NOT set
Assert.IsNull(appCtx._umbracoApplicationUrl);
}
[Test]
public void SetApplicationUrlFromDcSettingsSsl1()
{
// set from distributed call settings
// first server is master server
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == true && callSection.Servers == new IServer[]
{
Mock.Of<IServer>(server => server.ServerName == NetworkHelper.MachineName && server.ServerAddress == "server1.com"),
Mock.Of<IServer>(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"),
})
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
Initialize(settings);
var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true");
ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings);
Assert.AreEqual("http://server1.com:80/umbraco", appCtx._umbracoApplicationUrl);
var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2;
var role = registrar.GetCurrentServerRole();
Assert.AreEqual(ServerRole.Master, role);
}
[Test]
public void SetApplicationUrlFromDcSettingsSsl2()
{
// set from distributed call settings
// other servers are replica servers
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == true && callSection.Servers == new IServer[]
{
Mock.Of<IServer>(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"),
Mock.Of<IServer>(server => server.ServerName == NetworkHelper.MachineName && server.ServerAddress == "server1.com"),
})
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
Initialize(settings);
var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true");
ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings);
Assert.AreEqual("http://server1.com:80/umbraco", appCtx._umbracoApplicationUrl);
var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2;
var role = registrar.GetCurrentServerRole();
Assert.AreEqual(ServerRole.Slave, role);
}
[Test]
public void SetApplicationUrlFromDcSettingsSsl3()
{
// set from distributed call settings
// cannot set if not enabled
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == false && callSection.Servers == new IServer[]
{
Mock.Of<IServer>(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"),
Mock.Of<IServer>(server => server.ServerName == NetworkHelper.MachineName && server.ServerAddress == "server1.com"),
})
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
Initialize(settings);
var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true");
ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings);
Assert.IsNull(appCtx._umbracoApplicationUrl);
var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2;
var role = registrar.GetCurrentServerRole();
Assert.AreEqual(ServerRole.Single, role);
}
[Test]
public void ServerRoleSingle()
{
// distributed call settings disabled, single server
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == false && callSection.Servers == Enumerable.Empty<IServer>())
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
Initialize(settings);
var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2;
var role = registrar.GetCurrentServerRole();
Assert.AreEqual(ServerRole.Single, role);
}
[Test]
public void ServerRoleUnknown1()
{
// distributed call enabled but missing servers, unknown server
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == true && callSection.Servers == Enumerable.Empty<IServer>())
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
Initialize(settings);
var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2;
var role = registrar.GetCurrentServerRole();
Assert.AreEqual(ServerRole.Unknown, role);
}
[Test]
public void ServerRoleUnknown2()
{
// distributed call enabled, cannot find server, assume it's an undeclared replica
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == true && callSection.Servers == new IServer[]
{
Mock.Of<IServer>(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"),
})
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
Initialize(settings);
var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2;
var role = registrar.GetCurrentServerRole();
Assert.AreEqual(ServerRole.Slave, role);
}
[Test]
public void SetApplicationUrlFromStSettingsNoSsl()
{
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>())
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco"));
Initialize(settings);
var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "false");
ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings);
Assert.AreEqual("http://mycoolhost.com/umbraco", appCtx._umbracoApplicationUrl);
}
[Test]
public void SetApplicationUrlFromStSettingsSsl()
{
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>())
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null)
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco/"));
Initialize(settings);
var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true");
ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings);
Assert.AreEqual("https://mycoolhost.com/umbraco", appCtx._umbracoApplicationUrl);
}
[Test]
public void SetApplicationUrlFromWrSettingsSsl()
{
var settings = Mock.Of<IUmbracoSettingsSection>(section =>
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>())
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == "httpx://whatever.com/umbraco/")
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco"));
Initialize(settings);
var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here
ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings);
Assert.AreEqual("httpx://whatever.com/umbraco", appCtx._umbracoApplicationUrl);
}
}
}

View File

@@ -0,0 +1,55 @@
using System;
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests
{
[TestFixture]
public class AttemptTests
{
[Test]
public void Chained_Attempts()
{
Attempt.Try(Attempt.Succeed("success!"),
s => Assert.AreEqual("success!", s),
exception => Assert.Fail("Should have been successful."))
// previous one was a success so that one SHOULD NOT run
// and report success
.OnFailure(() => Attempt.Succeed(123),
i => Assert.Fail("The previous attempt was successful!"),
exception => Assert.Fail("The previous attempt was successful!"))
// previous one did not run, last run was a success so that one SHOULD run
// and report failure
.OnSuccess(() => Attempt<double>.Fail(new Exception("Failed!")),
d => Assert.Fail("Should have failed."),
exception => Assert.AreEqual("Failed!", exception.Message))
// previous one did run and was a failure so that one SHOULD NOT run
.OnSuccess(() => Attempt.Succeed(987),
i => Assert.Fail("The previous attempt failed!"),
exception => Assert.Fail("The previous attempt failed!"))
// previous one did not run, last run was a failure so that one SHOULD run
// then why does it run?
.OnFailure(() => Attempt.Succeed("finished"),
i => Assert.AreEqual("finished", i),
exception => Assert.Fail("Should have been successful."));
}
[Test]
public void AttemptIf()
{
// just making sure that it is ok to use TryParse as a condition
int value;
var attempt = Attempt.If(int.TryParse("1234", out value), value);
Assert.IsTrue(attempt.Success);
Assert.AreEqual(1234, attempt.Result);
attempt = Attempt.If(int.TryParse("12xxx34", out value), value);
Assert.IsFalse(attempt.Success);
}
}
}

View File

@@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.ObjectResolution;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Tests.TestHelpers;
using umbraco.interfaces;
using Umbraco.Core.Persistence;
using Umbraco.Core.Profiling;
using Umbraco.Core.Scoping;
using Umbraco.Core.Services;
namespace Umbraco.Tests.BootManagers
{
[TestFixture]
public class CoreBootManagerTests : BaseUmbracoConfigurationTest
{
private TestApp _testApp;
[SetUp]
public override void Initialize()
{
base.Initialize();
_testApp = new TestApp();
}
[TearDown]
public override void TearDown()
{
base.TearDown();
_testApp = null;
ResolverCollection.ResetAll();
}
/// <summary>
/// test application using a CoreBootManager instance to boot
/// </summary>
public class TestApp : UmbracoApplicationBase
{
protected override IBootManager GetBootManager()
{
return new TestBootManager(this, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
}
}
/// <summary>
/// Test boot manager to add a custom application event handler
/// </summary>
public class TestBootManager : CoreBootManager
{
public TestBootManager(UmbracoApplicationBase umbracoApplication, ProfilingLogger logger)
: base(umbracoApplication, logger)
{
}
/// <summary>
/// Creates and returns the application context singleton
/// </summary>
/// <param name="dbContext"></param>
/// <param name="serviceContext"></param>
protected override ApplicationContext CreateApplicationContext(DatabaseContext dbContext, ServiceContext serviceContext)
{
var appContext = base.CreateApplicationContext(dbContext, serviceContext);
var dbContextMock = new Mock<DatabaseContext>(Mock.Of<IScopeProviderInternal>(), ProfilingLogger.Logger, Mock.Of<ISqlSyntaxProvider>(), "test");
dbContextMock.Setup(x => x.CanConnect).Returns(true);
appContext.DatabaseContext = dbContextMock.Object;
return appContext;
}
protected override void InitializeApplicationEventsResolver()
{
//create an empty resolver so we can add our own custom ones (don't type find)
ApplicationEventsResolver.Current = new ApplicationEventsResolver(
new ActivatorServiceProvider(), ProfilingLogger.Logger,
new Type[]
{
typeof(LegacyStartupHandler),
typeof(TestApplicationEventHandler)
})
{
CanResolveBeforeFrozen = true
};
}
protected override void InitializeLoggerResolver()
{
}
protected override void InitializeProfilerResolver()
{
}
}
/// <summary>
/// Test legacy startup handler
/// </summary>
public class LegacyStartupHandler : IApplicationStartupHandler
{
public static bool Initialized = false;
public LegacyStartupHandler()
{
Initialized = true;
}
}
/// <summary>
/// test event handler
/// </summary>
public class TestApplicationEventHandler : IApplicationEventHandler
{
public static bool Initialized = false;
public static bool Starting = false;
public static bool Started = false;
public void OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
Initialized = true;
}
public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
Starting = true;
}
public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
Started = true;
}
}
[Test]
public void Handle_IApplicationEventHandler_Objects_Outside_Web_Context()
{
_testApp.StartApplication(_testApp, new EventArgs());
Assert.IsTrue(TestApplicationEventHandler.Initialized);
Assert.IsTrue(TestApplicationEventHandler.Starting);
Assert.IsTrue(TestApplicationEventHandler.Started);
}
[Test]
public void Ensure_Legacy_Startup_Handlers_Not_Started_Until_Complete()
{
EventHandler starting = (sender, args) =>
{
Assert.IsTrue(TestApplicationEventHandler.Initialized);
Assert.IsTrue(TestApplicationEventHandler.Starting);
Assert.IsFalse(LegacyStartupHandler.Initialized);
};
EventHandler started = (sender, args) =>
{
Assert.IsTrue(TestApplicationEventHandler.Started);
Assert.IsTrue(LegacyStartupHandler.Initialized);
};
TestApp.ApplicationStarting += starting;
TestApp.ApplicationStarted += started;
_testApp.StartApplication(_testApp, new EventArgs());
TestApp.ApplicationStarting -= starting;
TestApp.ApplicationStarting -= started;
}
}
}

View File

@@ -0,0 +1,69 @@
using System.Collections.Generic;
using System.Web.Mvc;
using NUnit.Framework;
using Umbraco.Core.Profiling;
using Umbraco.Web;
using Umbraco.Web.Mvc;
namespace Umbraco.Tests.BootManagers
{
[TestFixture]
public class WebBootManagerTests
{
[Test]
public void WrapViewEngines_HasEngines_WrapsAll()
{
IList<IViewEngine> engines = new List<IViewEngine>
{
new RenderViewEngine(),
new PluginViewEngine()
};
WebBootManager.WrapViewEngines(engines);
Assert.That(engines.Count, Is.EqualTo(2));
Assert.That(engines[0], Is.InstanceOf<ProfilingViewEngine>());
Assert.That(engines[1], Is.InstanceOf<ProfilingViewEngine>());
}
[Test]
public void WrapViewEngines_HasEngines_KeepsSortOrder()
{
IList<IViewEngine> engines = new List<IViewEngine>
{
new RenderViewEngine(),
new PluginViewEngine()
};
WebBootManager.WrapViewEngines(engines);
Assert.That(engines.Count, Is.EqualTo(2));
Assert.That(((ProfilingViewEngine)engines[0]).Inner, Is.InstanceOf<RenderViewEngine>());
Assert.That(((ProfilingViewEngine)engines[1]).Inner, Is.InstanceOf<PluginViewEngine>());
}
[Test]
public void WrapViewEngines_HasProfiledEngine_AddsSameInstance()
{
var profiledEngine = new ProfilingViewEngine(new PluginViewEngine());
IList<IViewEngine> engines = new List<IViewEngine>
{
profiledEngine
};
WebBootManager.WrapViewEngines(engines);
Assert.That(engines[0], Is.SameAs(profiledEngine));
}
[Test]
public void WrapViewEngines_CollectionIsNull_DoesNotThrow()
{
IList<IViewEngine> engines = null;
Assert.DoesNotThrow(() => WebBootManager.WrapViewEngines(engines));
Assert.That(engines, Is.Null);
}
}
}

View File

@@ -1,257 +1,257 @@
using System;
using System.Linq;
using System.Web.UI;
using NUnit.Framework;
using Umbraco.Core.Cache;
using umbraco;
namespace Umbraco.Tests.Cache
{
public abstract class CacheProviderTests
{
internal abstract ICacheProvider Provider { get; }
protected abstract int GetTotalItemCount { get; }
[SetUp]
public virtual void Setup()
{
}
[TearDown]
public virtual void TearDown()
{
Provider.ClearAllCache();
}
[Test]
public void Throws_On_Reentry()
{
// don't run for StaticCacheProvider - not making sense
if (GetType() == typeof (StaticCacheProviderTests))
Assert.Ignore("Do not run for StaticCacheProvider.");
Exception exception = null;
var result = Provider.GetCacheItem("blah", () =>
{
try
{
var result2 = Provider.GetCacheItem("blah");
}
catch (Exception e)
{
exception = e;
}
return "value";
});
Assert.IsNotNull(exception);
Assert.IsAssignableFrom<InvalidOperationException>(exception);
}
[Test]
public void Does_Not_Cache_Exceptions()
{
var counter = 0;
object result;
try
{
result = Provider.GetCacheItem("Blah", () =>
{
counter++;
throw new Exception("Do not cache this");
});
}
catch (Exception){}
try
{
result = Provider.GetCacheItem("Blah", () =>
{
counter++;
throw new Exception("Do not cache this");
});
}
catch (Exception){}
Assert.Greater(counter, 1);
}
[Test]
public void Ensures_Delegate_Result_Is_Cached_Once()
{
var counter = 0;
object result;
result = Provider.GetCacheItem("Blah", () =>
{
counter++;
return "";
});
result = Provider.GetCacheItem("Blah", () =>
{
counter++;
return "";
});
Assert.AreEqual(counter, 1);
}
[Test]
public void Can_Get_By_Search()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Tester2", () => cacheContent2);
Provider.GetCacheItem("Tes3", () => cacheContent3);
Provider.GetCacheItem("different4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
var result = Provider.GetCacheItemsByKeySearch("Tes");
Assert.AreEqual(3, result.Count());
}
[Test]
public void Can_Clear_By_Expression()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("TTes1t", () => cacheContent1);
Provider.GetCacheItem("Tester2", () => cacheContent2);
Provider.GetCacheItem("Tes3", () => cacheContent3);
Provider.GetCacheItem("different4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearCacheByKeyExpression("^\\w+es\\d.*");
Assert.AreEqual(2, GetTotalItemCount);
}
[Test]
public void Can_Clear_By_Search()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Tester2", () => cacheContent2);
Provider.GetCacheItem("Tes3", () => cacheContent3);
Provider.GetCacheItem("different4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearCacheByKeySearch("Test");
Assert.AreEqual(2, GetTotalItemCount);
}
[Test]
public void Can_Clear_By_Key()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Test2", () => cacheContent2);
Provider.GetCacheItem("Test3", () => cacheContent3);
Provider.GetCacheItem("Test4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearCacheItem("Test1");
Provider.ClearCacheItem("Test2");
Assert.AreEqual(2, GetTotalItemCount);
}
[Test]
public void Can_Clear_All_Items()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Test2", () => cacheContent2);
Provider.GetCacheItem("Test3", () => cacheContent3);
Provider.GetCacheItem("Test4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearAllCache();
Assert.AreEqual(0, GetTotalItemCount);
}
[Test]
public void Can_Add_When_Not_Available()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
Provider.GetCacheItem("Test1", () => cacheContent1);
Assert.AreEqual(1, GetTotalItemCount);
}
[Test]
public void Can_Get_When_Available()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var result = Provider.GetCacheItem("Test1", () => cacheContent1);
var result2 = Provider.GetCacheItem("Test1", () => cacheContent1);
Assert.AreEqual(1, GetTotalItemCount);
Assert.AreEqual(result, result2);
}
[Test]
public void Can_Remove_By_Type_Name()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Test2", () => cacheContent2);
Provider.GetCacheItem("Test3", () => cacheContent3);
Provider.GetCacheItem("Test4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
//Provider.ClearCacheObjectTypes("umbraco.MacroCacheContent");
Provider.ClearCacheObjectTypes(typeof(MacroCacheContent).ToString());
Assert.AreEqual(1, GetTotalItemCount);
}
[Test]
public void Can_Remove_By_Strong_Type()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Test2", () => cacheContent2);
Provider.GetCacheItem("Test3", () => cacheContent3);
Provider.GetCacheItem("Test4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearCacheObjectTypes<MacroCacheContent>();
Assert.AreEqual(1, GetTotalItemCount);
}
}
}
using System;
using System.Linq;
using System.Web.UI;
using NUnit.Framework;
using Umbraco.Core.Cache;
using umbraco;
namespace Umbraco.Tests.Cache
{
public abstract class CacheProviderTests
{
internal abstract ICacheProvider Provider { get; }
protected abstract int GetTotalItemCount { get; }
[SetUp]
public virtual void Setup()
{
}
[TearDown]
public virtual void TearDown()
{
Provider.ClearAllCache();
}
[Test]
public void Throws_On_Reentry()
{
// don't run for StaticCacheProvider - not making sense
if (GetType() == typeof (StaticCacheProviderTests))
Assert.Ignore("Do not run for StaticCacheProvider.");
Exception exception = null;
var result = Provider.GetCacheItem("blah", () =>
{
try
{
var result2 = Provider.GetCacheItem("blah");
}
catch (Exception e)
{
exception = e;
}
return "value";
});
Assert.IsNotNull(exception);
Assert.IsAssignableFrom<InvalidOperationException>(exception);
}
[Test]
public void Does_Not_Cache_Exceptions()
{
var counter = 0;
object result;
try
{
result = Provider.GetCacheItem("Blah", () =>
{
counter++;
throw new Exception("Do not cache this");
});
}
catch (Exception){}
try
{
result = Provider.GetCacheItem("Blah", () =>
{
counter++;
throw new Exception("Do not cache this");
});
}
catch (Exception){}
Assert.Greater(counter, 1);
}
[Test]
public void Ensures_Delegate_Result_Is_Cached_Once()
{
var counter = 0;
object result;
result = Provider.GetCacheItem("Blah", () =>
{
counter++;
return "";
});
result = Provider.GetCacheItem("Blah", () =>
{
counter++;
return "";
});
Assert.AreEqual(counter, 1);
}
[Test]
public void Can_Get_By_Search()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Tester2", () => cacheContent2);
Provider.GetCacheItem("Tes3", () => cacheContent3);
Provider.GetCacheItem("different4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
var result = Provider.GetCacheItemsByKeySearch("Tes");
Assert.AreEqual(3, result.Count());
}
[Test]
public void Can_Clear_By_Expression()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("TTes1t", () => cacheContent1);
Provider.GetCacheItem("Tester2", () => cacheContent2);
Provider.GetCacheItem("Tes3", () => cacheContent3);
Provider.GetCacheItem("different4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearCacheByKeyExpression("^\\w+es\\d.*");
Assert.AreEqual(2, GetTotalItemCount);
}
[Test]
public void Can_Clear_By_Search()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Tester2", () => cacheContent2);
Provider.GetCacheItem("Tes3", () => cacheContent3);
Provider.GetCacheItem("different4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearCacheByKeySearch("Test");
Assert.AreEqual(2, GetTotalItemCount);
}
[Test]
public void Can_Clear_By_Key()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Test2", () => cacheContent2);
Provider.GetCacheItem("Test3", () => cacheContent3);
Provider.GetCacheItem("Test4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearCacheItem("Test1");
Provider.ClearCacheItem("Test2");
Assert.AreEqual(2, GetTotalItemCount);
}
[Test]
public void Can_Clear_All_Items()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Test2", () => cacheContent2);
Provider.GetCacheItem("Test3", () => cacheContent3);
Provider.GetCacheItem("Test4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearAllCache();
Assert.AreEqual(0, GetTotalItemCount);
}
[Test]
public void Can_Add_When_Not_Available()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
Provider.GetCacheItem("Test1", () => cacheContent1);
Assert.AreEqual(1, GetTotalItemCount);
}
[Test]
public void Can_Get_When_Available()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var result = Provider.GetCacheItem("Test1", () => cacheContent1);
var result2 = Provider.GetCacheItem("Test1", () => cacheContent1);
Assert.AreEqual(1, GetTotalItemCount);
Assert.AreEqual(result, result2);
}
[Test]
public void Can_Remove_By_Type_Name()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Test2", () => cacheContent2);
Provider.GetCacheItem("Test3", () => cacheContent3);
Provider.GetCacheItem("Test4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
//Provider.ClearCacheObjectTypes("umbraco.MacroCacheContent");
Provider.ClearCacheObjectTypes(typeof(MacroCacheContent).ToString());
Assert.AreEqual(1, GetTotalItemCount);
}
[Test]
public void Can_Remove_By_Strong_Type()
{
var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1");
var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2");
var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3");
var cacheContent4 = new LiteralControl();
Provider.GetCacheItem("Test1", () => cacheContent1);
Provider.GetCacheItem("Test2", () => cacheContent2);
Provider.GetCacheItem("Test3", () => cacheContent3);
Provider.GetCacheItem("Test4", () => cacheContent4);
Assert.AreEqual(4, GetTotalItemCount);
Provider.ClearCacheObjectTypes<MacroCacheContent>();
Assert.AreEqual(1, GetTotalItemCount);
}
}
}

View File

@@ -1,32 +1,22 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core.Composing;
using Umbraco.Core.Events;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.Testing;
using Umbraco.Web.Cache;
using System.Linq;
namespace Umbraco.Tests.Cache
{
[TestFixture]
[UmbracoTest(WithApplication = true)]
public class CacheRefresherEventHandlerTests : UmbracoTestBase
public class CacheRefresherEventHandlerTests : BaseUmbracoApplicationTest
{
[Test]
public void Can_Find_All_Event_Handlers()
{
// fixme - cannot work with mocks
// because the events are defined on actual static classes, not on the interfaces, so name matching fails
// we should really refactor events entirely - in the meantime, let it be an UmbracoTestBase ;(
//var testObjects = new TestObjects(null);
//var serviceContext = testObjects.GetServiceContextMock();
var serviceContext = Current.Services;
var definitions = new IEventDefinition[]
{
//I would test these but they are legacy events and we don't need them for deploy, when we migrate to new/better events we can wire up the check
@@ -35,93 +25,85 @@ namespace Umbraco.Tests.Cache
//Permission.Deleted += PermissionDeleted;
//PermissionRepository<IContent>.AssignedPermissions += CacheRefresherEventHandler_AssignedPermissions;
new EventDefinition<IApplicationTreeService, EventArgs>(null, serviceContext.ApplicationTreeService, new EventArgs(), "Deleted"),
new EventDefinition<IApplicationTreeService, EventArgs>(null, serviceContext.ApplicationTreeService, new EventArgs(), "Updated"),
new EventDefinition<IApplicationTreeService, EventArgs>(null, serviceContext.ApplicationTreeService, new EventArgs(), "New"),
new EventDefinition<IApplicationTreeService, EventArgs>(null, ServiceContext.ApplicationTreeService, new EventArgs(), "Deleted"),
new EventDefinition<IApplicationTreeService, EventArgs>(null, ServiceContext.ApplicationTreeService, new EventArgs(), "Updated"),
new EventDefinition<IApplicationTreeService, EventArgs>(null, ServiceContext.ApplicationTreeService, new EventArgs(), "New"),
new EventDefinition<ISectionService, EventArgs>(null, serviceContext.SectionService, new EventArgs(), "Deleted"),
new EventDefinition<ISectionService, EventArgs>(null, serviceContext.SectionService, new EventArgs(), "New"),
new EventDefinition<ISectionService, EventArgs>(null, ServiceContext.SectionService, new EventArgs(), "Deleted"),
new EventDefinition<ISectionService, EventArgs>(null, ServiceContext.SectionService, new EventArgs(), "New"),
new EventDefinition<IUserService, SaveEventArgs<IUser>>(null, ServiceContext.UserService, new SaveEventArgs<IUser>(Enumerable.Empty<IUser>())),
new EventDefinition<IUserService, DeleteEventArgs<IUser>>(null, ServiceContext.UserService, new DeleteEventArgs<IUser>(Enumerable.Empty<IUser>())),
new EventDefinition<IUserService, SaveEventArgs<IUserGroup>>(null, ServiceContext.UserService, new SaveEventArgs<IUserGroup>(Enumerable.Empty<IUserGroup>())),
new EventDefinition<IUserService, DeleteEventArgs<IUserGroup>>(null, ServiceContext.UserService, new DeleteEventArgs<IUserGroup>(Enumerable.Empty<IUserGroup>())),
new EventDefinition<IUserService, SaveEventArgs<IUser>>(null, serviceContext.UserService, new SaveEventArgs<IUser>(Enumerable.Empty<IUser>())),
new EventDefinition<IUserService, DeleteEventArgs<IUser>>(null, serviceContext.UserService, new DeleteEventArgs<IUser>(Enumerable.Empty<IUser>())),
new EventDefinition<IUserService, SaveEventArgs<UserGroupWithUsers>>(null, serviceContext.UserService, new SaveEventArgs<UserGroupWithUsers>(Enumerable.Empty<UserGroupWithUsers>())),
new EventDefinition<IUserService, DeleteEventArgs<IUserGroup>>(null, serviceContext.UserService, new DeleteEventArgs<IUserGroup>(Enumerable.Empty<IUserGroup>())),
new EventDefinition<ILocalizationService, SaveEventArgs<IDictionaryItem>>(null, ServiceContext.LocalizationService, new SaveEventArgs<IDictionaryItem>(Enumerable.Empty<IDictionaryItem>())),
new EventDefinition<ILocalizationService, DeleteEventArgs<IDictionaryItem>>(null, ServiceContext.LocalizationService, new DeleteEventArgs<IDictionaryItem>(Enumerable.Empty<IDictionaryItem>())),
new EventDefinition<ILocalizationService, SaveEventArgs<IDictionaryItem>>(null, serviceContext.LocalizationService, new SaveEventArgs<IDictionaryItem>(Enumerable.Empty<IDictionaryItem>())),
new EventDefinition<ILocalizationService, DeleteEventArgs<IDictionaryItem>>(null, serviceContext.LocalizationService, new DeleteEventArgs<IDictionaryItem>(Enumerable.Empty<IDictionaryItem>())),
new EventDefinition<IDataTypeService, SaveEventArgs<IDataTypeDefinition>>(null, ServiceContext.DataTypeService, new SaveEventArgs<IDataTypeDefinition>(Enumerable.Empty<IDataTypeDefinition>())),
new EventDefinition<IDataTypeService, DeleteEventArgs<IDataTypeDefinition>>(null, ServiceContext.DataTypeService, new DeleteEventArgs<IDataTypeDefinition>(Enumerable.Empty<IDataTypeDefinition>())),
new EventDefinition<IDataTypeService, SaveEventArgs<IDataType>>(null, serviceContext.DataTypeService, new SaveEventArgs<IDataType>(Enumerable.Empty<IDataType>())),
new EventDefinition<IDataTypeService, DeleteEventArgs<IDataType>>(null, serviceContext.DataTypeService, new DeleteEventArgs<IDataType>(Enumerable.Empty<IDataType>())),
new EventDefinition<IFileService, SaveEventArgs<Stylesheet>>(null, ServiceContext.FileService, new SaveEventArgs<Stylesheet>(Enumerable.Empty<Stylesheet>())),
new EventDefinition<IFileService, DeleteEventArgs<Stylesheet>>(null, ServiceContext.FileService, new DeleteEventArgs<Stylesheet>(Enumerable.Empty<Stylesheet>())),
new EventDefinition<IFileService, SaveEventArgs<Stylesheet>>(null, serviceContext.FileService, new SaveEventArgs<Stylesheet>(Enumerable.Empty<Stylesheet>())),
new EventDefinition<IFileService, DeleteEventArgs<Stylesheet>>(null, serviceContext.FileService, new DeleteEventArgs<Stylesheet>(Enumerable.Empty<Stylesheet>())),
new EventDefinition<IDomainService, SaveEventArgs<IDomain>>(null, ServiceContext.DomainService, new SaveEventArgs<IDomain>(Enumerable.Empty<IDomain>())),
new EventDefinition<IDomainService, DeleteEventArgs<IDomain>>(null, ServiceContext.DomainService, new DeleteEventArgs<IDomain>(Enumerable.Empty<IDomain>())),
new EventDefinition<IDomainService, SaveEventArgs<IDomain>>(null, serviceContext.DomainService, new SaveEventArgs<IDomain>(Enumerable.Empty<IDomain>())),
new EventDefinition<IDomainService, DeleteEventArgs<IDomain>>(null, serviceContext.DomainService, new DeleteEventArgs<IDomain>(Enumerable.Empty<IDomain>())),
new EventDefinition<ILocalizationService, SaveEventArgs<ILanguage>>(null, ServiceContext.LocalizationService, new SaveEventArgs<ILanguage>(Enumerable.Empty<ILanguage>())),
new EventDefinition<ILocalizationService, DeleteEventArgs<ILanguage>>(null, ServiceContext.LocalizationService, new DeleteEventArgs<ILanguage>(Enumerable.Empty<ILanguage>())),
new EventDefinition<ILocalizationService, SaveEventArgs<ILanguage>>(null, serviceContext.LocalizationService, new SaveEventArgs<ILanguage>(Enumerable.Empty<ILanguage>())),
new EventDefinition<ILocalizationService, DeleteEventArgs<ILanguage>>(null, serviceContext.LocalizationService, new DeleteEventArgs<ILanguage>(Enumerable.Empty<ILanguage>())),
new EventDefinition<IContentTypeService, SaveEventArgs<IContentType>>(null, ServiceContext.ContentTypeService, new SaveEventArgs<IContentType>(Enumerable.Empty<IContentType>())),
new EventDefinition<IContentTypeService, DeleteEventArgs<IContentType>>(null, ServiceContext.ContentTypeService, new DeleteEventArgs<IContentType>(Enumerable.Empty<IContentType>())),
new EventDefinition<IContentTypeService, SaveEventArgs<IMediaType>>(null, ServiceContext.ContentTypeService, new SaveEventArgs<IMediaType>(Enumerable.Empty<IMediaType>())),
new EventDefinition<IContentTypeService, DeleteEventArgs<IMediaType>>(null, ServiceContext.ContentTypeService, new DeleteEventArgs<IMediaType>(Enumerable.Empty<IMediaType>())),
new EventDefinition<IContentTypeService, SaveEventArgs<IContentType>>(null, serviceContext.ContentTypeService, new SaveEventArgs<IContentType>(Enumerable.Empty<IContentType>())),
new EventDefinition<IContentTypeService, DeleteEventArgs<IContentType>>(null, serviceContext.ContentTypeService, new DeleteEventArgs<IContentType>(Enumerable.Empty<IContentType>())),
new EventDefinition<IMediaTypeService, SaveEventArgs<IMediaType>>(null, serviceContext.MediaTypeService, new SaveEventArgs<IMediaType>(Enumerable.Empty<IMediaType>())),
new EventDefinition<IMediaTypeService, DeleteEventArgs<IMediaType>>(null, serviceContext.MediaTypeService, new DeleteEventArgs<IMediaType>(Enumerable.Empty<IMediaType>())),
new EventDefinition<IMemberTypeService, SaveEventArgs<IMemberType>>(null, ServiceContext.MemberTypeService, new SaveEventArgs<IMemberType>(Enumerable.Empty<IMemberType>())),
new EventDefinition<IMemberTypeService, DeleteEventArgs<IMemberType>>(null, ServiceContext.MemberTypeService, new DeleteEventArgs<IMemberType>(Enumerable.Empty<IMemberType>())),
new EventDefinition<IMemberTypeService, SaveEventArgs<IMemberType>>(null, serviceContext.MemberTypeService, new SaveEventArgs<IMemberType>(Enumerable.Empty<IMemberType>())),
new EventDefinition<IMemberTypeService, DeleteEventArgs<IMemberType>>(null, serviceContext.MemberTypeService, new DeleteEventArgs<IMemberType>(Enumerable.Empty<IMemberType>())),
new EventDefinition<IFileService, SaveEventArgs<ITemplate>>(null, ServiceContext.FileService, new SaveEventArgs<ITemplate>(Enumerable.Empty<ITemplate>())),
new EventDefinition<IFileService, DeleteEventArgs<ITemplate>>(null, ServiceContext.FileService, new DeleteEventArgs<ITemplate>(Enumerable.Empty<ITemplate>())),
new EventDefinition<IFileService, SaveEventArgs<ITemplate>>(null, serviceContext.FileService, new SaveEventArgs<ITemplate>(Enumerable.Empty<ITemplate>())),
new EventDefinition<IFileService, DeleteEventArgs<ITemplate>>(null, serviceContext.FileService, new DeleteEventArgs<ITemplate>(Enumerable.Empty<ITemplate>())),
new EventDefinition<IMacroService, SaveEventArgs<IMacro>>(null, ServiceContext.MacroService, new SaveEventArgs<IMacro>(Enumerable.Empty<IMacro>())),
new EventDefinition<IMacroService, DeleteEventArgs<IMacro>>(null, ServiceContext.MacroService, new DeleteEventArgs<IMacro>(Enumerable.Empty<IMacro>())),
new EventDefinition<IMacroService, SaveEventArgs<IMacro>>(null, serviceContext.MacroService, new SaveEventArgs<IMacro>(Enumerable.Empty<IMacro>())),
new EventDefinition<IMacroService, DeleteEventArgs<IMacro>>(null, serviceContext.MacroService, new DeleteEventArgs<IMacro>(Enumerable.Empty<IMacro>())),
new EventDefinition<IMemberService, SaveEventArgs<IMember>>(null, ServiceContext.MemberService, new SaveEventArgs<IMember>(Enumerable.Empty<IMember>())),
new EventDefinition<IMemberService, DeleteEventArgs<IMember>>(null, ServiceContext.MemberService, new DeleteEventArgs<IMember>(Enumerable.Empty<IMember>())),
new EventDefinition<IMemberService, SaveEventArgs<IMember>>(null, serviceContext.MemberService, new SaveEventArgs<IMember>(Enumerable.Empty<IMember>())),
new EventDefinition<IMemberService, DeleteEventArgs<IMember>>(null, serviceContext.MemberService, new DeleteEventArgs<IMember>(Enumerable.Empty<IMember>())),
new EventDefinition<IMemberGroupService, SaveEventArgs<IMemberGroup>>(null, ServiceContext.MemberGroupService, new SaveEventArgs<IMemberGroup>(Enumerable.Empty<IMemberGroup>())),
new EventDefinition<IMemberGroupService, DeleteEventArgs<IMemberGroup>>(null, ServiceContext.MemberGroupService, new DeleteEventArgs<IMemberGroup>(Enumerable.Empty<IMemberGroup>())),
new EventDefinition<IMemberGroupService, SaveEventArgs<IMemberGroup>>(null, serviceContext.MemberGroupService, new SaveEventArgs<IMemberGroup>(Enumerable.Empty<IMemberGroup>())),
new EventDefinition<IMemberGroupService, DeleteEventArgs<IMemberGroup>>(null, serviceContext.MemberGroupService, new DeleteEventArgs<IMemberGroup>(Enumerable.Empty<IMemberGroup>())),
new EventDefinition<IMediaService, SaveEventArgs<IMedia>>(null, ServiceContext.MediaService, new SaveEventArgs<IMedia>(Enumerable.Empty<IMedia>())),
new EventDefinition<IMediaService, DeleteEventArgs<IMedia>>(null, ServiceContext.MediaService, new DeleteEventArgs<IMedia>(Enumerable.Empty<IMedia>())),
new EventDefinition<IMediaService, MoveEventArgs<IMedia>>(null, ServiceContext.MediaService, new MoveEventArgs<IMedia>(new MoveEventInfo<IMedia>(null, "", -1)), "Moved"),
new EventDefinition<IMediaService, MoveEventArgs<IMedia>>(null, ServiceContext.MediaService, new MoveEventArgs<IMedia>(new MoveEventInfo<IMedia>(null, "", -1)), "Trashed"),
new EventDefinition<IMediaService, RecycleBinEventArgs>(null, ServiceContext.MediaService, new RecycleBinEventArgs(Guid.NewGuid(), new Dictionary<int, IEnumerable<Property>>(), true)),
new EventDefinition<IMediaService, SaveEventArgs<IMedia>>(null, serviceContext.MediaService, new SaveEventArgs<IMedia>(Enumerable.Empty<IMedia>())),
new EventDefinition<IMediaService, DeleteEventArgs<IMedia>>(null, serviceContext.MediaService, new DeleteEventArgs<IMedia>(Enumerable.Empty<IMedia>())),
new EventDefinition<IMediaService, MoveEventArgs<IMedia>>(null, serviceContext.MediaService, new MoveEventArgs<IMedia>(new MoveEventInfo<IMedia>(null, "", -1)), "Moved"),
new EventDefinition<IMediaService, MoveEventArgs<IMedia>>(null, serviceContext.MediaService, new MoveEventArgs<IMedia>(new MoveEventInfo<IMedia>(null, "", -1)), "Trashed"),
new EventDefinition<IMediaService, RecycleBinEventArgs>(null, serviceContext.MediaService, new RecycleBinEventArgs(Guid.NewGuid())),
new EventDefinition<IContentService, SaveEventArgs<IContent>>(null, ServiceContext.ContentService, new SaveEventArgs<IContent>(Enumerable.Empty<IContent>()), "Saved"),
new EventDefinition<IContentService, SaveEventArgs<IContent>>(null, ServiceContext.ContentService, new SaveEventArgs<IContent>(Enumerable.Empty<IContent>()), "SavedBlueprint"),
new EventDefinition<IContentService, DeleteEventArgs<IContent>>(null, ServiceContext.ContentService, new DeleteEventArgs<IContent>(Enumerable.Empty<IContent>()), "Deleted"),
new EventDefinition<IContentService, DeleteEventArgs<IContent>>(null, ServiceContext.ContentService, new DeleteEventArgs<IContent>(Enumerable.Empty<IContent>()), "DeletedBlueprint"),
new EventDefinition<IContentService, CopyEventArgs<IContent>>(null, ServiceContext.ContentService, new CopyEventArgs<IContent>(null, null, -1)),
new EventDefinition<IContentService, MoveEventArgs<IContent>>(null, ServiceContext.ContentService, new MoveEventArgs<IContent>(new MoveEventInfo<IContent>(null, "", -1)), "Trashed"),
new EventDefinition<IContentService, RecycleBinEventArgs>(null, ServiceContext.ContentService, new RecycleBinEventArgs(Guid.NewGuid(), new Dictionary<int, IEnumerable<Property>>(), true)),
new EventDefinition<IContentService, PublishEventArgs<IContent>>(null, ServiceContext.ContentService, new PublishEventArgs<IContent>(Enumerable.Empty<IContent>()), "Published"),
new EventDefinition<IContentService, PublishEventArgs<IContent>>(null, ServiceContext.ContentService, new PublishEventArgs<IContent>(Enumerable.Empty<IContent>()), "UnPublished"),
new EventDefinition<IContentService, SaveEventArgs<IContent>>(null, serviceContext.ContentService, new SaveEventArgs<IContent>(Enumerable.Empty<IContent>()), "Saved"),
new EventDefinition<IContentService, DeleteEventArgs<IContent>>(null, serviceContext.ContentService, new DeleteEventArgs<IContent>(Enumerable.Empty<IContent>()), "Deleted"),
new EventDefinition<IPublicAccessService, SaveEventArgs<PublicAccessEntry>>(null, ServiceContext.PublicAccessService, new SaveEventArgs<PublicAccessEntry>(Enumerable.Empty<PublicAccessEntry>())),
new EventDefinition<IPublicAccessService, DeleteEventArgs<PublicAccessEntry>>(null, ServiceContext.PublicAccessService, new DeleteEventArgs<PublicAccessEntry>(Enumerable.Empty<PublicAccessEntry>())),
// not managed
//new EventDefinition<IContentService, SaveEventArgs<IContent>>(null, serviceContext.ContentService, new SaveEventArgs<IContent>(Enumerable.Empty<IContent>()), "SavedBlueprint"),
//new EventDefinition<IContentService, DeleteEventArgs<IContent>>(null, serviceContext.ContentService, new DeleteEventArgs<IContent>(Enumerable.Empty<IContent>()), "DeletedBlueprint"),
new EventDefinition<IRelationService, SaveEventArgs<IRelationType>>(null, ServiceContext.RelationService, new SaveEventArgs<IRelationType>(Enumerable.Empty<IRelationType>())),
new EventDefinition<IRelationService, DeleteEventArgs<IRelationType>>(null, ServiceContext.RelationService, new DeleteEventArgs<IRelationType>(Enumerable.Empty<IRelationType>())),
new EventDefinition<IContentService, CopyEventArgs<IContent>>(null, serviceContext.ContentService, new CopyEventArgs<IContent>(null, null, -1)),
new EventDefinition<IContentService, MoveEventArgs<IContent>>(null, serviceContext.ContentService, new MoveEventArgs<IContent>(new MoveEventInfo<IContent>(null, "", -1)), "Trashed"),
new EventDefinition<IContentService, RecycleBinEventArgs>(null, serviceContext.ContentService, new RecycleBinEventArgs(Guid.NewGuid())),
new EventDefinition<IContentService, PublishEventArgs<IContent>>(null, serviceContext.ContentService, new PublishEventArgs<IContent>(Enumerable.Empty<IContent>()), "Published"),
new EventDefinition<IContentService, PublishEventArgs<IContent>>(null, serviceContext.ContentService, new PublishEventArgs<IContent>(Enumerable.Empty<IContent>()), "Unpublished"),
new EventDefinition<IPublicAccessService, SaveEventArgs<PublicAccessEntry>>(null, serviceContext.PublicAccessService, new SaveEventArgs<PublicAccessEntry>(Enumerable.Empty<PublicAccessEntry>())),
new EventDefinition<IPublicAccessService, DeleteEventArgs<PublicAccessEntry>>(null, serviceContext.PublicAccessService, new DeleteEventArgs<PublicAccessEntry>(Enumerable.Empty<PublicAccessEntry>())),
new EventDefinition<IRelationService, SaveEventArgs<IRelationType>>(null, serviceContext.RelationService, new SaveEventArgs<IRelationType>(Enumerable.Empty<IRelationType>())),
new EventDefinition<IRelationService, DeleteEventArgs<IRelationType>>(null, serviceContext.RelationService, new DeleteEventArgs<IRelationType>(Enumerable.Empty<IRelationType>())),
new EventDefinition<IRelationService, SaveEventArgs<IRelationType>>(null, serviceContext.RelationService, new SaveEventArgs<IRelationType>(Enumerable.Empty<IRelationType>())),
new EventDefinition<IRelationService, DeleteEventArgs<IRelationType>>(null, serviceContext.RelationService, new DeleteEventArgs<IRelationType>(Enumerable.Empty<IRelationType>())),
new EventDefinition<IRelationService, SaveEventArgs<IRelationType>>(null, ServiceContext.RelationService, new SaveEventArgs<IRelationType>(Enumerable.Empty<IRelationType>())),
new EventDefinition<IRelationService, DeleteEventArgs<IRelationType>>(null, ServiceContext.RelationService, new DeleteEventArgs<IRelationType>(Enumerable.Empty<IRelationType>())),
};
var ok = true;
foreach (var definition in definitions)
{
var found = CacheRefresherComponent.FindHandler(definition);
if (found == null)
{
Console.WriteLine("Couldn't find method for " + definition.EventName + " on " + definition.Sender.GetType());
ok = false;
}
var found = CacheRefresherEventHandler.FindHandler(definition);
Assert.IsNotNull(found, "Couldn't find method for " + definition.EventName + " on " + definition.Sender.GetType());
}
Assert.IsTrue(ok, "see log for details");
}
}
}
}

View File

@@ -0,0 +1,31 @@
using System;
using NUnit.Framework;
using Umbraco.Core.Sync;
using umbraco.presentation.webservices;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class CacheRefresherTests
{
[TestCase("", "123456", "testmachine", true)] //empty hash will continue
[TestCase("2e6deefea4444a69dbd15a01b4c2749d", "123456", "testmachine", false)] //match, don't continue
[TestCase("2e6deefea4444a69dbd15a01b4c2749d", "12345", "testmachine", true)] // no match, continue
[TestCase("2e6deefea4444a69dbd15a01b4c2749d", "123456", "testmachin", true)] // same
[TestCase("2e6deefea4444a69dbd15a01b4c2749", "123456", "testmachine", true)] // same
public void Continue_Refreshing_For_Request(string hash, string appDomainAppId, string machineName, bool expected)
{
if (expected)
Assert.IsTrue(Continue(hash, WebServiceServerMessenger.GetServerHash(appDomainAppId, machineName)));
else
Assert.IsFalse(Continue(hash, WebServiceServerMessenger.GetServerHash(appDomainAppId, machineName)));
}
// that's what CacheRefresher.asmx.cs does...
private bool Continue(string hash1, string hash2)
{
if (string.IsNullOrEmpty(hash1)) return true;
return hash1 != hash2;
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Web;
@@ -7,7 +7,7 @@ using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Collections;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Entities;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Tests.Collections;
@@ -66,7 +66,7 @@ namespace Umbraco.Tests.Cache
Assert.IsTrue(original.IsDirty());
var val = _provider.GetCacheItem<TestClass>("test", () => original);
Assert.AreNotEqual(original.CloneId, val.CloneId);
Assert.IsFalse(val.IsDirty());
}
@@ -95,7 +95,7 @@ namespace Umbraco.Tests.Cache
return "succ" + i;
}
private class TestClass : BeingDirtyBase, IDeepCloneable
private class TestClass : TracksChangesEntityBase, IDeepCloneable
{
public TestClass()
{
@@ -127,4 +127,4 @@ namespace Umbraco.Tests.Cache
}
}
}
}
}

View File

@@ -1,29 +1,16 @@
using System;
using System;
using System.Collections.Generic;
using System.Web.Caching;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;
using Umbraco.Core.Scoping;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class DefaultCachePolicyTests
{
private IScopeAccessor DefaultAccessor
{
get
{
var accessor = new Mock<IScopeAccessor>();
var scope = new Mock<IScope>();
scope.Setup(x => x.RepositoryCacheMode).Returns(RepositoryCacheMode.Default);
accessor.Setup(x => x.AmbientScope).Returns(scope.Object);
return accessor.Object;
}
}
[Test]
public void Caches_Single()
{
@@ -36,9 +23,9 @@ namespace Umbraco.Tests.Cache
isCached = true;
});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
var unused = defaultPolicy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), o => null);
var found = defaultPolicy.Get(1, id => new AuditItem(1, "blah", AuditType.Copy, 123), o => null);
Assert.IsTrue(isCached);
}
@@ -46,9 +33,9 @@ namespace Umbraco.Tests.Cache
public void Get_Single_From_Cache()
{
var cache = new Mock<IRuntimeCacheProvider>();
cache.Setup(x => x.GetCacheItem(It.IsAny<string>())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah"));
cache.Setup(x => x.GetCacheItem(It.IsAny<string>())).Returns(new AuditItem(1, "blah", AuditType.Copy, 123));
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
var found = defaultPolicy.Get(1, id => null, ids => null);
Assert.IsNotNull(found);
@@ -67,13 +54,13 @@ namespace Umbraco.Tests.Cache
});
cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny<string>())).Returns(new AuditItem[] {});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
var unused = defaultPolicy.GetAll(new object[] {}, ids => new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
});
var found = defaultPolicy.GetAll(new object[] { }, ids => new[]
{
new AuditItem(1, "blah", AuditType.Copy, 123),
new AuditItem(2, "blah2", AuditType.Copy, 123)
});
Assert.AreEqual(2, cached.Count);
}
@@ -84,13 +71,13 @@ namespace Umbraco.Tests.Cache
var cache = new Mock<IRuntimeCacheProvider>();
cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny<string>())).Returns(new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
new AuditItem(1, "blah", AuditType.Copy, 123),
new AuditItem(2, "blah2", AuditType.Copy, 123)
});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
var found = defaultPolicy.GetAll(new object[] {}, ids => new[] { (AuditItem)null });
var found = defaultPolicy.GetAll(new object[] { }, ids => new[] { (AuditItem)null });
Assert.AreEqual(2, found.Length);
}
@@ -105,10 +92,10 @@ namespace Umbraco.Tests.Cache
cacheCleared = true;
});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
try
{
defaultPolicy.Update(new AuditItem(1, AuditType.Copy, 123, "test", "blah"), item => throw new Exception("blah!"));
defaultPolicy.Update(new AuditItem(1, "blah", AuditType.Copy, 123), item => { throw new Exception("blah!"); });
}
catch
{
@@ -131,10 +118,10 @@ namespace Umbraco.Tests.Cache
cacheCleared = true;
});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
try
{
defaultPolicy.Delete(new AuditItem(1, AuditType.Copy, 123, "test", "blah"), item => throw new Exception("blah!"));
defaultPolicy.Delete(new AuditItem(1, "blah", AuditType.Copy, 123), item => { throw new Exception("blah!"); });
}
catch
{
@@ -146,4 +133,4 @@ namespace Umbraco.Tests.Cache
}
}
}
}
}

View File

@@ -1,10 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using LightInject;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using umbraco.interfaces;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.ObjectResolution;
using Umbraco.Core.Sync;
namespace Umbraco.Tests.Cache.DistributedCache
@@ -15,27 +17,24 @@ namespace Umbraco.Tests.Cache.DistributedCache
[TestFixture]
public class DistributedCacheTests
{
private Umbraco.Web.Cache.DistributedCache _distributedCache;
[SetUp]
public void Setup()
{
var container = new ServiceContainer();
container.ConfigureUmbracoCore();
container.Register<IServerRegistrar>(_ => new TestServerRegistrar());
container.Register<IServerMessenger>(_ => new TestServerMessenger(), new PerContainerLifetime());
container.RegisterCollectionBuilder<CacheRefresherCollectionBuilder>()
.Add<TestCacheRefresher>();
_distributedCache = new Umbraco.Web.Cache.DistributedCache();
ServerRegistrarResolver.Current = new ServerRegistrarResolver(
new TestServerRegistrar());
ServerMessengerResolver.Current = new ServerMessengerResolver(
new TestServerMessenger());
CacheRefreshersResolver.Current = new CacheRefreshersResolver(
new ActivatorServiceProvider(), Mock.Of<ILogger>(), () => new[] { typeof(TestCacheRefresher) });
Resolution.Freeze();
}
[TearDown]
public void Teardown()
{
Current.Reset();
ServerRegistrarResolver.Reset();
ServerMessengerResolver.Reset();
CacheRefreshersResolver.Reset();
}
[Test]
@@ -43,9 +42,9 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 1; i < 11; i++)
{
_distributedCache.Refresh(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), i);
global::Umbraco.Web.Cache.DistributedCache.Instance.Refresh(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), i);
}
Assert.AreEqual(10, ((TestServerMessenger)Current.ServerMessenger).IntIdsRefreshed.Count);
Assert.AreEqual(10, ((TestServerMessenger)ServerMessengerResolver.Current.Messenger).IntIdsRefreshed.Count);
}
[Test]
@@ -53,12 +52,12 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 0; i < 10; i++)
{
_distributedCache.Refresh(
global::Umbraco.Web.Cache.DistributedCache.Instance.Refresh(
Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"),
x => x.Id,
new TestObjectWithId{Id = i});
}
Assert.AreEqual(10, ((TestServerMessenger)Current.ServerMessenger).IntIdsRefreshed.Count);
Assert.AreEqual(10, ((TestServerMessenger)ServerMessengerResolver.Current.Messenger).IntIdsRefreshed.Count);
}
[Test]
@@ -66,9 +65,9 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 0; i < 11; i++)
{
_distributedCache.Refresh(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), Guid.NewGuid());
global::Umbraco.Web.Cache.DistributedCache.Instance.Refresh(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), Guid.NewGuid());
}
Assert.AreEqual(11, ((TestServerMessenger)Current.ServerMessenger).GuidIdsRefreshed.Count);
Assert.AreEqual(11, ((TestServerMessenger)ServerMessengerResolver.Current.Messenger).GuidIdsRefreshed.Count);
}
[Test]
@@ -76,9 +75,9 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 1; i < 13; i++)
{
_distributedCache.Remove(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), i);
global::Umbraco.Web.Cache.DistributedCache.Instance.Remove(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"), i);
}
Assert.AreEqual(12, ((TestServerMessenger)Current.ServerMessenger).IntIdsRemoved.Count);
Assert.AreEqual(12, ((TestServerMessenger)ServerMessengerResolver.Current.Messenger).IntIdsRemoved.Count);
}
[Test]
@@ -86,9 +85,9 @@ namespace Umbraco.Tests.Cache.DistributedCache
{
for (var i = 0; i < 13; i++)
{
_distributedCache.RefreshAll(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"));
global::Umbraco.Web.Cache.DistributedCache.Instance.RefreshAll(Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"));
}
Assert.AreEqual(13, ((TestServerMessenger)Current.ServerMessenger).CountOfFullRefreshes);
Assert.AreEqual(13, ((TestServerMessenger)ServerMessengerResolver.Current.Messenger).CountOfFullRefreshes);
}
#region internal test classes
@@ -100,81 +99,91 @@ namespace Umbraco.Tests.Cache.DistributedCache
internal class TestCacheRefresher : ICacheRefresher
{
public static readonly Guid UniqueId = Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73");
public Guid RefresherUniqueId => UniqueId;
public string Name => "Test Cache Refresher";
public Guid UniqueIdentifier
{
get { return Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"); }
}
public string Name
{
get { return "Test"; }
}
public void RefreshAll()
{ }
{
}
public void Refresh(int id)
{ }
{
}
public void Remove(int id)
{ }
{
}
public void Refresh(Guid id)
{ }
{
}
}
internal class TestServerMessenger : IServerMessenger
{
//used for tests
public List<int> IntIdsRefreshed = new List<int>();
public List<int> IntIdsRefreshed = new List<int>();
public List<Guid> GuidIdsRefreshed = new List<Guid>();
public List<int> IntIdsRemoved = new List<int>();
public List<string> PayloadsRemoved = new List<string>();
public List<string> PayloadsRefreshed = new List<string>();
public List<string> PayloadsRefreshed = new List<string>();
public int CountOfFullRefreshes = 0;
public void PerformRefresh<TPayload>(ICacheRefresher refresher, TPayload[] payload)
public void PerformRefresh(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, object payload)
{
// doing nothing
}
public void PerformRefresh(ICacheRefresher refresher, string jsonPayload)
public void PerformRefresh(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, string jsonPayload)
{
PayloadsRefreshed.Add(jsonPayload);
}
public void PerformRefresh<T>(ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances)
public void PerformRefresh<T>(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances)
{
IntIdsRefreshed.AddRange(instances.Select(getNumericId));
}
public void PerformRefresh<T>(ICacheRefresher refresher, Func<T, Guid> getGuidId, params T[] instances)
public void PerformRefresh<T>(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, Func<T, Guid> getGuidId, params T[] instances)
{
GuidIdsRefreshed.AddRange(instances.Select(getGuidId));
}
public void PerformRemove(ICacheRefresher refresher, string jsonPayload)
public void PerformRemove(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, string jsonPayload)
{
PayloadsRemoved.Add(jsonPayload);
}
public void PerformRemove<T>(ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances)
public void PerformRemove<T>(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances)
{
IntIdsRemoved.AddRange(instances.Select(getNumericId));
}
public void PerformRemove(ICacheRefresher refresher, params int[] numericIds)
public void PerformRemove(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, params int[] numericIds)
{
IntIdsRemoved.AddRange(numericIds);
}
public void PerformRefresh(ICacheRefresher refresher, params int[] numericIds)
public void PerformRefresh(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, params int[] numericIds)
{
IntIdsRefreshed.AddRange(numericIds);
}
public void PerformRefresh(ICacheRefresher refresher, params Guid[] guidIds)
public void PerformRefresh(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, params Guid[] guidIds)
{
GuidIdsRefreshed.AddRange(guidIds);
}
public void PerformRefreshAll(ICacheRefresher refresher)
public void PerformRefreshAll(IEnumerable<IServerAddress> servers, ICacheRefresher refresher)
{
CountOfFullRefreshes++;
}
@@ -182,19 +191,15 @@ namespace Umbraco.Tests.Cache.DistributedCache
internal class TestServerRegistrar : IServerRegistrar
{
public IEnumerable<IServerAddress> Registrations => new List<IServerAddress>
public IEnumerable<IServerAddress> Registrations
{
new TestServerAddress("localhost")
};
public ServerRole GetCurrentServerRole()
{
throw new NotImplementedException();
}
public string GetCurrentServerUmbracoApplicationUrl()
{
throw new NotImplementedException();
get
{
return new List<IServerAddress>()
{
new TestServerAddress("localhost")
};
}
}
}
@@ -209,4 +214,4 @@ namespace Umbraco.Tests.Cache.DistributedCache
#endregion
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
@@ -8,32 +8,19 @@ using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Collections;
using Umbraco.Core.Models;
using Umbraco.Core.Scoping;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class FullDataSetCachePolicyTests
{
private IScopeAccessor DefaultAccessor
{
get
{
var accessor = new Mock<IScopeAccessor>();
var scope = new Mock<IScope>();
scope.Setup(x => x.RepositoryCacheMode).Returns(RepositoryCacheMode.Default);
accessor.Setup(x => x.AmbientScope).Returns(scope.Object);
return accessor.Object;
}
}
[Test]
public void Caches_Single()
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
new AuditItem(1, "blah", AuditType.Copy, 123),
new AuditItem(2, "blah2", AuditType.Copy, 123)
};
var isCached = false;
@@ -45,9 +32,9 @@ namespace Umbraco.Tests.Cache
isCached = true;
});
var policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, item => item.Id, false);
var unused = policy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), ids => getAll);
var found = policy.Get(1, id => new AuditItem(1, "blah", AuditType.Copy, 123), ids => getAll);
Assert.IsTrue(isCached);
}
@@ -56,14 +43,14 @@ namespace Umbraco.Tests.Cache
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
new AuditItem(1, "blah", AuditType.Copy, 123),
new AuditItem(2, "blah2", AuditType.Copy, 123)
};
var cache = new Mock<IRuntimeCacheProvider>();
cache.Setup(x => x.GetCacheItem(It.IsAny<string>())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah"));
cache.Setup(x => x.GetCacheItem(It.IsAny<string>())).Returns(new AuditItem(1, "blah", AuditType.Copy, 123));
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, item => item.Id, false);
var found = defaultPolicy.Get(1, id => null, ids => getAll);
Assert.IsNotNull(found);
@@ -75,7 +62,7 @@ namespace Umbraco.Tests.Cache
var getAll = new AuditItem[] {};
var cached = new List<string>();
IList list = null;
var cache = new Mock<IRuntimeCacheProvider>();
@@ -93,15 +80,15 @@ namespace Umbraco.Tests.Cache
return cached.Any() ? new DeepCloneableList<AuditItem>(ListCloneBehavior.CloneOnce) : null;
});
var policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, item => item.Id, false);
var found = policy.GetAll(new object[] {}, ids => getAll);
var found = policy.GetAll(new object[] { }, ids => getAll);
Assert.AreEqual(1, cached.Count);
Assert.IsNotNull(list);
//Do it again, ensure that its coming from the cache!
policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, item => item.Id, false);
found = policy.GetAll(new object[] { }, ids => getAll);
@@ -114,8 +101,8 @@ namespace Umbraco.Tests.Cache
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
new AuditItem(1, "blah", AuditType.Copy, 123),
new AuditItem(2, "blah2", AuditType.Copy, 123)
};
var cached = new List<string>();
@@ -132,7 +119,7 @@ namespace Umbraco.Tests.Cache
});
cache.Setup(x => x.GetCacheItem(It.IsAny<string>())).Returns(new AuditItem[] { });
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, item => item.Id, false);
var found = defaultPolicy.GetAll(new object[] { }, ids => getAll);
@@ -149,11 +136,11 @@ namespace Umbraco.Tests.Cache
cache.Setup(x => x.GetCacheItem(It.IsAny<string>())).Returns(() => new DeepCloneableList<AuditItem>(ListCloneBehavior.CloneOnce)
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
new AuditItem(1, "blah", AuditType.Copy, 123),
new AuditItem(2, "blah2", AuditType.Copy, 123)
});
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, item => item.Id, false);
var found = defaultPolicy.GetAll(new object[] { }, ids => getAll);
Assert.AreEqual(2, found.Length);
@@ -164,8 +151,8 @@ namespace Umbraco.Tests.Cache
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
new AuditItem(1, "blah", AuditType.Copy, 123),
new AuditItem(2, "blah2", AuditType.Copy, 123)
};
var cacheCleared = false;
@@ -176,10 +163,10 @@ namespace Umbraco.Tests.Cache
cacheCleared = true;
});
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, item => item.Id, false);
try
{
defaultPolicy.Update(new AuditItem(1, AuditType.Copy, 123, "test", "blah"), item => { throw new Exception("blah!"); });
defaultPolicy.Update(new AuditItem(1, "blah", AuditType.Copy, 123), item => { throw new Exception("blah!"); });
}
catch
{
@@ -196,8 +183,8 @@ namespace Umbraco.Tests.Cache
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
new AuditItem(1, "blah", AuditType.Copy, 123),
new AuditItem(2, "blah2", AuditType.Copy, 123)
};
var cacheCleared = false;
@@ -208,10 +195,10 @@ namespace Umbraco.Tests.Cache
cacheCleared = true;
});
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, item => item.Id, false);
try
{
defaultPolicy.Delete(new AuditItem(1, AuditType.Copy, 123, "test", "blah"), item => { throw new Exception("blah!"); });
defaultPolicy.Delete(new AuditItem(1, "blah", AuditType.Copy, 123), item => { throw new Exception("blah!"); });
}
catch
{
@@ -223,4 +210,4 @@ namespace Umbraco.Tests.Cache
}
}
}
}
}

View File

@@ -1,52 +1,52 @@
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class HttpRequestCacheProviderTests : CacheProviderTests
{
private HttpRequestCacheProvider _provider;
private FakeHttpContextFactory _ctx;
public override void Setup()
{
base.Setup();
_ctx = new FakeHttpContextFactory("http://localhost/test");
_provider = new HttpRequestCacheProvider(_ctx.HttpContext);
}
internal override ICacheProvider Provider
{
get { return _provider; }
}
protected override int GetTotalItemCount
{
get { return _ctx.HttpContext.Items.Count; }
}
}
[TestFixture]
public class StaticCacheProviderTests : CacheProviderTests
{
private StaticCacheProvider _provider;
public override void Setup()
{
base.Setup();
_provider = new StaticCacheProvider();
}
internal override ICacheProvider Provider
{
get { return _provider; }
}
protected override int GetTotalItemCount
{
get { return _provider.StaticCache.Count; }
}
}
}
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class HttpRequestCacheProviderTests : CacheProviderTests
{
private HttpRequestCacheProvider _provider;
private FakeHttpContextFactory _ctx;
public override void Setup()
{
base.Setup();
_ctx = new FakeHttpContextFactory("http://localhost/test");
_provider = new HttpRequestCacheProvider(_ctx.HttpContext);
}
internal override ICacheProvider Provider
{
get { return _provider; }
}
protected override int GetTotalItemCount
{
get { return _ctx.HttpContext.Items.Count; }
}
}
[TestFixture]
public class StaticCacheProviderTests : CacheProviderTests
{
private StaticCacheProvider _provider;
public override void Setup()
{
base.Setup();
_provider = new StaticCacheProvider();
}
internal override ICacheProvider Provider
{
get { return _provider; }
}
protected override int GetTotalItemCount
{
get { return _provider.StaticCache.Count; }
}
}
}

View File

@@ -1,59 +1,59 @@
using System;
using System.Diagnostics;
using System.Web;
using NUnit.Framework;
using Umbraco.Core.Cache;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class HttpRuntimeCacheProviderTests : RuntimeCacheProviderTests
{
private HttpRuntimeCacheProvider _provider;
protected override int GetTotalItemCount
{
get { return HttpRuntime.Cache.Count; }
}
public override void Setup()
{
base.Setup();
_provider = new HttpRuntimeCacheProvider(HttpRuntime.Cache);
}
internal override ICacheProvider Provider
{
get { return _provider; }
}
internal override IRuntimeCacheProvider RuntimeProvider
{
get { return _provider; }
}
[Test]
public void DoesNotCacheExceptions()
{
string value;
Assert.Throws<Exception>(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(1)); });
Assert.Throws<Exception>(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(2)); });
// does not throw
value = (string)_provider.GetCacheItem("key", () => GetValue(3));
Assert.AreEqual("succ3", value);
// cache
value = (string)_provider.GetCacheItem("key", () => GetValue(4));
Assert.AreEqual("succ3", value);
}
private static string GetValue(int i)
{
Debug.Print("get" + i);
if (i < 3)
throw new Exception("fail");
return "succ" + i;
}
}
}
using System;
using System.Diagnostics;
using System.Web;
using NUnit.Framework;
using Umbraco.Core.Cache;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class HttpRuntimeCacheProviderTests : RuntimeCacheProviderTests
{
private HttpRuntimeCacheProvider _provider;
protected override int GetTotalItemCount
{
get { return HttpRuntime.Cache.Count; }
}
public override void Setup()
{
base.Setup();
_provider = new HttpRuntimeCacheProvider(HttpRuntime.Cache);
}
internal override ICacheProvider Provider
{
get { return _provider; }
}
internal override IRuntimeCacheProvider RuntimeProvider
{
get { return _provider; }
}
[Test]
public void DoesNotCacheExceptions()
{
string value;
Assert.Throws<Exception>(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(1)); });
Assert.Throws<Exception>(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(2)); });
// does not throw
value = (string)_provider.GetCacheItem("key", () => GetValue(3));
Assert.AreEqual("succ3", value);
// cache
value = (string)_provider.GetCacheItem("key", () => GetValue(4));
Assert.AreEqual("succ3", value);
}
private static string GetValue(int i)
{
Debug.Print("get" + i);
if (i < 3)
throw new Exception("fail");
return "succ" + i;
}
}
}

View File

@@ -1,36 +1,36 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class ObjectCacheProviderTests : RuntimeCacheProviderTests
{
private ObjectCacheRuntimeCacheProvider _provider;
protected override int GetTotalItemCount
{
get { return _provider.MemoryCache.Count(); }
}
public override void Setup()
{
base.Setup();
_provider = new ObjectCacheRuntimeCacheProvider();
}
internal override ICacheProvider Provider
{
get { return _provider; }
}
internal override IRuntimeCacheProvider RuntimeProvider
{
get { return _provider; }
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class ObjectCacheProviderTests : RuntimeCacheProviderTests
{
private ObjectCacheRuntimeCacheProvider _provider;
protected override int GetTotalItemCount
{
get { return _provider.MemoryCache.Count(); }
}
public override void Setup()
{
base.Setup();
_provider = new ObjectCacheRuntimeCacheProvider();
}
internal override ICacheProvider Provider
{
get { return _provider; }
}
internal override IRuntimeCacheProvider RuntimeProvider
{
get { return _provider; }
}
}
}

View File

@@ -1,130 +1,188 @@
using System.Linq;
using System.Linq;
using System.Xml;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using umbraco.BusinessLogic;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.Testing;
using Umbraco.Tests.Testing.Objects.Accessors;
using Umbraco.Web;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
namespace Umbraco.Tests.Cache.PublishedCache
{
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)]
public class PublishContentCacheTests : BaseWebTest
{
private FakeHttpContextFactory _httpContextFactory;
private UmbracoContext _umbracoContext;
private IPublishedContentCache _cache;
private XmlDocument _xml;
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerFixture)]
[TestFixture]
public class PublishContentCacheTests : BaseWebTest
{
private FakeHttpContextFactory _httpContextFactory;
private UmbracoContext _umbracoContext;
private ContextualPublishedContentCache _cache;
private XmlDocument _xml;
private string GetXml()
{
return @"<?xml version=""1.0"" encoding=""utf-8""?><!DOCTYPE root[
private string GetLegacyXml()
{
return @"<?xml version=""1.0"" encoding=""utf-8""?><!DOCTYPE root[
<!ELEMENT node ANY> <!ATTLIST node id ID #REQUIRED> <!ELEMENT data ANY>
]>
<root id=""-1"">
<node id=""1046"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1046"" nodeTypeAlias=""Home"" ><content><![CDATA[]]></content>
<node id=""1173"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""1"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""sub1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173"" nodeTypeAlias=""Home""><content><![CDATA[]]></content>
<node id=""1174"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""1"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""sub2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1174"" nodeTypeAlias=""Home"" ><content><![CDATA[]]></content>
</node>
<node id=""1176"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""sub-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1176"" nodeTypeAlias=""Home"" ><content><![CDATA[]]></content>
</node>
</node>
<node id=""1175"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1175"" nodeTypeAlias=""Home"" ><content><![CDATA[]]></content>
</node>
</node>
<node id=""1172"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test"" writerName=""admin"" creatorName=""admin"" path=""-1,1172"" nodeTypeAlias=""Home"" />
</root>";
}
private string GetXml()
{
return @"<?xml version=""1.0"" encoding=""utf-8""?><!DOCTYPE root[
<!ELEMENT Home ANY>
<!ATTLIST Home id ID #REQUIRED>
]>
<root id=""-1"">
<Home id=""1046"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1046"" isDoc=""""><content><![CDATA[]]></content>
<Home id=""1173"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""1"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""sub1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173"" isDoc=""""><content><![CDATA[]]></content>
<Home id=""1174"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""1"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""sub2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1174"" isDoc=""""><content><![CDATA[]]></content>
</Home>
<Home id=""1176"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""sub-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1176"" isDoc=""""><content><![CDATA[]]></content>
</Home>
</Home>
<Home id=""1175"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1175"" isDoc=""""><content><![CDATA[]]></content>
</Home>
<Home id=""1177"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub'Apostrophe"" urlName=""sub'apostrophe"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1177"" isDoc=""""><content><![CDATA[]]></content>
</Home>
</Home>
<Home id=""1172"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test"" writerName=""admin"" creatorName=""admin"" path=""-1,1172"" isDoc="""" />
<Home id=""1046"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1046"" isDoc=""""><content><![CDATA[]]></content>
<Home id=""1173"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""1"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""sub1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173"" isDoc=""""><content><![CDATA[]]></content>
<Home id=""1174"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""1"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""sub2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1174"" isDoc=""""><content><![CDATA[]]></content>
</Home>
<Home id=""1176"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""sub-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1176"" isDoc=""""><content><![CDATA[]]></content>
</Home>
</Home>
<Home id=""1175"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1175"" isDoc=""""><content><![CDATA[]]></content>
</Home>
<Home id=""1177"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub'Apostrophe"" urlName=""sub'apostrophe"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1177"" isDoc=""""><content><![CDATA[]]></content>
</Home>
</Home>
<Home id=""1172"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test"" writerName=""admin"" creatorName=""admin"" path=""-1,1172"" isDoc="""" />
</root>";
}
}
public override void SetUp()
[SetUp]
public override void Initialize()
{
base.SetUp();
base.Initialize();
_httpContextFactory = new FakeHttpContextFactory("~/Home");
//ensure the StateHelper is using our custom context
StateHelper.HttpContext = _httpContextFactory.HttpContext;
var umbracoSettings = SettingsForTests.GenerateMockUmbracoSettings();
var globalSettings = SettingsForTests.GenerateMockGlobalSettings();
SettingsForTests.ConfigureSettings(umbracoSettings);
SettingsForTests.ConfigureSettings(globalSettings);
var settings = SettingsForTests.GenerateMockSettings();
var contentMock = Mock.Get(settings.Content);
contentMock.Setup(x => x.UseLegacyXmlSchema).Returns(false);
SettingsForTests.ConfigureSettings(settings);
_xml = new XmlDocument();
_xml.LoadXml(GetXml());
var xmlStore = new XmlStore(() => _xml, null, null, null);
var cacheProvider = new StaticCacheProvider();
var domainCache = new DomainCache(ServiceContext.DomainService, DefaultCultureAccessor);
var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedSnapshot(
new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, new SiteDomainHelper(), ContentTypesCache, null, null),
new PublishedMediaCache(xmlStore, ServiceContext.MediaService, ServiceContext.UserService, cacheProvider, ContentTypesCache),
new PublishedMemberCache(null, cacheProvider, Current.Services.MemberService, ContentTypesCache),
domainCache);
var publishedSnapshotService = new Mock<IPublishedSnapshotService>();
publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny<string>())).Returns(publishedShapshot);
var cache = new PublishedContentCache
{
GetXmlDelegate = (context, preview) => _xml
};
_umbracoContext = new UmbracoContext(
_umbracoContext = new UmbracoContext(
_httpContextFactory.HttpContext,
publishedSnapshotService.Object,
new WebSecurity(_httpContextFactory.HttpContext, Current.Services.UserService, globalSettings),
umbracoSettings,
Enumerable.Empty<IUrlProvider>(),
globalSettings,
new TestVariationContextAccessor());
ApplicationContext,
new PublishedCaches(cache, new PublishedMediaCache(ApplicationContext)),
new WebSecurity(_httpContextFactory.HttpContext, ApplicationContext));
_cache = _umbracoContext.ContentCache;
_cache = _umbracoContext.ContentCache;
}
[Test]
public void Has_Content()
{
Assert.IsTrue(_cache.HasContent());
}
private void SetupForLegacy()
{
var settings = SettingsForTests.GenerateMockSettings();
var contentMock = Mock.Get(settings.Content);
contentMock.Setup(x => x.UseLegacyXmlSchema).Returns(true);
SettingsForTests.ConfigureSettings(settings);
_xml = new XmlDocument();
_xml.LoadXml(GetLegacyXml());
}
protected override void FreezeResolution()
{
PublishedContentModelFactoryResolver.Current = new PublishedContentModelFactoryResolver();
base.FreezeResolution();
}
[Test]
public void Has_Content_LegacySchema()
{
SetupForLegacy();
Has_Content();
}
[Test]
public void Get_Root_Docs()
{
var result = _cache.GetAtRoot();
Assert.AreEqual(2, result.Count());
Assert.AreEqual(1046, result.ElementAt(0).Id);
Assert.AreEqual(1172, result.ElementAt(1).Id);
}
[Test]
public void Has_Content()
{
Assert.IsTrue(_cache.HasContent());
}
[Test]
public void Get_Root_Docs_LegacySchema()
{
SetupForLegacy();
Get_Root_Docs();
}
[TestCase("/", 1046)]
[TestCase("/home", 1046)]
[TestCase("/Home", 1046)] //test different cases
[TestCase("/home/sub1", 1173)]
[TestCase("/Home/sub1", 1173)]
[TestCase("/home/Sub1", 1173)] //test different cases
[TestCase("/home/Sub'Apostrophe", 1177)]
public void Get_Node_By_Route(string route, int nodeId)
{
var result = _cache.GetByRoute(route, false);
Assert.IsNotNull(result);
Assert.AreEqual(nodeId, result.Id);
}
[Test]
public void Get_Root_Docs()
{
var result = _cache.GetAtRoot();
Assert.AreEqual(2, result.Count());
Assert.AreEqual(1046, result.ElementAt(0).Id);
Assert.AreEqual(1172, result.ElementAt(1).Id);
}
[TestCase("/", 1046)]
[TestCase("/home", 1046)]
[TestCase("/Home", 1046)] //test different cases
[TestCase("/home/sub1", 1173)]
[TestCase("/Home/sub1", 1173)]
[TestCase("/home/Sub1", 1173)] //test different cases
public void Get_Node_By_Route_LegacySchema(string route, int nodeId)
{
SetupForLegacy();
Get_Node_By_Route(route, nodeId);
}
[TestCase("/", 1046)]
[TestCase("/home", 1046)]
[TestCase("/Home", 1046)] //test different cases
[TestCase("/home/sub1", 1173)]
[TestCase("/Home/sub1", 1173)]
[TestCase("/home/Sub1", 1173)] //test different cases
[TestCase("/home/Sub'Apostrophe", 1177)]
public void Get_Node_By_Route(string route, int nodeId)
{
var result = _cache.GetByRoute(route, false);
Assert.IsNotNull(result);
Assert.AreEqual(nodeId, result.Id);
}
[TestCase("/", 1046)]
[TestCase("/sub1", 1173)]
[TestCase("/Sub1", 1173)]
public void Get_Node_By_Route_Hiding_Top_Level_Nodes(string route, int nodeId)
{
var result = _cache.GetByRoute(route, true);
Assert.IsNotNull(result);
Assert.AreEqual(nodeId, result.Id);
}
}
}
[TestCase("/", 1046)]
[TestCase("/sub1", 1173)]
[TestCase("/Sub1", 1173)]
public void Get_Node_By_Route_Hiding_Top_Level_Nodes_LegacySchema(string route, int nodeId)
{
SetupForLegacy();
Get_Node_By_Route_Hiding_Top_Level_Nodes(route, nodeId);
}
[TestCase("/", 1046)]
[TestCase("/sub1", 1173)]
[TestCase("/Sub1", 1173)]
public void Get_Node_By_Route_Hiding_Top_Level_Nodes(string route, int nodeId)
{
var result = _cache.GetByRoute(route, true);
Assert.IsNotNull(result);
Assert.AreEqual(nodeId, result.Id);
}
}
}

View File

@@ -1,155 +1,111 @@
using System;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Examine;
using NUnit.Framework;
using umbraco.BusinessLogic;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Strings;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
using Umbraco.Tests.Testing;
using Current = Umbraco.Web.Composing.Current;
using LightInject;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Tests.PublishedContent;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
namespace Umbraco.Tests.Cache.PublishedCache
{
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)]
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture]
public class PublishMediaCacheTests : BaseWebTest
{
private Dictionary<string, PublishedContentType> _mediaTypes;
protected override void Compose()
{
protected override void FreezeResolution()
{
base.Compose();
Container.GetInstance<UrlSegmentProviderCollectionBuilder>()
.Clear()
.Append<DefaultUrlSegmentProvider>();
}
protected override void Initialize()
{
base.Initialize();
var type = new AutoPublishedContentType(22, "myType", new PublishedPropertyType[] { });
var image = new AutoPublishedContentType(23, "Image", new PublishedPropertyType[] { });
var testMediaType = new AutoPublishedContentType(24, "TestMediaType", new PublishedPropertyType[] { });
_mediaTypes = new Dictionary<string, PublishedContentType>
{
{ type.Alias, type },
{ image.Alias, image },
{ testMediaType.Alias, testMediaType }
};
ContentTypesCache.GetPublishedContentTypeByAlias = alias => _mediaTypes[alias];
}
private IMediaType MakeNewMediaType(IUser user, string text, int parentId = -1)
{
var mt = new MediaType(parentId) { Name = text, Alias = text, Thumbnail = "icon-folder", Icon = "icon-folder" };
ServiceContext.MediaTypeService.Save(mt);
return mt;
}
private IMedia MakeNewMedia(string name, IMediaType mediaType, IUser user, int parentId)
{
var m = ServiceContext.MediaService.CreateMediaWithIdentity(name, parentId, mediaType.Alias);
return m;
}
//NOTE: This is "Without_Examine" too
[Test]
public void Get_Root_Docs()
{
var user = ServiceContext.UserService.GetUserById(0);
var mType = MakeNewMediaType(user, "TestMediaType");
var mRoot1 = MakeNewMedia("MediaRoot1", mType, user, -1);
var mRoot2 = MakeNewMedia("MediaRoot2", mType, user, -1);
var mChild1 = MakeNewMedia("Child1", mType, user, mRoot1.Id);
var mChild2 = MakeNewMedia("Child2", mType, user, mRoot2.Id);
var ctx = GetUmbracoContext("/test");
var cache = new PublishedMediaCache(new XmlStore((XmlDocument) null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache);
var roots = cache.GetAtRoot();
Assert.AreEqual(2, roots.Count());
Assert.IsTrue(roots.Select(x => x.Id).ContainsAll(new[] {mRoot1.Id, mRoot2.Id}));
PublishedContentModelFactoryResolver.Current = new PublishedContentModelFactoryResolver();
base.FreezeResolution();
}
[Test]
public void Get_Item_Without_Examine()
{
var user = ServiceContext.UserService.GetUserById(0);
var mType = MakeNewMediaType(user, "TestMediaType");
_mediaTypes[mType.Alias] = new PublishedContentType(mType, null);
var mRoot = MakeNewMedia("MediaRoot", mType, user, -1);
var mChild1 = MakeNewMedia("Child1", mType, user, mRoot.Id);
public void Get_Root_Docs()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot1", mType, user, -1);
var mRoot2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot2", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot1.Id);
var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot2.Id);
//var publishedMedia = PublishedMediaTests.GetNode(mRoot.Id, GetUmbracoContext("/test", 1234));
var umbracoContext = GetUmbracoContext("/test");
var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new StaticCacheProvider(), ContentTypesCache);
var publishedMedia = cache.GetById(mRoot.Id);
Assert.IsNotNull(publishedMedia);
var ctx = GetUmbracoContext("/test", 1234);
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application), ctx);
var roots = cache.GetAtRoot();
Assert.AreEqual(2, roots.Count());
Assert.IsTrue(roots.Select(x => x.Id).ContainsAll(new[] {mRoot1.Id, mRoot2.Id}));
Assert.AreEqual(mRoot.Id, publishedMedia.Id);
Assert.AreEqual(mRoot.CreateDate.ToString("dd/MM/yyyy HH:mm:ss"), publishedMedia.CreateDate.ToString("dd/MM/yyyy HH:mm:ss"));
Assert.AreEqual(mRoot.CreatorId, publishedMedia.CreatorId);
//Assert.AreEqual(mRoot.User.Name, publishedMedia.CreatorName);
Assert.AreEqual(mRoot.ContentType.Alias, publishedMedia.ContentType.Alias);
Assert.AreEqual(mRoot.ContentType.Id, publishedMedia.ContentType.Id);
Assert.AreEqual(mRoot.Level, publishedMedia.Level);
Assert.AreEqual(mRoot.Name, publishedMedia.Name);
Assert.AreEqual(mRoot.Path, publishedMedia.Path);
Assert.AreEqual(mRoot.SortOrder, publishedMedia.SortOrder);
Assert.IsNull(publishedMedia.Parent);
}
}
[TestCase("id")]
[TestCase("nodeId")]
[TestCase("__NodeId")]
public void DictionaryDocument_Id_Keys(string key)
{
var dicDoc = GetDictionaryDocument(idKey: key);
DoAssert(dicDoc);
}
[Test]
public void Get_Item_Without_Examine()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id);
var publishedMedia = PublishedMediaTests.GetNode(mRoot.Id, GetUmbracoContext("/test", 1234));
[TestCase("template")]
[TestCase("templateId")]
public void DictionaryDocument_Template_Keys(string key)
{
var dicDoc = GetDictionaryDocument(templateKey: key);
DoAssert(dicDoc);
}
Assert.AreEqual(mRoot.Id, publishedMedia.Id);
Assert.AreEqual(mRoot.CreateDateTime.ToString("dd/MM/yyyy HH:mm:ss"), publishedMedia.CreateDate.ToString("dd/MM/yyyy HH:mm:ss"));
Assert.AreEqual(mRoot.User.Id, publishedMedia.CreatorId);
Assert.AreEqual(mRoot.User.Name, publishedMedia.CreatorName);
Assert.AreEqual(mRoot.ContentType.Alias, publishedMedia.DocumentTypeAlias);
Assert.AreEqual(mRoot.ContentType.Id, publishedMedia.DocumentTypeId);
Assert.AreEqual(mRoot.Level, publishedMedia.Level);
Assert.AreEqual(mRoot.Text, publishedMedia.Name);
Assert.AreEqual(mRoot.Path, publishedMedia.Path);
Assert.AreEqual(mRoot.sortOrder, publishedMedia.SortOrder);
Assert.IsNull(publishedMedia.Parent);
}
[TestCase("nodeName")]
[TestCase("__nodeName")]
public void DictionaryDocument_NodeName_Keys(string key)
{
var dicDoc = GetDictionaryDocument(nodeNameKey: key);
DoAssert(dicDoc);
}
[TestCase("id")]
[TestCase("nodeId")]
[TestCase("__NodeId")]
public void DictionaryDocument_Id_Keys(string key)
{
var dicDoc = GetDictionaryDocument(idKey: key);
DoAssert(dicDoc);
}
[TestCase("nodeTypeAlias")]
[TestCase("__NodeTypeAlias")]
public void DictionaryDocument_NodeTypeAlias_Keys(string key)
{
var dicDoc = GetDictionaryDocument(nodeTypeAliasKey: key);
DoAssert(dicDoc);
}
[TestCase("template")]
[TestCase("templateId")]
public void DictionaryDocument_Template_Keys(string key)
{
var dicDoc = GetDictionaryDocument(templateKey: key);
DoAssert(dicDoc);
}
[TestCase("path")]
[TestCase("__Path")]
public void DictionaryDocument_Path_Keys(string key)
{
var dicDoc = GetDictionaryDocument(pathKey: key);
DoAssert(dicDoc);
}
[TestCase("nodeName")]
[TestCase("__nodeName")]
public void DictionaryDocument_NodeName_Keys(string key)
{
var dicDoc = GetDictionaryDocument(nodeNameKey: key);
DoAssert(dicDoc);
}
[TestCase("nodeTypeAlias")]
[TestCase("__NodeTypeAlias")]
public void DictionaryDocument_NodeTypeAlias_Keys(string key)
{
var dicDoc = GetDictionaryDocument(nodeTypeAliasKey: key);
DoAssert(dicDoc);
}
[TestCase("path")]
[TestCase("__Path")]
public void DictionaryDocument_Path_Keys(string key)
{
var dicDoc = GetDictionaryDocument(pathKey: key);
DoAssert(dicDoc);
}
[Test]
public void DictionaryDocument_Key()
@@ -159,82 +115,78 @@ namespace Umbraco.Tests.Cache.PublishedCache
DoAssert(dicDoc, keyVal: key);
}
[Test]
public void DictionaryDocument_Get_Children()
{
var child1 = GetDictionaryDocument(idVal: 222333);
var child2 = GetDictionaryDocument(idVal: 444555);
[Test]
public void DictionaryDocument_Get_Children()
{
var child1 = GetDictionaryDocument(idVal: 222333);
var child2 = GetDictionaryDocument(idVal: 444555);
var dicDoc = GetDictionaryDocument(children: new List<IPublishedContent>()
{
child1, child2
});
var dicDoc = GetDictionaryDocument(children: new List<IPublishedContent>()
{
child1, child2
});
Assert.AreEqual(2, dicDoc.Children.Count());
Assert.AreEqual(222333, dicDoc.Children.ElementAt(0).Id);
Assert.AreEqual(444555, dicDoc.Children.ElementAt(1).Id);
}
Assert.AreEqual(2, dicDoc.Children.Count());
Assert.AreEqual(222333, dicDoc.Children.ElementAt(0).Id);
Assert.AreEqual(444555, dicDoc.Children.ElementAt(1).Id);
}
[Test]
public void Convert_From_Search_Result()
{
var ctx = GetUmbracoContext("/test");
[TestCase(true)]
[TestCase(false)]
public void Convert_From_Search_Result(bool withKey)
{
var ctx = GetUmbracoContext("/test", 1234);
var key = Guid.NewGuid();
var result = new SearchResult()
{
Id = 1234,
Score = 1
};
result.Fields.Add("__IndexType", "media");
result.Fields.Add("__NodeId", "1234");
result.Fields.Add("__NodeTypeAlias", Constants.Conventions.MediaTypes.Image);
result.Fields.Add("__Path", "-1,1234");
result.Fields.Add("__nodeName", "Test");
result.Fields.Add("id", "1234");
if (withKey) result.Fields.Add("key", key.ToString());
result.Fields.Add("nodeName", "Test");
result.Fields.Add("nodeTypeAlias", Constants.Conventions.MediaTypes.Image);
result.Fields.Add("parentID", "-1");
result.Fields.Add("path", "-1,1234");
result.Fields.Add("updateDate", "2012-07-16T10:34:09");
result.Fields.Add("writerName", "Shannon");
var store = new PublishedMediaCache(ctx.Application);
var doc = store.CreateFromCacheValues(store.ConvertFromSearchResult(result));
DoAssert(doc, 1234, withKey ? key : default(Guid), 0, 0, "", "Image", 0, "Shannon", "", 0, 0, "-1,1234", default(DateTime), DateTime.Parse("2012-07-16T10:34:09"), 2);
Assert.AreEqual(null, doc.Parent);
}
[TestCase(true)]
[TestCase(false)]
public void Convert_From_XPath_Navigator(bool withKey)
{
var ctx = GetUmbracoContext("/test", 1234);
var key = Guid.NewGuid();
var fields = new Dictionary<string, string>
{
{"__IndexType", "media"},
{"__NodeId", "1234"},
{"__NodeTypeAlias", Constants.Conventions.MediaTypes.Image},
{"__Path", "-1,1234"},
{"__nodeName", "Test"},
{"id", "1234"},
{"key", key.ToString()},
{"urlName", "/media/test.jpg"},
{"nodeType", "0"},
{"sortOrder", "0"},
{"level", "2"},
{"nodeName", "Test"},
{"nodeTypeAlias", Constants.Conventions.MediaTypes.Image},
{"parentID", "-1"},
{"path", "-1,1234"},
{"updateDate", DateTime.Parse("2012-07-16T10:34:09").Ticks.ToString()},
{"createDate", DateTime.Parse("2012-07-17T10:34:09").Ticks.ToString()},
{"creatorID", "0"},
{"creatorName", "Shannon"}
};
var xmlDoc = GetMediaXml();
if (withKey) ((XmlElement)xmlDoc.DocumentElement.FirstChild).SetAttribute("key", key.ToString());
var navigator = xmlDoc.SelectSingleNode("/root/Image").CreateNavigator();
var cache = new PublishedMediaCache(ctx.Application);
var doc = cache.CreateFromCacheValues(cache.ConvertFromXPathNavigator(navigator, true));
var result = new SearchResult("1234", 1, 1, () => fields.ToDictionary(x => x.Key, x => new List<string> { x.Value }));
DoAssert(doc, 2000, withKey ? key : default(Guid), 0, 2, "image1", "Image", 2044, "Shannon", "Shannon2", 22, 33, "-1,2000", DateTime.Parse("2012-06-12T14:13:17"), DateTime.Parse("2012-07-20T18:50:43"), 1);
Assert.AreEqual(null, doc.Parent);
Assert.AreEqual(2, doc.Children.Count());
Assert.AreEqual(2001, doc.Children.ElementAt(0).Id);
Assert.AreEqual(2002, doc.Children.ElementAt(1).Id);
}
var store = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache);
var doc = store.CreateFromCacheValues(store.ConvertFromSearchResult(result));
DoAssert(doc, 1234, key, 0, 0, "/media/test.jpg", "Image", 23, "Shannon", "Shannon", 0, 0, "-1,1234", DateTime.Parse("2012-07-17T10:34:09"), DateTime.Parse("2012-07-16T10:34:09"), 2);
Assert.AreEqual(null, doc.Parent);
}
[Test]
public void Convert_From_XPath_Navigator()
{
var ctx = GetUmbracoContext("/test");
var key = Guid.NewGuid();
var xmlDoc = GetMediaXml();
((XmlElement)xmlDoc.DocumentElement.FirstChild).SetAttribute("key", key.ToString());
var navigator = xmlDoc.SelectSingleNode("/root/Image").CreateNavigator();
var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache);
var doc = cache.CreateFromCacheValues(cache.ConvertFromXPathNavigator(navigator, true));
DoAssert(doc, 2000, key, 0, 2, "image1", "Image", 23, "Shannon", "Shannon", 33, 33, "-1,2000", DateTime.Parse("2012-06-12T14:13:17"), DateTime.Parse("2012-07-20T18:50:43"), 1);
Assert.AreEqual(null, doc.Parent);
Assert.AreEqual(2, doc.Children.Count());
Assert.AreEqual(2001, doc.Children.ElementAt(0).Id);
Assert.AreEqual(2002, doc.Children.ElementAt(1).Id);
}
private XmlDocument GetMediaXml()
{
var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
private XmlDocument GetMediaXml()
{
var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<!DOCTYPE root[
<!ELEMENT Home ANY>
<!ATTLIST Home id ID #REQUIRED>
@@ -242,171 +194,160 @@ namespace Umbraco.Tests.Cache.PublishedCache
<!ATTLIST CustomDocument id ID #REQUIRED>
]>
<root id=""-1"">
<Image id=""2000"" parentID=""-1"" level=""1"" writerID=""33"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon"" path=""-1,2000"" isDoc="""">
<file><![CDATA[/media/1234/image1.png]]></file>
<Image id=""2001"" parentID=""2000"" level=""2"" writerID=""33"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon"" path=""-1,2000,2001"" isDoc="""">
<file><![CDATA[/media/1234/image1.png]]></file>
</Image>
<Image id=""2002"" parentID=""2000"" level=""2"" writerID=""33"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon"" path=""-1,2000,2002"" isDoc="""">
<file><![CDATA[/media/1234/image1.png]]></file>
</Image>
</Image>
<Image id=""2000"" parentID=""-1"" level=""1"" writerID=""22"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon2"" path=""-1,2000"" isDoc="""">
<file><![CDATA[/media/1234/image1.png]]></file>
<Image id=""2001"" parentID=""2000"" level=""2"" writerID=""22"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon2"" path=""-1,2000,2001"" isDoc="""">
<file><![CDATA[/media/1234/image1.png]]></file>
</Image>
<Image id=""2002"" parentID=""2000"" level=""2"" writerID=""22"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon2"" path=""-1,2000,2002"" isDoc="""">
<file><![CDATA[/media/1234/image1.png]]></file>
</Image>
</Image>
</root>";
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
return xmlDoc;
}
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
return xmlDoc;
}
private Dictionary<string, string> GetDictionary(
int id,
private Dictionary<string, string> GetDictionary(
int id,
Guid key,
int parentId,
string idKey,
string templateKey,
string nodeNameKey,
string nodeTypeAliasKey,
string pathKey)
{
return new Dictionary<string, string>()
{
{idKey, id.ToString()},
int parentId,
string idKey,
string templateKey,
string nodeNameKey,
string nodeTypeAliasKey,
string pathKey)
{
return new Dictionary<string, string>()
{
{idKey, id.ToString()},
{"key", key.ToString()},
{templateKey, "0"},
{"sortOrder", "44"},
{nodeNameKey, "Testing"},
{"urlName", "testing"},
{nodeTypeAliasKey, "myType"},
{"nodeType", "22"},
{"writerName", "Shannon"},
{"creatorName", "Shannon"},
{"writerID", "33"},
{"creatorID", "33"},
{pathKey, "1,2,3,4,5"},
{"createDate", "2012-01-02"},
{"updateDate", "2012-01-02"},
{"level", "3"},
{"parentID", parentId.ToString()}
};
}
{templateKey, "333"},
{"sortOrder", "44"},
{nodeNameKey, "Testing"},
{"urlName", "testing"},
{nodeTypeAliasKey, "myType"},
{"nodeType", "22"},
{"writerName", "Shannon"},
{"creatorName", "Shannon2"},
{"writerID", "33"},
{"creatorID", "44"},
{pathKey, "1,2,3,4,5"},
{"createDate", "2012-01-02"},
{"updateDate", "2012-01-03"},
{"level", "3"},
{"parentID", parentId.ToString()}
};
}
private DictionaryPublishedContent GetDictionaryDocument(
string idKey = "id",
string templateKey = "template",
string nodeNameKey = "nodeName",
string nodeTypeAliasKey = "nodeTypeAlias",
string pathKey = "path",
int idVal = 1234,
private PublishedMediaCache.DictionaryPublishedContent GetDictionaryDocument(
string idKey = "id",
string templateKey = "template",
string nodeNameKey = "nodeName",
string nodeTypeAliasKey = "nodeTypeAlias",
string pathKey = "path",
int idVal = 1234,
Guid keyVal = default(Guid),
int parentIdVal = 321,
IEnumerable<IPublishedContent> children = null)
{
if (children == null)
children = new List<IPublishedContent>();
var dicDoc = new DictionaryPublishedContent(
//the dictionary
GetDictionary(idVal, keyVal, parentIdVal, idKey, templateKey, nodeNameKey, nodeTypeAliasKey, pathKey),
//callback to get the parent
d => new DictionaryPublishedContent(
// the dictionary
GetDictionary(parentIdVal, default(Guid), -1, idKey, templateKey, nodeNameKey, nodeTypeAliasKey, pathKey),
// callback to get the parent: there is no parent
a => null,
// callback to get the children: we're not going to test this so ignore
(dd, n) => new List<IPublishedContent>(),
// callback to get a property
(dd, a) => dd.Properties.FirstOrDefault(x => x.Alias.InvariantEquals(a)),
null, // cache provider
ContentTypesCache,
// no xpath
int parentIdVal = 321,
IEnumerable<IPublishedContent> children = null)
{
if (children == null)
children = new List<IPublishedContent>();
var dicDoc = new PublishedMediaCache.DictionaryPublishedContent(
//the dictionary
GetDictionary(idVal, keyVal, parentIdVal, idKey, templateKey, nodeNameKey, nodeTypeAliasKey, pathKey),
//callback to get the parent
d => new PublishedMediaCache.DictionaryPublishedContent(
GetDictionary(parentIdVal, default(Guid), -1, idKey, templateKey, nodeNameKey, nodeTypeAliasKey, pathKey),
//there is no parent
a => null,
//we're not going to test this so ignore
(dd, n) => new List<IPublishedContent>(),
(dd, a) => dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(a)),
null,
false),
//callback to get the children
(dd, n) => children,
(dd, a) => dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(a)),
null,
// not from examine
false),
//callback to get the children
(dd, n) => children,
// callback to get a property
(dd, a) => dd.Properties.FirstOrDefault(x => x.Alias.InvariantEquals(a)),
null, // cache provider
ContentTypesCache,
// no xpath
null,
// not from examine
false);
return dicDoc;
}
false);
return dicDoc;
}
private void DoAssert(
DictionaryPublishedContent dicDoc,
int idVal = 1234,
private void DoAssert(
PublishedMediaCache.DictionaryPublishedContent dicDoc,
int idVal = 1234,
Guid keyVal = default(Guid),
int templateIdVal = 0,
int sortOrderVal = 44,
string urlNameVal = "testing",
string nodeTypeAliasVal = "myType",
int nodeTypeIdVal = 22,
string writerNameVal = "Shannon",
string creatorNameVal = "Shannon",
int writerIdVal = 33,
int creatorIdVal = 33,
string pathVal = "1,2,3,4,5",
DateTime? createDateVal = null,
DateTime? updateDateVal = null,
int levelVal = 3,
int parentIdVal = 321)
{
if (!createDateVal.HasValue)
createDateVal = DateTime.Parse("2012-01-02");
if (!updateDateVal.HasValue)
updateDateVal = DateTime.Parse("2012-01-02");
int templateIdVal = 333,
int sortOrderVal = 44,
string urlNameVal = "testing",
string nodeTypeAliasVal = "myType",
int nodeTypeIdVal = 22,
string writerNameVal = "Shannon",
string creatorNameVal = "Shannon2",
int writerIdVal = 33,
int creatorIdVal = 44,
string pathVal = "1,2,3,4,5",
DateTime? createDateVal = null,
DateTime? updateDateVal = null,
int levelVal = 3,
int parentIdVal = 321)
{
if (!createDateVal.HasValue)
createDateVal = DateTime.Parse("2012-01-02");
if (!updateDateVal.HasValue)
updateDateVal = DateTime.Parse("2012-01-03");
DoAssert((IPublishedContent)dicDoc, idVal, keyVal, templateIdVal, sortOrderVal, urlNameVal, nodeTypeAliasVal, nodeTypeIdVal, writerNameVal,
creatorNameVal, writerIdVal, creatorIdVal, pathVal, createDateVal, updateDateVal, levelVal);
DoAssert((IPublishedContent)dicDoc, idVal, keyVal, templateIdVal, sortOrderVal, urlNameVal, nodeTypeAliasVal, nodeTypeIdVal, writerNameVal,
creatorNameVal, writerIdVal, creatorIdVal, pathVal, createDateVal, updateDateVal, levelVal);
//now validate the parentId that has been parsed, this doesn't exist on the IPublishedContent
Assert.AreEqual(parentIdVal, dicDoc.ParentId);
}
//now validate the parentId that has been parsed, this doesn't exist on the IPublishedContent
Assert.AreEqual(parentIdVal, dicDoc.ParentId);
}
private void DoAssert(
IPublishedContent doc,
int idVal = 1234,
private void DoAssert(
IPublishedContent doc,
int idVal = 1234,
Guid keyVal = default(Guid),
int templateIdVal = 0,
int sortOrderVal = 44,
string urlNameVal = "testing",
string nodeTypeAliasVal = "myType",
int nodeTypeIdVal = 22,
string writerNameVal = "Shannon",
string creatorNameVal = "Shannon",
int writerIdVal = 33,
int creatorIdVal = 33,
string pathVal = "1,2,3,4,5",
DateTime? createDateVal = null,
DateTime? updateDateVal = null,
int levelVal = 3)
{
if (!createDateVal.HasValue)
createDateVal = DateTime.Parse("2012-01-02");
if (!updateDateVal.HasValue)
updateDateVal = DateTime.Parse("2012-01-02");
int templateIdVal = 333,
int sortOrderVal = 44,
string urlNameVal = "testing",
string nodeTypeAliasVal = "myType",
int nodeTypeIdVal = 22,
string writerNameVal = "Shannon",
string creatorNameVal = "Shannon2",
int writerIdVal = 33,
int creatorIdVal = 44,
string pathVal = "1,2,3,4,5",
DateTime? createDateVal = null,
DateTime? updateDateVal = null,
int levelVal = 3)
{
if (!createDateVal.HasValue)
createDateVal = DateTime.Parse("2012-01-02");
if (!updateDateVal.HasValue)
updateDateVal = DateTime.Parse("2012-01-03");
Assert.AreEqual(idVal, doc.Id);
Assert.AreEqual(keyVal, doc.Key);
Assert.AreEqual(templateIdVal, doc.TemplateId);
Assert.AreEqual(sortOrderVal, doc.SortOrder);
Assert.AreEqual(urlNameVal, doc.UrlSegment);
Assert.AreEqual(nodeTypeAliasVal, doc.ContentType.Alias);
Assert.AreEqual(nodeTypeIdVal, doc.ContentType.Id);
Assert.AreEqual(writerNameVal, doc.WriterName);
Assert.AreEqual(creatorNameVal, doc.CreatorName);
Assert.AreEqual(writerIdVal, doc.WriterId);
Assert.AreEqual(creatorIdVal, doc.CreatorId);
Assert.AreEqual(pathVal, doc.Path);
Assert.AreEqual(createDateVal.Value, doc.CreateDate);
Assert.AreEqual(updateDateVal.Value, doc.UpdateDate);
Assert.AreEqual(levelVal, doc.Level);
Assert.AreEqual(idVal, doc.Id);
Assert.AreEqual(keyVal, doc.GetKey());
Assert.AreEqual(templateIdVal, doc.TemplateId);
Assert.AreEqual(sortOrderVal, doc.SortOrder);
Assert.AreEqual(urlNameVal, doc.UrlName);
Assert.AreEqual(nodeTypeAliasVal, doc.DocumentTypeAlias);
Assert.AreEqual(nodeTypeIdVal, doc.DocumentTypeId);
Assert.AreEqual(writerNameVal, doc.WriterName);
Assert.AreEqual(creatorNameVal, doc.CreatorName);
Assert.AreEqual(writerIdVal, doc.WriterId);
Assert.AreEqual(creatorIdVal, doc.CreatorId);
Assert.AreEqual(pathVal, doc.Path);
Assert.AreEqual(createDateVal.Value, doc.CreateDate);
Assert.AreEqual(updateDateVal.Value, doc.UpdateDate);
Assert.AreEqual(levelVal, doc.Level);
}
}
}
}
}
}

View File

@@ -1,64 +0,0 @@
using System;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Services.Changes;
using Umbraco.Web.Cache;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class RefreshersTests
{
[Test]
public void MediaCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new MediaCacheRefresher.JsonPayload(1234, TreeChangeTypes.None) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<MediaCacheRefresher.JsonPayload[]>(json);
Assert.AreEqual(source[0].Id, payload[0].Id);
Assert.AreEqual(source[0].ChangeTypes, payload[0].ChangeTypes);
}
[Test]
public void ContentCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new ContentCacheRefresher.JsonPayload(1234, TreeChangeTypes.None) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<ContentCacheRefresher.JsonPayload[]>(json);
Assert.AreEqual(source[0].Id, payload[0].Id);
Assert.AreEqual(source[0].ChangeTypes, payload[0].ChangeTypes);
}
[Test]
public void ContentTypeCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new ContentTypeCacheRefresher.JsonPayload("xxx", 1234, ContentTypeChangeTypes.None) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<ContentTypeCacheRefresher.JsonPayload[]>(json);
Assert.AreEqual(source[0].ItemType, payload[0].ItemType);
Assert.AreEqual(source[0].Id, payload[0].Id);
Assert.AreEqual(source[0].ChangeTypes, payload[0].ChangeTypes);
}
[Test]
public void DataTypeCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new DataTypeCacheRefresher.JsonPayload(1234, Guid.NewGuid(), true) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<DataTypeCacheRefresher.JsonPayload[]>(json);
Assert.AreEqual(source[0].Id, payload[0].Id);
Assert.AreEqual(source[0].Key, payload[0].Key);
Assert.AreEqual(source[0].Removed, payload[0].Removed);
}
[Test]
public void DomainCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new DomainCacheRefresher.JsonPayload(1234, DomainChangeTypes.None) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<DomainCacheRefresher.JsonPayload[]>(json);
Assert.AreEqual(source[0].Id, payload[0].Id);
Assert.AreEqual(source[0].ChangeType, payload[0].ChangeType);
}
}
}

View File

@@ -1,29 +1,30 @@
using System;
using System.Threading;
using NUnit.Framework;
using Umbraco.Core.Cache;
namespace Umbraco.Tests.Cache
{
public abstract class RuntimeCacheProviderTests : CacheProviderTests
{
internal abstract IRuntimeCacheProvider RuntimeProvider { get; }
[Test]
[Explicit("Testing for timeouts cannot work on VSTS.")]
public void Can_Add_And_Expire_Struct_Strongly_Typed_With_Null()
{
var now = DateTime.Now;
RuntimeProvider.InsertCacheItem("DateTimeTest", () => now, new TimeSpan(0, 0, 0, 0, 200));
Assert.AreEqual(now, Provider.GetCacheItem<DateTime>("DateTimeTest"));
Assert.AreEqual(now, Provider.GetCacheItem<DateTime?>("DateTimeTest"));
Thread.Sleep(300); //sleep longer than the cache expiration
Assert.AreEqual(default(DateTime), Provider.GetCacheItem<DateTime>("DateTimeTest"));
Assert.AreEqual(null, Provider.GetCacheItem<DateTime?>("DateTimeTest"));
}
}
}
using System;
using System.Threading;
using System.Web.Caching;
using NUnit.Framework;
using Umbraco.Core.Cache;
namespace Umbraco.Tests.Cache
{
public abstract class RuntimeCacheProviderTests : CacheProviderTests
{
internal abstract IRuntimeCacheProvider RuntimeProvider { get; }
[Test]
public void Can_Add_And_Expire_Struct_Strongly_Typed_With_Null()
{
var now = DateTime.Now;
RuntimeProvider.InsertCacheItem("DateTimeTest", () => now, new TimeSpan(0, 0, 0, 0, 200));
Assert.AreEqual(now, Provider.GetCacheItem<DateTime>("DateTimeTest"));
Assert.AreEqual(now, Provider.GetCacheItem<DateTime?>("DateTimeTest"));
Thread.Sleep(300); //sleep longer than the cache expiration
Assert.AreEqual(default(DateTime), Provider.GetCacheItem<DateTime>("DateTimeTest"));
Assert.AreEqual(null, Provider.GetCacheItem<DateTime?>("DateTimeTest"));
}
}
}

View File

@@ -1,29 +1,18 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Caching;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;
using Umbraco.Core.Scoping;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class SingleItemsOnlyCachePolicyTests
{
private IScopeAccessor DefaultAccessor
{
get
{
var accessor = new Mock<IScopeAccessor>();
var scope = new Mock<IScope>();
scope.Setup(x => x.RepositoryCacheMode).Returns(RepositoryCacheMode.Default);
accessor.Setup(x => x.AmbientScope).Returns(scope.Object);
return accessor.Object;
}
}
[Test]
public void Get_All_Doesnt_Cache()
{
@@ -37,13 +26,13 @@ namespace Umbraco.Tests.Cache
});
cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny<string>())).Returns(new AuditItem[] { });
var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
var unused = defaultPolicy.GetAll(new object[] { }, ids => new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
});
var found = defaultPolicy.GetAll(new object[] { }, ids => new[]
{
new AuditItem(1, "blah", AuditType.Copy, 123),
new AuditItem(2, "blah2", AuditType.Copy, 123)
});
Assert.AreEqual(0, cached.Count);
}
@@ -60,10 +49,10 @@ namespace Umbraco.Tests.Cache
isCached = true;
});
var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
var unused = defaultPolicy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), ids => null);
var found = defaultPolicy.Get(1, id => new AuditItem(1, "blah", AuditType.Copy, 123), ids => null);
Assert.IsTrue(isCached);
}
}
}
}

View File

@@ -1,967 +0,0 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Scoping;
using Umbraco.Web.PublishedCache.NuCache;
namespace Umbraco.Tests.Cache
{
[TestFixture]
public class SnapDictionaryTests
{
[Test]
public void LiveGenUpdate()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
Assert.AreEqual(0, d.Test.GetValues(1).Length);
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.Clear(1);
Assert.AreEqual(0, d.Test.GetValues(1).Length); // gone
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.AreEqual(0, d.Test.FloorGen);
}
[Test]
public void OtherGenUpdate()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
Assert.AreEqual(0, d.Test.GetValues(1).Length);
Assert.AreEqual(0, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s = d.CreateSnapshot();
Assert.AreEqual(1, s.Gen);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 2
d.Clear(1);
Assert.AreEqual(2, d.Test.GetValues(1).Length); // there
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.AreEqual(0, d.Test.FloorGen);
GC.KeepAlive(s);
}
[Test]
public void MissingReturnsNull()
{
var d = new SnapDictionary<int, string>();
var s = d.CreateSnapshot();
Assert.IsNull(s.Get(1));
}
[Test]
public void DeletedReturnsNull()
{
var d = new SnapDictionary<int, string>();
// gen 1
d.Set(1, "one");
var s1 = d.CreateSnapshot();
Assert.AreEqual("one", s1.Get(1));
// gen 2
d.Clear(1);
var s2 = d.CreateSnapshot();
Assert.IsNull(s2.Get(1));
Assert.AreEqual("one", s1.Get(1));
}
[Test]
public async Task CollectValues()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.Set(1, "uno");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s1 = d.CreateSnapshot();
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 2
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.Set(1, "one");
Assert.AreEqual(2, d.Test.GetValues(1).Length);
d.Set(1, "uno");
Assert.AreEqual(2, d.Test.GetValues(1).Length);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s2 = d.CreateSnapshot();
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 3
Assert.AreEqual(2, d.Test.GetValues(1).Length);
d.Set(1, "one");
Assert.AreEqual(3, d.Test.GetValues(1).Length);
d.Set(1, "uno");
Assert.AreEqual(3, d.Test.GetValues(1).Length);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var tv = d.Test.GetValues(1);
Assert.AreEqual(3, tv[0].Gen);
Assert.AreEqual(2, tv[1].Gen);
Assert.AreEqual(1, tv[2].Gen);
Assert.AreEqual(0, d.Test.FloorGen);
// nothing to collect
await d.CollectAsync();
GC.KeepAlive(s1);
GC.KeepAlive(s2);
Assert.AreEqual(0, d.Test.FloorGen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.AreEqual(2, d.SnapCount);
Assert.AreEqual(3, d.Test.GetValues(1).Length);
// one snapshot to collect
s1 = null;
GC.Collect();
GC.KeepAlive(s2);
await d.CollectAsync();
Assert.AreEqual(1, d.Test.FloorGen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.AreEqual(1, d.SnapCount);
Assert.AreEqual(2, d.Test.GetValues(1).Length);
// another snapshot to collect
s2 = null;
GC.Collect();
await d.CollectAsync();
Assert.AreEqual(2, d.Test.FloorGen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.AreEqual(0, d.SnapCount);
Assert.AreEqual(1, d.Test.GetValues(1).Length);
}
[Test]
public async Task ProperlyCollects()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
for (var i = 0; i < 32; i++)
{
d.Set(i, i.ToString());
d.CreateSnapshot().Dispose();
}
Assert.AreEqual(32, d.GenCount);
Assert.AreEqual(0, d.SnapCount); // because we've disposed them
await d.CollectAsync();
Assert.AreEqual(32, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual(0, d.GenCount);
Assert.AreEqual(0, d.SnapCount);
Assert.AreEqual(32, d.Count);
for (var i = 0; i < 32; i++)
d.Set(i, null);
d.CreateSnapshot().Dispose();
// because we haven't collected yet, but disposed nevertheless
Assert.AreEqual(1, d.GenCount);
Assert.AreEqual(0, d.SnapCount);
Assert.AreEqual(32, d.Count);
// once we collect, they are all gone
// since noone is interested anymore
await d.CollectAsync();
Assert.AreEqual(0, d.GenCount);
Assert.AreEqual(0, d.SnapCount);
Assert.AreEqual(0, d.Count);
}
[Test]
public async Task CollectNulls()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.Set(1, "uno");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s1 = d.CreateSnapshot();
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 2
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.Set(1, "one");
Assert.AreEqual(2, d.Test.GetValues(1).Length);
d.Set(1, "uno");
Assert.AreEqual(2, d.Test.GetValues(1).Length);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s2 = d.CreateSnapshot();
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 3
Assert.AreEqual(2, d.Test.GetValues(1).Length);
d.Set(1, "one");
Assert.AreEqual(3, d.Test.GetValues(1).Length);
d.Set(1, "uno");
Assert.AreEqual(3, d.Test.GetValues(1).Length);
d.Clear(1);
Assert.AreEqual(3, d.Test.GetValues(1).Length);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var tv = d.Test.GetValues(1);
Assert.AreEqual(3, tv[0].Gen);
Assert.AreEqual(2, tv[1].Gen);
Assert.AreEqual(1, tv[2].Gen);
Assert.AreEqual(0, d.Test.FloorGen);
// nothing to collect
await d.CollectAsync();
GC.KeepAlive(s1);
GC.KeepAlive(s2);
Assert.AreEqual(0, d.Test.FloorGen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.AreEqual(2, d.SnapCount);
Assert.AreEqual(3, d.Test.GetValues(1).Length);
// one snapshot to collect
s1 = null;
GC.Collect();
GC.KeepAlive(s2);
await d.CollectAsync();
Assert.AreEqual(1, d.Test.FloorGen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.AreEqual(1, d.SnapCount);
Assert.AreEqual(2, d.Test.GetValues(1).Length);
// another snapshot to collect
s2 = null;
GC.Collect();
await d.CollectAsync();
Assert.AreEqual(2, d.Test.FloorGen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.AreEqual(0, d.SnapCount);
// and everything is gone?
// no, cannot collect the live gen because we'd need to lock
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.CreateSnapshot();
GC.Collect();
await d.CollectAsync();
// poof, gone
Assert.AreEqual(0, d.Test.GetValues(1).Length);
}
[Test]
public async Task EventuallyCollectNulls()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
Assert.AreEqual(0, d.Test.GetValues(1).Length);
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
await d.CollectAsync();
var tv = d.Test.GetValues(1);
Assert.AreEqual(1, tv.Length);
Assert.AreEqual(1, tv[0].Gen);
var s = d.CreateSnapshot();
Assert.AreEqual("one", s.Get(1));
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual(1, d.Count);
Assert.AreEqual(1, d.SnapCount);
Assert.AreEqual(1, d.GenCount);
// gen 2
d.Clear(1);
tv = d.Test.GetValues(1);
Assert.AreEqual(2, tv.Length);
Assert.AreEqual(2, tv[0].Gen);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.AreEqual(1, d.Count);
Assert.AreEqual(1, d.SnapCount);
Assert.AreEqual(1, d.GenCount);
// nothing to collect
await d.CollectAsync();
GC.KeepAlive(s);
Assert.AreEqual(2, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Count);
Assert.AreEqual(1, d.SnapCount);
Assert.AreEqual(1, d.GenCount);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
// collect snapshot
// don't collect liveGen+
s = null; // without being disposed
GC.Collect(); // should release the generation reference
await d.CollectAsync();
Assert.AreEqual(1, d.Test.GetValues(1).Length); // "one" value is gone
Assert.AreEqual(1, d.Count); // still have 1 item
Assert.AreEqual(0, d.SnapCount); // snapshot is gone
Assert.AreEqual(0, d.GenCount); // and generation has been dequeued
// liveGen/nextGen
s = d.CreateSnapshot();
s = null;
// collect liveGen
GC.Collect();
SnapDictionary<int, string>.GenerationObject genObj;
Assert.IsTrue(d.Test.GenerationObjects.TryPeek(out genObj));
genObj = null;
// in Release mode, it works, but in Debug mode, the weak reference is still alive
// and for some reason we need to do this to ensure it is collected
#if DEBUG
await d.CollectAsync();
GC.Collect();
#endif
Assert.IsTrue(d.Test.GenerationObjects.TryPeek(out genObj));
Assert.IsFalse(genObj.WeakReference.IsAlive); // snapshot is gone, along with its reference
await d.CollectAsync();
Assert.AreEqual(0, d.Test.GetValues(1).Length); // null value is gone
Assert.AreEqual(0, d.Count); // item is gone
Assert.AreEqual(0, d.Test.GenerationObjects.Count);
Assert.AreEqual(0, d.SnapCount); // snapshot is gone
Assert.AreEqual(0, d.GenCount); // and generation has been dequeued
}
[Test]
public async Task CollectDisposedSnapshots()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s1 = d.CreateSnapshot();
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 2
d.Set(1, "two");
Assert.AreEqual(2, d.Test.GetValues(1).Length);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s2 = d.CreateSnapshot();
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 3
d.Set(1, "three");
Assert.AreEqual(3, d.Test.GetValues(1).Length);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s3 = d.CreateSnapshot();
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual(3, d.SnapCount);
s1.Dispose();
await d.CollectAsync();
Assert.AreEqual(2, d.SnapCount);
Assert.AreEqual(2, d.Test.GetValues(1).Length);
s2.Dispose();
await d.CollectAsync();
Assert.AreEqual(1, d.SnapCount);
Assert.AreEqual(1, d.Test.GetValues(1).Length);
s3.Dispose();
await d.CollectAsync();
Assert.AreEqual(0, d.SnapCount);
Assert.AreEqual(1, d.Test.GetValues(1).Length);
}
[Test]
public async Task CollectGcSnapshots()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s1 = d.CreateSnapshot();
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 2
d.Set(1, "two");
Assert.AreEqual(2, d.Test.GetValues(1).Length);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s2 = d.CreateSnapshot();
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
// gen 3
d.Set(1, "three");
Assert.AreEqual(3, d.Test.GetValues(1).Length);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s3 = d.CreateSnapshot();
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual(3, d.SnapCount);
s1 = s2 = s3 = null;
await d.CollectAsync();
Assert.AreEqual(3, d.SnapCount);
Assert.AreEqual(3, d.Test.GetValues(1).Length);
GC.Collect();
await d.CollectAsync();
Assert.AreEqual(0, d.SnapCount);
Assert.AreEqual(1, d.Test.GetValues(1).Length);
}
[Test]
public async Task RandomTest1()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
d.Set(1, "one");
d.Set(2, "two");
var s1 = d.CreateSnapshot();
var v1 = s1.Get(1);
Assert.AreEqual("one", v1);
d.Set(1, "uno");
var s2 = d.CreateSnapshot();
var v2 = s2.Get(1);
Assert.AreEqual("uno", v2);
v1 = s1.Get(1);
Assert.AreEqual("one", v1);
Assert.AreEqual(2, d.SnapCount);
s1 = null;
GC.Collect();
await d.CollectAsync();
// in Release mode, it works, but in Debug mode, the weak reference is still alive
// and for some reason we need to do this to ensure it is collected
#if DEBUG
GC.Collect();
await d.CollectAsync();
#endif
Assert.AreEqual(1, d.SnapCount);
v2 = s2.Get(1);
Assert.AreEqual("uno", v2);
s2 = null;
GC.Collect();
await d.CollectAsync();
Assert.AreEqual(0, d.SnapCount);
}
[Test]
public async Task RandomTest2()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
d.Set(1, "one");
d.Set(2, "two");
var s1 = d.CreateSnapshot();
var v1 = s1.Get(1);
Assert.AreEqual("one", v1);
d.Clear(1);
var s2 = d.CreateSnapshot();
var v2 = s2.Get(1);
Assert.AreEqual(null, v2);
v1 = s1.Get(1);
Assert.AreEqual("one", v1);
Assert.AreEqual(2, d.SnapCount);
s1 = null;
GC.Collect();
await d.CollectAsync();
// in Release mode, it works, but in Debug mode, the weak reference is still alive
// and for some reason we need to do this to ensure it is collected
#if DEBUG
GC.Collect();
await d.CollectAsync();
#endif
Assert.AreEqual(1, d.SnapCount);
v2 = s2.Get(1);
Assert.AreEqual(null, v2);
s2 = null;
GC.Collect();
await d.CollectAsync();
Assert.AreEqual(0, d.SnapCount);
}
[Test]
public void WriteLockingFirstSnapshot()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
using (d.GetWriter(GetScopeProvider()))
{
var s1 = d.CreateSnapshot();
Assert.AreEqual(0, s1.Gen);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
Assert.IsNull(s1.Get(1));
}
var s2 = d.CreateSnapshot();
Assert.AreEqual(1, s2.Gen);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual("one", s2.Get(1));
}
[Test]
public void WriteLocking()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s1 = d.CreateSnapshot();
Assert.AreEqual(1, s1.Gen);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual("one", s1.Get(1));
// gen 2
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.Set(1, "uno");
Assert.AreEqual(2, d.Test.GetValues(1).Length);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s2 = d.CreateSnapshot();
Assert.AreEqual(2, s2.Gen);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual("uno", s2.Get(1));
using (d.GetWriter(GetScopeProvider()))
{
// gen 3
Assert.AreEqual(2, d.Test.GetValues(1).Length);
d.Set(1, "ein");
Assert.AreEqual(3, d.Test.GetValues(1).Length);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s3 = d.CreateSnapshot();
Assert.AreEqual(2, s3.Gen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen); // has NOT changed when (non) creating snapshot
Assert.AreEqual("uno", s3.Get(1));
}
var s4 = d.CreateSnapshot();
Assert.AreEqual(3, s4.Gen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual("ein", s4.Get(1));
}
[Test]
public void NestedWriteLocking()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
var scopeProvider = GetScopeProvider();
using (d.GetWriter(scopeProvider))
{
using (d.GetWriter(scopeProvider))
{
d.Set(1, "one");
}
}
}
[Test]
public void WriteLocking2()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
Assert.AreEqual(1, d.Test.GetValues(1).Length);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s1 = d.CreateSnapshot();
Assert.AreEqual(1, s1.Gen);
Assert.AreEqual(1, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual("one", s1.Get(1));
// gen 2
Assert.AreEqual(1, d.Test.GetValues(1).Length);
d.Set(1, "uno");
Assert.AreEqual(2, d.Test.GetValues(1).Length);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s2 = d.CreateSnapshot();
Assert.AreEqual(2, s2.Gen);
Assert.AreEqual(2, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual("uno", s2.Get(1));
var scopeProvider = GetScopeProvider();
using (d.GetWriter(scopeProvider))
{
// gen 3
Assert.AreEqual(2, d.Test.GetValues(1).Length);
d.Set(1, "ein");
Assert.AreEqual(3, d.Test.GetValues(1).Length);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen);
var s3 = d.CreateSnapshot();
Assert.AreEqual(2, s3.Gen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsTrue(d.Test.NextGen); // has NOT changed when (non) creating snapshot
Assert.AreEqual("uno", s3.Get(1));
}
var s4 = d.CreateSnapshot();
Assert.AreEqual(3, s4.Gen);
Assert.AreEqual(3, d.Test.LiveGen);
Assert.IsFalse(d.Test.NextGen);
Assert.AreEqual("ein", s4.Get(1));
}
[Test]
public void WriteLocking3()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
var s1 = d.CreateSnapshot();
Assert.AreEqual(1, s1.Gen);
Assert.AreEqual("one", s1.Get(1));
d.Set(1, "uno");
var s2 = d.CreateSnapshot();
Assert.AreEqual(2, s2.Gen);
Assert.AreEqual("uno", s2.Get(1));
var scopeProvider = GetScopeProvider();
using (d.GetWriter(scopeProvider))
{
// creating a snapshot in a write-lock does NOT return the "current" content
// it uses the previous snapshot, so new snapshot created only on release
d.Set(1, "ein");
var s3 = d.CreateSnapshot();
Assert.AreEqual(2, s3.Gen);
Assert.AreEqual("uno", s3.Get(1));
// but live snapshot contains changes
var ls = d.Test.LiveSnapshot;
Assert.AreEqual("ein", ls.Get(1));
Assert.AreEqual(3, ls.Gen);
}
var s4 = d.CreateSnapshot();
Assert.AreEqual(3, s4.Gen);
Assert.AreEqual("ein", s4.Get(1));
}
[Test]
public void ScopeLocking1()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
var s1 = d.CreateSnapshot();
Assert.AreEqual(1, s1.Gen);
Assert.AreEqual("one", s1.Get(1));
d.Set(1, "uno");
var s2 = d.CreateSnapshot();
Assert.AreEqual(2, s2.Gen);
Assert.AreEqual("uno", s2.Get(1));
var scopeProvider = GetScopeProvider(true);
using (d.GetWriter(scopeProvider))
{
// creating a snapshot in a write-lock does NOT return the "current" content
// it uses the previous snapshot, so new snapshot created only on release
d.Set(1, "ein");
var s3 = d.CreateSnapshot();
Assert.AreEqual(2, s3.Gen);
Assert.AreEqual("uno", s3.Get(1));
// but live snapshot contains changes
var ls = d.Test.LiveSnapshot;
Assert.AreEqual("ein", ls.Get(1));
Assert.AreEqual(3, ls.Gen);
}
var s4 = d.CreateSnapshot();
Assert.AreEqual(2, s4.Gen);
Assert.AreEqual("uno", s4.Get(1));
((ScopeContext) scopeProvider.Context).ScopeExit(true);
var s5 = d.CreateSnapshot();
Assert.AreEqual(3, s5.Gen);
Assert.AreEqual("ein", s5.Get(1));
}
[Test]
public void ScopeLocking2()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
// gen 1
d.Set(1, "one");
var s1 = d.CreateSnapshot();
Assert.AreEqual(1, s1.Gen);
Assert.AreEqual("one", s1.Get(1));
d.Set(1, "uno");
var s2 = d.CreateSnapshot();
Assert.AreEqual(2, s2.Gen);
Assert.AreEqual("uno", s2.Get(1));
var scopeProviderMock = new Mock<IScopeProvider>();
var scopeContext = new ScopeContext();
scopeProviderMock.Setup(x => x.Context).Returns(scopeContext);
var scopeProvider = scopeProviderMock.Object;
using (d.GetWriter(scopeProvider))
{
// creating a snapshot in a write-lock does NOT return the "current" content
// it uses the previous snapshot, so new snapshot created only on release
d.Set(1, "ein");
var s3 = d.CreateSnapshot();
Assert.AreEqual(2, s3.Gen);
Assert.AreEqual("uno", s3.Get(1));
// but live snapshot contains changes
var ls = d.Test.LiveSnapshot;
Assert.AreEqual("ein", ls.Get(1));
Assert.AreEqual(3, ls.Gen);
}
var s4 = d.CreateSnapshot();
Assert.AreEqual(2, s4.Gen);
Assert.AreEqual("uno", s4.Get(1));
scopeContext.ScopeExit(false);
var s5 = d.CreateSnapshot();
Assert.AreEqual(2, s5.Gen);
Assert.AreEqual("uno", s5.Get(1));
}
[Test]
public void GetAll()
{
var d = new SnapDictionary<int, string>();
d.Test.CollectAuto = false;
Assert.AreEqual(0, d.Test.GetValues(1).Length);
d.Set(1, "one");
d.Set(2, "two");
d.Set(3, "three");
d.Set(4, "four");
var s1 = d.CreateSnapshot();
var all = s1.GetAll().ToArray();
Assert.AreEqual(4, all.Length);
Assert.AreEqual("one", all[0]);
Assert.AreEqual("four", all[3]);
d.Set(1, "uno");
var s2 = d.CreateSnapshot();
all = s1.GetAll().ToArray();
Assert.AreEqual(4, all.Length);
Assert.AreEqual("one", all[0]);
Assert.AreEqual("four", all[3]);
all = s2.GetAll().ToArray();
Assert.AreEqual(4, all.Length);
Assert.AreEqual("uno", all[0]);
Assert.AreEqual("four", all[3]);
}
private IScopeProvider GetScopeProvider(bool withContext = false)
{
var scopeProviderMock = new Mock<IScopeProvider>();
var scopeContext = withContext ? new ScopeContext() : null;
scopeProviderMock.Setup(x => x.Context).Returns(scopeContext);
var scopeProvider = scopeProviderMock.Object;
return scopeProvider;
}
}
}

View File

@@ -2,7 +2,7 @@
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.CoreThings
namespace Umbraco.Tests
{
[TestFixture]
public class CallContextTests
@@ -19,7 +19,7 @@ namespace Umbraco.Tests.CoreThings
}, o => {});
}
[OneTimeSetUp]
[TestFixtureSetUp]
public void SetUpFixture()
{
_first = true;
@@ -35,11 +35,11 @@ namespace Umbraco.Tests.CoreThings
SafeCallContext.Clear();
}
[TearDown]
public void TearDown()
{
SafeCallContext.Clear();
}
//[TearDown]
//public void TearDown()
//{
// SafeCallContext.Clear();
//}
[Test]
public void Test1()

View File

@@ -1,666 +0,0 @@
using System;
using System.Reflection;
using NUnit.Framework;
using Umbraco.Core;
using System.Linq;
using Newtonsoft.Json;
namespace Umbraco.Tests.Clr
{
[TestFixture]
public class ReflectionUtilitiesTests
{
[Test]
public void EmitCtorEmits()
{
var ctor1 = ReflectionUtilities.EmitConstuctor<Func<Class1>>();
Assert.IsInstanceOf<Class1>(ctor1());
var ctor2 = ReflectionUtilities.EmitConstuctor<Func<object>>(declaring: typeof(Class1));
Assert.IsInstanceOf<Class1>(ctor2());
var ctor3 = ReflectionUtilities.EmitConstuctor<Func<int, Class3>>();
Assert.IsInstanceOf<Class3>(ctor3(42));
var ctor4 = ReflectionUtilities.EmitConstuctor<Func<int, object>>(declaring: typeof(Class3));
Assert.IsInstanceOf<Class3>(ctor4(42));
}
[Test]
public void EmitCtorEmitsFromInfo()
{
var ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, Array.Empty<Type>(), null);
var ctor1 = ReflectionUtilities.EmitConstructor<Func<Class1>>(ctorInfo);
Assert.IsInstanceOf<Class1>(ctor1());
ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, new[] { typeof(int) }, null);
var ctor3 = ReflectionUtilities.EmitConstructor<Func<int, object>>(ctorInfo);
Assert.IsInstanceOf<Class1>(ctor3(42));
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitConstructor<Func<string, object>>(ctorInfo));
}
[Test]
public void EmitCtorEmitsPrivateCtor()
{
var ctor = ReflectionUtilities.EmitConstuctor<Func<string, Class3>>();
Assert.IsInstanceOf<Class3>(ctor("foo"));
}
[Test]
public void EmitCtorThrowsIfNotFound()
{
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitConstuctor<Func<bool, Class3>>());
}
[Test]
public void EmitCtorThrowsIfInvalid()
{
var ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, Array.Empty<Type>(), null);
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitConstructor<Func<Class2>>(ctorInfo));
}
[Test]
public void EmitCtorReturnsNull()
{
Assert.IsNull(ReflectionUtilities.EmitConstuctor<Func<bool, Class3>>(false));
}
[Test]
public void EmitMethodEmitsInstance()
{
var class1 = new Class1();
var method1 = ReflectionUtilities.EmitMethod<Action<Class1>>("Method1");
method1(class1);
var method2 = ReflectionUtilities.EmitMethod<Action<Class1, int>>("Method2");
method2(class1, 42);
var method3 = ReflectionUtilities.EmitMethod<Func<Class1, int>>("Method3");
Assert.AreEqual(42, method3(class1));
var method4 = ReflectionUtilities.EmitMethod<Func<Class1, string, int>>("Method4");
Assert.AreEqual(42, method4(class1, "42"));
}
[Test]
public void EmitMethodEmitsStatic()
{
var method1 = ReflectionUtilities.EmitMethod<Class1, Action>("SMethod1");
method1();
var method2 = ReflectionUtilities.EmitMethod<Class1, Action<int>>("SMethod2");
method2(42);
var method3 = ReflectionUtilities.EmitMethod<Class1, Func<int>>("SMethod3");
Assert.AreEqual(42, method3());
var method4 = ReflectionUtilities.EmitMethod<Class1, Func<string, int>>("SMethod4");
Assert.AreEqual(42, method4("42"));
}
[Test]
public void EmitMethodEmitsStaticStatic()
{
// static types cannot be used as type arguments
//var method = ReflectionUtilities.EmitMethod<StaticClass1, Action>("Method");
var method = ReflectionUtilities.EmitMethod<Action>(typeof (StaticClass1), "Method");
method();
}
[Test]
public void EmitMethodEmitsFromInfo()
{
var class1 = new Class1();
var methodInfo = typeof (Class1).GetMethod("Method1", BindingFlags.Instance | BindingFlags.Public);
var method1 = ReflectionUtilities.EmitMethod<Action<Class1>>(methodInfo);
method1(class1);
methodInfo = typeof(Class1).GetMethod("Method2", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(int) }, null);
var method2 = ReflectionUtilities.EmitMethod<Action<Class1, int>>(methodInfo);
method2(class1, 42);
methodInfo = typeof(Class1).GetMethod("Method3", BindingFlags.Instance | BindingFlags.Public);
var method3 = ReflectionUtilities.EmitMethod<Func<Class1, int>>(methodInfo);
Assert.AreEqual(42, method3(class1));
methodInfo = typeof(Class1).GetMethod("Method4", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(string) }, null);
var method4 = ReflectionUtilities.EmitMethod<Func<Class1, string, int>>(methodInfo);
Assert.AreEqual(42, method4(class1, "42"));
methodInfo = typeof(Class1).GetMethod("SMethod1", BindingFlags.Static | BindingFlags.Public);
var smethod1 = ReflectionUtilities.EmitMethod<Action>(methodInfo);
smethod1();
methodInfo = typeof(Class1).GetMethod("SMethod2", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(int) }, null);
var smethod2 = ReflectionUtilities.EmitMethod<Action<int>>(methodInfo);
smethod2(42);
methodInfo = typeof(Class1).GetMethod("SMethod3", BindingFlags.Static | BindingFlags.Public);
var smethod3 = ReflectionUtilities.EmitMethod<Func<int>>(methodInfo);
Assert.AreEqual(42, smethod3());
methodInfo = typeof(Class1).GetMethod("SMethod4", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string) }, null);
var smethod4 = ReflectionUtilities.EmitMethod<Func<string, int>>(methodInfo);
Assert.AreEqual(42, smethod4("42"));
methodInfo = typeof(StaticClass1).GetMethod("Method", BindingFlags.Static | BindingFlags.Public);
var method = ReflectionUtilities.EmitMethod<Action>(methodInfo);
method();
}
[Test]
public void EmitMethodEmitsPrivateMethod()
{
var class1 = new Class1();
var method1 = ReflectionUtilities.EmitMethod<Action<Class1>>("MethodP1");
method1(class1);
var method2 = ReflectionUtilities.EmitMethod<Class1, Action>("SMethodP1");
method2();
}
[Test]
public void EmitMethodThrowsIfNotFound()
{
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitMethod<Action<Class1>>("ZZZ"));
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitMethod<Action<Class1, int, int>>("Method1"));
}
[Test]
public void EmitMethodThrowsIfInvalid()
{
var methodInfo = typeof(Class1).GetMethod("Method1", BindingFlags.Instance | BindingFlags.Public);
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitMethod<Action<Class1, int, int>>(methodInfo));
}
[Test]
public void EmitMethodReturnsNull()
{
Assert.IsNull(ReflectionUtilities.EmitMethod<Action<Class1>>("ZZZ", false));
Assert.IsNull(ReflectionUtilities.EmitMethod<Action<Class1, int, int>>("Method1", false));
}
[Test]
public void EmitPropertyEmits()
{
var class1 = new Class1();
var getter1 = ReflectionUtilities.EmitPropertyGetter<Class1, int>("Value1");
Assert.AreEqual(42, getter1(class1));
var getter2 = ReflectionUtilities.EmitPropertyGetter<Class1, int>("Value3");
Assert.AreEqual(42, getter2(class1));
var setter1 = ReflectionUtilities.EmitPropertySetter<Class1, int>("Value2");
setter1(class1, 42);
var setter2 = ReflectionUtilities.EmitPropertySetter<Class1, int>("Value3");
setter2(class1, 42);
(var getter3, var setter3) = ReflectionUtilities.EmitPropertyGetterAndSetter<Class1, int>("Value3");
Assert.AreEqual(42, getter3(class1));
setter3(class1, 42);
// this is not supported yet
//var getter4 = ReflectionUtilities.EmitPropertyGetter<Class1, object>("Value1", returned: typeof(int));
//Assert.AreEqual(42, getter1(class1));
}
[Test]
public void EmitPropertyEmitsFromInfo()
{
var class1 = new Class1();
var propertyInfo = typeof (Class1).GetProperty("Value1");
var getter1 = ReflectionUtilities.EmitPropertyGetter<Class1, int>(propertyInfo);
Assert.AreEqual(42, getter1(class1));
propertyInfo = typeof(Class1).GetProperty("Value3");
var getter2 = ReflectionUtilities.EmitPropertyGetter<Class1, int>(propertyInfo);
Assert.AreEqual(42, getter2(class1));
propertyInfo = typeof(Class1).GetProperty("Value2");
var setter1 = ReflectionUtilities.EmitPropertySetter<Class1, int>(propertyInfo);
setter1(class1, 42);
propertyInfo = typeof(Class1).GetProperty("Value3");
var setter2 = ReflectionUtilities.EmitPropertySetter<Class1, int>(propertyInfo);
setter2(class1, 42);
(var getter3, var setter3) = ReflectionUtilities.EmitPropertyGetterAndSetter<Class1, int>(propertyInfo);
Assert.AreEqual(42, getter3(class1));
setter3(class1, 42);
}
[Test]
public void EmitPropertyEmitsPrivateProperty()
{
var class1 = new Class1();
var getter1 = ReflectionUtilities.EmitPropertyGetter<Class1, int>("ValueP1");
Assert.AreEqual(42, getter1(class1));
}
[Test]
public void EmitPropertyThrowsIfNotFound()
{
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitPropertyGetter<Class1, int>("Zalue1"));
Assert.Throws<InvalidOperationException>(() => ReflectionUtilities.EmitPropertyGetter<Class1, int>("Value2"));
var propertyInfo = typeof(Class1).GetProperty("Value1");
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitPropertySetter<Class1, int>(propertyInfo));
}
[Test]
public void EmitPropertyThrowsIfInvalid()
{
Assert.Throws<ArgumentException>(() => ReflectionUtilities.EmitPropertyGetter<Class1, string>("Value1"));
}
[Test]
public void EmitPropertyReturnsNull()
{
Assert.IsNull(ReflectionUtilities.EmitPropertyGetter<Class1, int>("Zalue1", false));
Assert.IsNull(ReflectionUtilities.EmitPropertyGetter<Class1, int>("Value2", false));
}
[Test]
public void PropertySetterCanCastUnsafeValue()
{
// test that we can emit property setters that cast from eg 'object'
var type4 = typeof(Class4);
var propInt4 = type4.GetProperty("IntValue");
var propString4 = type4.GetProperty("StringValue");
var propClassA4 = type4.GetProperty("ClassAValue");
var object4 = new Class4();
var object2A = new Class2A();
// works with a string property
Assert.IsNotNull(propString4);
var setterString4 = ReflectionUtilities.EmitPropertySetterUnsafe<Class4, object>(propString4);
Assert.IsNotNull(setterString4);
setterString4(object4, "foo");
Assert.IsNotNull(object4.StringValue);
Assert.AreEqual("foo", object4.StringValue);
// unsafe is... unsafe
Assert.Throws<InvalidCastException>(() => setterString4(object4, new Class2()));
// works with a reference property
Assert.IsNotNull(propClassA4);
var setterClassA4 = ReflectionUtilities.EmitPropertySetterUnsafe<Class4, object>(propClassA4);
Assert.IsNotNull(setterClassA4);
setterClassA4(object4, object2A);
Assert.IsNotNull(object4.ClassAValue);
Assert.AreEqual(object2A, object4.ClassAValue);
// works with a boxed value type
Assert.IsNotNull(propInt4);
var setterInt4 = ReflectionUtilities.EmitPropertySetterUnsafe<Class4, object>(propInt4);
Assert.IsNotNull(setterInt4);
setterInt4(object4, 42);
Assert.AreEqual(42, object4.IntValue);
// fixme the code below runs fine with ReSharper test running within VisualStudio
// but it crashes when running via vstest.console.exe - unless some settings are required?
// converting works
setterInt4(object4, 42.0);
Assert.AreEqual(42, object4.IntValue);
// unsafe is... unsafe
Assert.Throws<FormatException>(() => setterInt4(object4, "foo"));
}
[Test]
public void PropertySetterCanCastObject()
{
// Class5 inherits from Class4 and ClassValue is defined on Class4
var type5 = typeof(Class5);
var propClass4 = type5.GetProperty("ClassValue");
var object2 = new Class2();
// can cast the object type from Class5 to Class4
var setterClass4 = ReflectionUtilities.EmitPropertySetter<Class5, Class2>(propClass4);
var object4 = new Class5();
setterClass4(object4, object2);
Assert.IsNotNull(object4.ClassValue);
Assert.AreSame(object2, object4.ClassValue);
}
[Test]
public void PropertySetterCanCastUnsafeObject()
{
var type5 = typeof(Class5);
var propClass4 = type5.GetProperty("ClassValue");
var object2 = new Class2();
// can cast the object type from object to Class4
var setterClass4 = ReflectionUtilities.EmitPropertySetterUnsafe<object, Class2>(propClass4);
var object4 = new Class5();
setterClass4(object4, object2);
Assert.IsNotNull(object4.ClassValue);
Assert.AreSame(object2, object4.ClassValue);
}
[Test]
public void PropertyGetterCanCastValue()
{
var type4 = typeof(Class4);
var propClassA4 = type4.GetProperty("ClassAValue");
var propInt4 = type4.GetProperty("IntValue");
var object2A = new Class2A();
var object4 = new Class4 { ClassAValue = object2A, IntValue = 159 };
// can cast the return type from Class2A to Class2
var getterClassA4 = ReflectionUtilities.EmitPropertyGetter<Class4, Class2>(propClassA4);
var valueClass4A = getterClassA4(object4);
Assert.IsNotNull(valueClass4A);
Assert.AreSame(object2A, valueClass4A);
// cannot cast the return type from Class2A to Class3!
Assert.Throws<ArgumentException>(()
=> ReflectionUtilities.EmitPropertyGetter<Class4, Class3>(propClassA4));
// can cast and box the return type from int to object
var getterInt4 = ReflectionUtilities.EmitPropertyGetter<Class4, object>(propInt4);
var valueInt4 = getterInt4(object4);
Assert.IsTrue(valueInt4 is int);
Assert.AreEqual(159, valueInt4);
// cannot cast the return type from int to Class3!
Assert.Throws<ArgumentException>(()
=> ReflectionUtilities.EmitPropertyGetter<Class4, Class3>(propInt4));
}
[Test]
public void PropertyGetterCanCastObject()
{
var type5 = typeof(Class5);
var propClass4 = type5.GetProperty("ClassValue");
var object2 = new Class2();
var object4 = new Class5 { ClassValue = object2 };
// can cast the object type from Class5 to Class4
var getterClass4 = ReflectionUtilities.EmitPropertyGetter<Class5, Class2>(propClass4);
var valueClass4 = getterClass4(object4);
Assert.IsNotNull(valueClass4);
Assert.AreSame(object2, valueClass4);
// cannot cast the object type from Class3 to Class4!
Assert.Throws<ArgumentException>(()
=> ReflectionUtilities.EmitPropertyGetter<Class3, Class2>(propClass4));
}
[Test]
public void EmitPropertyCastGetterEmits()
{
// test that we can emit property getters that cast the returned value to 'object'
// test simple class
var type4 = typeof(Class4);
var object4 = new Class4
{
IntValue = 1,
StringValue = "foo",
ClassValue = new Class2(),
};
// works with a string property
var propString4 = type4.GetProperty("StringValue");
Assert.IsNotNull(propString4);
var getterString4 = ReflectionUtilities.EmitPropertyGetter<Class4, object>(propString4);
Assert.IsNotNull(getterString4);
var valueString4 = getterString4(object4);
Assert.IsNotNull(valueString4);
Assert.AreEqual("foo", valueString4);
// works with a reference property
var propClass4 = type4.GetProperty("ClassValue");
Assert.IsNotNull(propClass4);
var getterClass4 = ReflectionUtilities.EmitPropertyGetter<Class4, object>(propClass4);
Assert.IsNotNull(getterClass4);
var valueClass4 = getterClass4(object4);
Assert.IsNotNull(valueClass4);
Assert.IsInstanceOf<Class2>(valueClass4);
// works with a value type property
var propInt4 = type4.GetProperty("IntValue");
Assert.IsNotNull(propInt4);
// ... if explicitely getting a value type
var getterInt4T = ReflectionUtilities.EmitPropertyGetter<Class4, int>(propInt4);
Assert.IsNotNull(getterInt4T);
var valueInt4T = getterInt4T(object4);
Assert.AreEqual(1, valueInt4T);
// ... if using a compiled getter
var valueInt4D = GetIntValue(object4);
Assert.IsNotNull(valueInt4D);
Assert.IsTrue(valueInt4D is int);
Assert.AreEqual(1, valueInt4D);
// ... if getting a non-value type (emit adds a box)
var getterInt4 = ReflectionUtilities.EmitPropertyGetter<Class4, object>(propInt4);
Assert.IsNotNull(getterInt4);
var valueInt4 = getterInt4(object4);
Assert.IsNotNull(valueInt4);
Assert.IsTrue(valueInt4 is int);
Assert.AreEqual(1, valueInt4);
var getters4 = type4
.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)
.ToDictionary(x => x.Name, x => (object) ReflectionUtilities.EmitPropertyGetter<Class4, object>(x));
Console.WriteLine("Getting object4 values...");
var values4 = getters4.ToDictionary(kvp => kvp.Key, kvp => ((Func<Class4, object>) kvp.Value)(object4));
Console.WriteLine("Writing object4 values...");
foreach ((var name, var value) in values4)
Console.WriteLine($"{name}: {value}");
Assert.AreEqual(4, values4.Count);
Assert.AreEqual("foo", values4["StringValue"]);
Assert.IsInstanceOf<Class2>(values4["ClassValue"]);
Assert.AreEqual(1, values4["IntValue"]);
// test hierarchy
var type5 = typeof(Class5);
var getters5 = type5
.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)
.ToDictionary(x => x.Name, x => (object) ReflectionUtilities.EmitPropertyGetter<Class5, object>(x));
var object5 = new Class5
{
IntValue = 1,
IntValue2 = 1,
StringValue = "foo",
StringValue2 = "foo",
ClassValue = new Class2(),
ClassValue2 = new Class2()
};
Console.WriteLine("Getting object5 values...");
var values5 = getters5.ToDictionary(kvp => kvp.Key, kvp => ((Func<Class5, object>) kvp.Value)(object5));
Console.WriteLine("Writing object5 values...");
foreach ((var name, var value) in values5)
Console.WriteLine($"{name}: {value}");
Assert.AreEqual(7, values5.Count);
Assert.AreEqual("foo", values5["StringValue"]);
Assert.IsInstanceOf<Class2>(values5["ClassValue"]);
Assert.AreEqual(1, values5["IntValue"]);
Assert.AreEqual("foo", values5["StringValue2"]);
Assert.IsInstanceOf<Class2>(values5["ClassValue2"]);
Assert.AreEqual(1, values5["IntValue2"]);
// test object extensions
Console.WriteLine("Getting object5D values...");
var values5D = ObjectExtensions.ToObjectDictionary(object5);
Console.WriteLine("Writing object5D values...");
foreach ((var name, var value) in values5)
Console.WriteLine($"{name}: {value}");
Assert.AreEqual(7, values5.Count);
Assert.AreEqual("foo", values5D["StringValue"]);
Assert.IsInstanceOf<Class2>(values5D["ClassValue"]);
Assert.AreEqual(1, values5D["IntValue"]);
Assert.AreEqual("foo", values5D["StringValue2"]);
Assert.IsInstanceOf<Class2>(values5D["ClassValue2"]);
Assert.AreEqual(1, values5D["intValue2"]); // JsonProperty changes property name
}
[Test]
public void EmitFieldGetterSetterEmits()
{
var getter1 = ReflectionUtilities.EmitFieldGetter<Class1, int>("Field1");
var getter2 = ReflectionUtilities.EmitFieldGetter<Class1, int>("Field2");
var c = new Class1();
Assert.AreEqual(33, getter1(c));
Assert.AreEqual(66, getter2(c));
var setter2 = ReflectionUtilities.EmitFieldSetter<Class1, int>("Field2");
setter2(c, 99);
Assert.AreEqual(99, getter2(c));
// works on readonly fields!
var (getter3, setter3) = ReflectionUtilities.EmitFieldGetterAndSetter<Class1, int>("Field3");
Assert.AreEqual(22, getter3(c));
setter3(c, 44);
Assert.AreEqual(44, getter3(c));
}
// fixme - missing tests specifying 'returned' on method, property
#region IL Code
// these functions can be examined in eg DotPeek to understand IL works
// box [mscorlib]System.Int32
public object GetIntValue(Class4 object4) => object4.IntValue;
// unbox.any [mscorlib]System.Int32
public void SetIntValue(Class4 object4, object i) => object4.IntValue = (int) i;
// castclass [mscorlib]System.String
public void SetStringValue(Class4 object4, object s) => object4.StringValue = (string) s;
// conv.i4
public void SetIntValue(Class4 object4, double d) => object4.IntValue = (int) d;
// unbox.any [mscorlib]System.Double
// conv.i4
public void SetIntValue2(Class4 object4, object d) => object4.IntValue = (int) (double) d;
public void SetIntValue3(Class4 object4, object v)
{
if (v is int i)
object4.IntValue = i;
else
object4.IntValue = Convert.ToInt32(v);
}
public void SetIntValue4(Class4 object4, object v)
{
if (v is int i)
object4.IntValue = i;
else
object4.IntValue = (int) Convert.ChangeType(v, typeof(int));
}
// get field
public int GetIntField(Class1 object1) => object1.Field1;
// set field
public void SetIntField(Class1 object1, int i) => object1.Field1 = i;
#endregion
#region Test Objects
public static class StaticClass1
{
public static void Method() { }
}
public class Class1
{
public Class1() { }
public Class1(int i) { }
public void Method1() { }
public void Method2(int i) { }
public int Method3() => 42;
public int Method4(string s) => int.Parse(s);
public string Method5() => "foo";
public static void SMethod1() { }
public static void SMethod2(int i) { }
public static int SMethod3() => 42;
public static int SMethod4(string s) => int.Parse(s);
private void MethodP1() { }
private static void SMethodP1() { }
public int Value1 => 42;
public int Value2 { set { } }
public int Value3 { get { return 42; } set { } }
private int ValueP1 => 42;
public int Field1 = 33;
private int Field2 = 66;
public readonly int Field3 = 22;
}
public class Class2 { }
public class Class2A : Class2 { }
public class Class3
{
public Class3(int i) { }
private Class3(string s) { }
}
public class Class4
{
public int IntValue { get; set; }
public string StringValue { get; set; }
public Class2 ClassValue { get;set; }
public Class2A ClassAValue { get; set; }
}
public class Class5 : Class4
{
[JsonProperty("intValue2")]
public int IntValue2 { get; set; }
public string StringValue2 { get; set; }
public Class2 ClassValue2 { get;set; }
}
#endregion
}
}

View File

@@ -0,0 +1,23 @@
using System;
namespace Umbraco.Tests.CodeFirst.Attributes
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Interface, AllowMultiple = false, Inherited = true)]
public class AliasAttribute : Attribute
{
public AliasAttribute(string @alias)
{
Alias = alias;
}
/// <summary>
/// Gets or Sets the Alias of the Property
/// </summary>
public string Alias { get; private set; }
/// <summary>
/// Gets or Sets an optional name of the Property
/// </summary>
public string Name { get; set; }
}
}

View File

@@ -0,0 +1,52 @@
using System;
namespace Umbraco.Tests.CodeFirst.Attributes
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ContentTypeAttribute : Attribute
{
public ContentTypeAttribute(string @alias)
{
Alias = alias;
IconUrl = "folder.gif";
Thumbnail = "folder.png";
Description = "";
}
/// <summary>
/// Gets or sets the Alias of the ContentType
/// </summary>
public string Alias { get; private set; }
/// <summary>
/// Gets or sets the optional Name of the ContentType
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the optional Description of the ContentType
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets the optional IconUrl of the ContentType
/// </summary>
public string IconUrl { get; set; }
/// <summary>
/// Gets or sets the optional Thumbnail of the ContentType
/// </summary>
public string Thumbnail { get; set; }
/// <summary>
/// Gets or sets the optional array of Allowed Child ContentTypes of the ContentType
/// </summary>
public Type[] AllowedChildContentTypes { get; set; }
/// <summary>
/// Gets or sets the optional array of Allowed Template names of the ContentType
/// </summary>
public string[] AllowedTemplates { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
using System;
namespace Umbraco.Tests.CodeFirst.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DescriptionAttribute : Attribute
{
public DescriptionAttribute(string description)
{
Description = description;
}
/// <summary>
/// Gets or sets the Description of the Property
/// </summary>
public string Description { get; private set; }
}
}

View File

@@ -0,0 +1,18 @@
using System;
namespace Umbraco.Tests.CodeFirst.Attributes
{
[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)]
public class MixinAttribute : Attribute
{
public MixinAttribute(Type type)
{
Type = type;
}
/// <summary>
/// Gets or sets the Type of the implementing class
/// </summary>
public Type Type { get; private set; }
}
}

View File

@@ -0,0 +1,40 @@
using System;
using Umbraco.Core.Models;
using Umbraco.Tests.CodeFirst.Definitions;
using umbraco.editorControls.numberfield;
namespace Umbraco.Tests.CodeFirst.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class Numeric : PropertyTypeAttribute
{
public Numeric(string dataTypeName)
: base(typeof(IDataTypenteger))
{
DataTypeName = dataTypeName;
DatabaseType = DataTypeDatabaseType.Integer;
}
public string DataTypeName { get; set; }
public string PreValue { get; set; }
public override PropertyDefinition GetPropertyConvention()
{
var definition = new PropertyDefinition();
definition.Mandatory = Mandatory;
definition.ValidationRegExp = string.IsNullOrEmpty(ValidationRegExp) ? ValidationRegExp : string.Empty;
definition.PropertyGroup = string.IsNullOrEmpty(PropertyGroup) ? "Generic Properties" : PropertyGroup;
definition.DataTypeDefinition = Conventions.CreateDataTypeDefinitionFromAttribute(this, DataTypeName);
if(string.IsNullOrEmpty(PreValue) == false)
{
//TODO - test inserting a prevalue when a DataTypeDefinition has been created, as its currently throwing a foreignkey constraint error.
Conventions.CreatePrevalueForDataTypeDefinition(definition.DataTypeDefinition.Id, PreValue, 0, string.Empty);
}
return definition;
}
}
}

View File

@@ -0,0 +1,60 @@
using System;
using Umbraco.Core.Models;
using Umbraco.Tests.CodeFirst.Definitions;
namespace Umbraco.Tests.CodeFirst.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class PropertyTypeAttribute : PropertyTypeConventionAttribute
{
public PropertyTypeAttribute(Type type)
{
Type = type;
PropertyGroup = "Generic Properties";
Mandatory = false;
ValidationRegExp = string.Empty;
DatabaseType = DataTypeDatabaseType.Nvarchar;
}
/// <summary>
/// Gets or sets the Type of the DataType
/// </summary>
public Type Type { get; private set; }
/// <summary>
/// Gets or sets the Database Type to use for the chosen DataType.
/// </summary>
/// <remarks>
/// Please note that the DatabaseType only needs to be set when
/// creating a new DataType definition.
/// </remarks>
public DataTypeDatabaseType DatabaseType { get; set; }
/// <summary>
/// Gets or sets the Name of the PropertyGroup that this PropertyType belongs to
/// </summary>
public string PropertyGroup { get; set; }
/// <summary>
/// Boolean indicating that a value is required for this PropertyType
/// </summary>
public bool Mandatory { get; set; }
/// <summary>
/// Regular Expression for validating PropertyType's values
/// </summary>
public string ValidationRegExp { get; set; }
public override PropertyDefinition GetPropertyConvention()
{
var definition = new PropertyDefinition();
definition.Mandatory = Mandatory;
definition.ValidationRegExp = string.IsNullOrEmpty(ValidationRegExp) ? ValidationRegExp : string.Empty;
definition.PropertyGroup = string.IsNullOrEmpty(PropertyGroup) ? "Generic Properties" : PropertyGroup;
definition.DataTypeDefinition = Conventions.GetDataTypeDefinitionByAttributeOrType(this, Type);
return definition;
}
}
}

View File

@@ -0,0 +1,11 @@
using System;
using Umbraco.Tests.CodeFirst.Definitions;
namespace Umbraco.Tests.CodeFirst.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public abstract class PropertyTypeConventionAttribute : Attribute
{
public abstract PropertyDefinition GetPropertyConvention();
}
}

View File

@@ -0,0 +1,14 @@
using System;
using umbraco.editorControls.tinyMCE3;
namespace Umbraco.Tests.CodeFirst.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RichtextAttribute : PropertyTypeAttribute
{
public RichtextAttribute()
: base(typeof(tinyMCE3dataType))
{
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
namespace Umbraco.Tests.CodeFirst.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class SortOrderAttribute : Attribute
{
public SortOrderAttribute(int order)
{
Order = order;
}
/// <summary>
/// Gets or sets the sort order of the Property
/// </summary>
public int Order { get; private set; }
}
}

View File

@@ -0,0 +1,225 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Serialization;
using Umbraco.Tests.CodeFirst.Definitions;
using Umbraco.Tests.CodeFirst.TestModels;
using Umbraco.Tests.CodeFirst.TestModels.Composition;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
namespace Umbraco.Tests.CodeFirst
{
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture]
public class CodeFirstTests : BaseDatabaseFactoryTest
{
[SetUp]
public override void Initialize()
{
//LegacyUmbracoSettings.SettingsFilePath = IOHelper.MapPath(SystemDirectories.Config + Path.DirectorySeparatorChar, false);
base.Initialize();
var jsonNetSerializer = new JsonNetSerializer();
SerializationService = new SerializationService(jsonNetSerializer);
}
[Ignore("With the changes to the data type definition GUID -> Alias this no longer passes, will need Morten's help with this one")]
[Test]
public void Can_Create_Model_With_NonExisting_DataTypeDefinition()
{
ContentTypeDefinitionFactory.ClearContentTypeCache();
var modelType = typeof(ModelWithNewDataType);
var contentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(modelType);
var mappedContentTypes = ContentTypeDefinitionFactory.RetrieveMappedContentTypes();
ServiceContext.ContentTypeService.Save(mappedContentTypes);
var model = ServiceContext.ContentTypeService.GetContentType(NodeDto.NodeIdSeed + 1);
Assert.That(model, Is.Not.Null);
}
[Test]
public void Can_Resolve_ContentType_From_Decorated_Home_Model()
{
var modelType = typeof(Home);
var contentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(modelType);
Assert.That(contentType, Is.Not.Null);
Assert.That(contentType.Value.PropertyGroups, Is.Not.Null);
Assert.That(contentType.Value.PropertyTypes.Any(), Is.True);
Assert.That(contentType.Value.PropertyTypes.Count(), Is.EqualTo(2));
var result = SerializationService.ToStream(contentType.Value);
var json = result.ResultStream.ToJsonString();
Debug.Print(json);
}
[Test]
public void Can_Resolve_ContentType_From_Decorated_ContentPage_Model()
{
var modelType = typeof(ContentPage);
var contentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(modelType);
Assert.That(contentType, Is.Not.Null);
Assert.That(contentType.Value.PropertyGroups, Is.Not.Null);
Assert.That(contentType.Value.PropertyGroups.Any(), Is.True);
Assert.That(contentType.Value.PropertyGroups.Count(), Is.EqualTo(1));
Assert.That(contentType.Value.PropertyTypes.Any(), Is.True);
Assert.That(contentType.Value.PropertyTypes.Count(), Is.EqualTo(1));
}
[Test]
public void Can_Resolve_ContentType_From_PlainPocoType_Model()
{
var modelType = typeof(PlainPocoType);
var contentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(modelType);
Assert.That(contentType, Is.Not.Null);
Assert.That(contentType.Value.PropertyGroups, Is.Not.Null);
Assert.That(contentType.Value.PropertyTypes.Any(), Is.True);
Assert.That(contentType.Value.PropertyGroups.Count(), Is.EqualTo(1));
Assert.That(contentType.Value.PropertyTypes.Count(), Is.EqualTo(5));
var result = SerializationService.ToStream(contentType.Value);
var json = result.ResultStream.ToJsonString();
Debug.Print(json);
}
[Test]
public void Can_Retrieve_ContentTypes_After_Resolving()
{
ContentTypeDefinitionFactory.ClearContentTypeCache();
var modelType = typeof(Home);
var contentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(modelType);
var mappedContentTypes = ContentTypeDefinitionFactory.RetrieveMappedContentTypes();
Assert.That(mappedContentTypes, Is.Not.Null);
Assert.That(mappedContentTypes.Any(), Is.True);
Assert.That(mappedContentTypes.Count(), Is.EqualTo(2));
}
[Test]
public void Can_Resolve_Existing_ContentType_With_Decorated_Model()
{
var textPage = MockedContentTypes.CreateTextpageContentType();
ServiceContext.ContentTypeService.Save(textPage);
var modelType = typeof(TextPage);
var contentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(modelType);
Assert.That(contentType.Value.Id, Is.EqualTo(textPage.Id));
ServiceContext.ContentTypeService.Save(contentType.Value);
}
[Test]
public void Can_Save_Models_To_Database()
{
ContentTypeDefinitionFactory.ClearContentTypeCache();
var homeModel = typeof(Home);
var textPageModel = typeof(TextPage);
var homeContentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(homeModel);
var textPageContentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(textPageModel);
var mappedContentTypes = ContentTypeDefinitionFactory.RetrieveMappedContentTypes().ToList();
ServiceContext.ContentTypeService.Save(mappedContentTypes);
}
[Test]
public void Can_Resolve_Parent_Child_ContentTypes_And_Save_To_Database()
{
ContentTypeDefinitionFactory.ClearContentTypeCache();
var simplemodel = typeof(SimpleContentPage);
var model = typeof(AdvancedContentPage);
var sContentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(simplemodel);
var aContentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(model);
var mappedContentTypes = ContentTypeDefinitionFactory.RetrieveMappedContentTypes().ToList();
ServiceContext.ContentTypeService.Save(mappedContentTypes);
var type1 = ServiceContext.ContentTypeService.GetContentType(NodeDto.NodeIdSeed);
var type2 = ServiceContext.ContentTypeService.GetContentType(NodeDto.NodeIdSeed + 1);
Assert.That(type1, Is.Not.Null);
Assert.That(type2, Is.Not.Null);
}
[Test]
public void Can_Resolve_And_Save_Decorated_Model_To_Database()
{
ContentTypeDefinitionFactory.ClearContentTypeCache();
var model = typeof(DecoratedModelPage);
var modelContentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(model);
var mappedContentTypes = ContentTypeDefinitionFactory.RetrieveMappedContentTypes().ToList();
ServiceContext.ContentTypeService.Save(mappedContentTypes);
var type1 = ServiceContext.ContentTypeService.GetContentType(NodeDto.NodeIdSeed + 2);
Assert.That(type1, Is.Not.Null);
Assert.That(type1.PropertyGroups.Count(), Is.EqualTo(2));
Assert.That(type1.PropertyTypes.Count(), Is.EqualTo(4));
}
[Test]
public void Can_Resolve_ContentType_Composition_And_Save_To_Database()
{
ContentTypeDefinitionFactory.ClearContentTypeCache();
var metaSeoModel = typeof(MetaSeo);
var seoContentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(metaSeoModel);
var metaModel = typeof(Meta);
var metaContentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(metaModel);
var baseModel = typeof(Base);
var baseContentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(baseModel);
var newsModel = typeof(News);
var newsContentType = ContentTypeDefinitionFactory.GetContentTypeDefinition(newsModel);
var mappedContentTypes = ContentTypeDefinitionFactory.RetrieveMappedContentTypes().ToList();
ServiceContext.ContentTypeService.Save(mappedContentTypes);
Assert.That(mappedContentTypes.Count(), Is.EqualTo(4));
}
[Ignore("This now fails due to the new constraints on the db tables: A duplicate value cannot be inserted into a unique index. [ Table name = cmsPropertyTypeGroup,Constraint name = PK_cmsPropertyTypeGroup ]")]
[Test]
public void Can_Resolve_Full_List_Of_Models_Implementing_ContentTypeBase()
{
ContentTypeDefinitionFactory.ClearContentTypeCache();
var foundTypes = PluginManager.Current.ResolveContentTypeBaseTypes();
var contentTypeList = foundTypes.Select(ContentTypeDefinitionFactory.GetContentTypeDefinition).ToList();
var mappedContentTypes = ContentTypeDefinitionFactory.RetrieveMappedContentTypes();
Assert.That(contentTypeList.Count(), Is.EqualTo(mappedContentTypes.Count()));
ServiceContext.ContentTypeService.Save(mappedContentTypes);//Save to db
}
private SerializationService SerializationService { get; set; }
[TearDown]
public override void TearDown()
{
base.TearDown();
SerializationService = null;
}
}
}

View File

@@ -0,0 +1,171 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Models;
namespace Umbraco.Tests.CodeFirst
{
public abstract class ContentTypeBase
{
private IPublishedContent _content;
protected ContentTypeBase(){}
internal IPublishedContent Content
{
set { _content = value; }
}
#region Standard IPublisedContent properties
public IPublishedContent Parent
{
get { return _content.Parent; }
}
public int Id
{
get { return _content.Id; }
}
public int TemplateId
{
get { return _content.TemplateId; }
}
public int SortOrder
{
get { return _content.SortOrder; }
}
public string Name
{
get { return _content.Name; }
}
public string UrlName
{
get { return _content.UrlName; }
}
public string DocumentTypeAlias
{
get { return _content.DocumentTypeAlias; }
}
public int DocumentTypeId
{
get { return _content.DocumentTypeId; }
}
public string WriterName
{
get { return _content.WriterName; }
}
public string CreatorName
{
get { return _content.CreatorName; }
}
public int WriterId
{
get { return _content.WriterId; }
}
public int CreatorId
{
get { return _content.CreatorId; }
}
public string Path
{
get { return _content.Path; }
}
public DateTime CreateDate
{
get { return _content.CreateDate; }
}
public DateTime UpdateDate
{
get { return _content.UpdateDate; }
}
public Guid Version
{
get { return _content.Version; }
}
public int Level
{
get { return _content.Level; }
}
//Using this attribute to hide Properties from Intellisense (when compiled?)
[EditorBrowsable(EditorBrowsableState.Never)]
public ICollection<IPublishedProperty> Properties
{
get { return _content.Properties; }
}
//Using this attribute to hide Properties from Intellisense (when compiled?)
[EditorBrowsable(EditorBrowsableState.Never)]
public IEnumerable<IPublishedContent> Children
{
get { return _content.Children; }
}
//Using this attribute to hide Properties from Intellisense (when compiled?)
[EditorBrowsable(EditorBrowsableState.Never)]
public IPublishedProperty GetProperty(string alias)
{
return _content.GetProperty(alias);
}
#endregion
#region Strongly typed queries
public IEnumerable<T> ChildrenOfType<T>() where T : ContentTypeBase, new ()
{
var docTypeAlias = typeof (T).Name;
return _content.Children
.Where(x => x.DocumentTypeAlias == docTypeAlias)
.Select(ContentTypeMapper.Map<T>);
}
public IEnumerable<T> Descendants<T>() where T : ContentTypeBase, new ()
{
var docTypeAlias = typeof(T).Name;
return _content.Children.Map(x => true, (IPublishedContent n) => n.Children)
.Where(x => x.DocumentTypeAlias == docTypeAlias)
.Select(ContentTypeMapper.Map<T>);
}
#endregion
}
public static class ContentTypeBaseExtensions
{
public static IEnumerable<T> Children<T>(this ContentTypeBase contentTypeBase)
where T : ContentTypeBase, new()
{
var docTypeAlias = typeof(T).Name;
return contentTypeBase.Children
.Where(x => x.DocumentTypeAlias == docTypeAlias)
.Select(ContentTypeMapper.Map<T>);
}
public static IEnumerable<TSource> Map<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> selectorFunction,
Func<TSource, IEnumerable<TSource>> getChildrenFunction)
{
if (!source.Any())
{
return source;
}
// Add what we have to the stack
var flattenedList = source.Where(selectorFunction);
// Go through the input enumerable looking for children,
// and add those if we have them
foreach (TSource element in source)
{
var secondInner = getChildrenFunction(element);
if (secondInner.Any())
{
secondInner = secondInner.Map(selectorFunction, getChildrenFunction);
}
flattenedList = flattenedList.Concat(secondInner);
}
return flattenedList;
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Linq;
using Umbraco.Core.Models;
namespace Umbraco.Tests.CodeFirst
{
public static class ContentTypeMapper
{
public static T Map<T>(IPublishedContent content) where T : ContentTypeBase, new()
{
//TODO Verify passed in type T against DocumentType name/alias
//TODO Cache mapped properties?
T mapped = new T();
mapped.Content = content;
var propertyInfos = typeof(T).GetProperties();
foreach (var property in content.Properties)
{
var @alias = property.PropertyTypeAlias.ToLowerInvariant();
var propertyInfo = propertyInfos.FirstOrDefault(x => x.Name.ToLowerInvariant() == @alias);
if (propertyInfo == null) continue;
object value = null;
//TODO Proper mapping of types
if (propertyInfo.PropertyType == typeof(string))
value = property.Value;
else if (propertyInfo.PropertyType == typeof(DateTime))
value = DateTime.Parse(property.Value.ToString());
else if (propertyInfo.PropertyType == typeof(Boolean))
{
if (String.IsNullOrEmpty(property.Value.ToString()) || (string)property.Value == "0")
{
value = false;
}
else
{
value = true;
}
}
propertyInfo.SetValue(mapped, value, null);
}
return mapped;
}
}
}

View File

@@ -0,0 +1,385 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Tests.CodeFirst.Attributes;
namespace Umbraco.Tests.CodeFirst.Definitions
{
public static class ContentTypeDefinitionFactory
{
private static ConcurrentDictionary<string, DependencyField> _contentTypeCache = new ConcurrentDictionary<string, DependencyField>();
public static Lazy<IContentType> GetContentTypeDefinition(Type modelType)
{
//Check for BaseType different from ContentTypeBase
bool hasParent = modelType.BaseType != null && modelType.BaseType != typeof(ContentTypeBase) && modelType.BaseType != typeof(object);
var parent = new Lazy<IContentType>();
if(hasParent)
{
var isResolved = _contentTypeCache.ContainsKey(modelType.BaseType.FullName);
parent = isResolved
? _contentTypeCache[modelType.BaseType.FullName].ContentType
: GetContentTypeDefinition(modelType.BaseType);
}
var contentTypeAttribute = modelType.FirstAttribute<ContentTypeAttribute>();
var contentTypeAlias = contentTypeAttribute == null ? modelType.Name.ToUmbracoAlias() : contentTypeAttribute.Alias;
//Check if ContentType already exists by looking it up by Alias.
var existing = ApplicationContext.Current.Services.ContentTypeService.GetContentType(contentTypeAlias);
Lazy<IContentType> contentType = contentTypeAttribute == null
? PlainPocoConvention(modelType, existing)
: ContentTypeConvention(contentTypeAttribute, modelType, existing);
//Check for interfaces that'll be used for ContentTypeComposition
var mixins = GetAliasesFromTypeInterfaces(modelType);
var definitions = new List<PropertyDefinition>();
int order = 0;
var objProperties = modelType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();
foreach (var propertyInfo in objProperties)
{
var propertyTypeAttribute = propertyInfo.FirstAttribute<PropertyTypeConventionAttribute>();
var definition = propertyTypeAttribute == null
? new PropertyDefinition()
: propertyTypeAttribute.GetPropertyConvention();
//DataTypeDefinition fallback
if(definition.DataTypeDefinition == null)
{
definition.DataTypeDefinition = Conventions.GetDataTypeDefinitionByAttributeOrType(null, propertyInfo.PropertyType);
}
if(string.IsNullOrEmpty(definition.PropertyGroup))
{
definition.PropertyGroup = "Generic Properties";
}
//Alias fallback
if (string.IsNullOrEmpty(definition.Alias))
{
var aliasAttribute = propertyInfo.FirstAttribute<AliasAttribute>();
definition.Alias = Conventions.GetPropertyTypeAlias(aliasAttribute, propertyInfo.Name);
definition.Name = Conventions.GetPropertyTypeName(aliasAttribute, propertyInfo.Name);
}
//Description fallback
if (string.IsNullOrEmpty(definition.Description))
{
var descriptionAttribute = propertyInfo.FirstAttribute<DescriptionAttribute>();
definition.Description = descriptionAttribute != null
? descriptionAttribute.Description
: string.Empty;
}
//SortOrder fallback
if (definition.Order == default(int))
{
var sortOrderAttribute = propertyInfo.FirstAttribute<SortOrderAttribute>();
definition.Order = sortOrderAttribute != null ? sortOrderAttribute.Order : order;
}
definitions.Add(definition);
order++;
}
//Loop through definitions for PropertyGroups and create those that not already exists
var groupDefinitions = definitions.DistinctBy(d => d.PropertyGroup);
foreach (var groupDefinition in groupDefinitions)
{
var groupExists = contentType.Value.PropertyGroups.Contains(groupDefinition.PropertyGroup);
if(groupExists == false)
{
var propertyGroup = new PropertyGroup {Name = groupDefinition.PropertyGroup};
contentType.Value.PropertyGroups.Add(propertyGroup);
}
}
//Loop through definitions for PropertyTypes and add them to the correct PropertyGroup
foreach (var definition in definitions)
{
var group = contentType.Value.PropertyGroups.First(x => x.Name == definition.PropertyGroup);
//Check if a PropertyType with the same alias already exists, as we don't want to override existing ones
if(group.PropertyTypes.Contains(definition.Alias)) continue;
var propertyType = new PropertyType(definition.DataTypeDefinition, definition.Alias)
{
Mandatory = definition.Mandatory,
ValidationRegExp = definition.ValidationRegExp,
SortOrder = definition.Order,
Name = definition.Name
};
group.PropertyTypes.Add(propertyType);
}
//If current ContentType has a Parent the ParentId should be set and the ContentType added to the composition.
if(hasParent)
{
contentType.Value.SetLazyParentId(new Lazy<int>(() => parent.Value.Id));
contentType.Value.AddContentType(parent.Value);
}
//Add the resolved ContentType to the internal cache
var field = new DependencyField {ContentType = contentType, Alias = contentType.Value.Alias};
var dependencies = new List<string>();
//If current type has a parent (inherited model) we add the alias of that type as a dependency
if(hasParent)
{
dependencies.Add(parent.Value.Alias);
}
//Check ContentType for existing 'Allowed ContentTypes'
if(contentType.Value.AllowedContentTypes.Any())
{
dependencies.AddRange(contentType.Value.AllowedContentTypes.Select(allowed => allowed.Alias));
}
//Check for interfaces with AliasAttribute and add those as dependencies
//NOTE: might also be an idea to check if ContentType has already been created/added to cache that implements the interface.
if(mixins.Any())
{
foreach (var mixin in mixins)
{
if(dependencies.Contains(mixin.Item1)) continue;
dependencies.Add(mixin.Item1);
var isMixinResolved = _contentTypeCache.ContainsKey(mixin.Item2);
Lazy<IContentType> compositionType = null;
if (isMixinResolved)
{
compositionType = _contentTypeCache[mixin.Item2].ContentType;
}
else
{
GetContentTypeDefinition(mixin.Item3);
compositionType = _contentTypeCache[mixin.Item2].ContentType;
}
contentType.Value.AddContentType(compositionType.Value);
}
}
field.DependsOn = dependencies.ToArray();
_contentTypeCache.AddOrUpdate(modelType.FullName, field, (x, y) => field);
return contentType;
}
private static int[] GetTopologicalSortOrder(IList<DependencyField> fields)
{
var g = new TopologicalSorter(fields.Count());
var _indexes = new Dictionary<string, int>();
//add vertices
for (int i = 0; i < fields.Count(); i++)
{
_indexes[fields[i].Alias.ToLower()] = g.AddVertex(i);
}
//add edges
for (int i = 0; i < fields.Count; i++)
{
if (fields[i].DependsOn != null)
{
for (int j = 0; j < fields[i].DependsOn.Length; j++)
{
g.AddEdge(i,
_indexes[fields[i].DependsOn[j].ToLower()]);
}
}
}
int[] result = g.Sort();
return result;
}
//public static IEnumerable<Lazy<IContentType>> RetrieveMappedContentTypes()
public static IEnumerable<IContentType> RetrieveMappedContentTypes()
{
var fields = _contentTypeCache.Select(x => x.Value).ToList();
int[] sortOrder = GetTopologicalSortOrder(fields);
//var list = new List<Lazy<IContentType>>();
var list = new List<IContentType>();
for (int i = 0; i < sortOrder.Length; i++)
{
var field = fields[sortOrder[i]];
list.Add(field.ContentType.Value);
Debug.Print(field.Alias);
if (field.DependsOn != null)
foreach (var item in field.DependsOn)
{
Debug.Print(" -{0}", item);
}
}
list.Reverse();
return list;
}
public static void ClearContentTypeCache()
{
_contentTypeCache.Clear();
}
/// <summary>
/// Retrieves a list of aliases that correspond to the interfaces on the passed in type,
/// which are attributed with the AliasAttribute.
/// </summary>
/// <remarks>
/// The modelType is also used to ensure that the implementing class doesn't reference
/// itself via its interface.
/// </remarks>
/// <param name="modelType">Type of the model to retrieve interface aliases from</param>
/// <returns>An enumerable list of strings with aliases</returns>
private static IEnumerable<Tuple<string, string, Type>> GetAliasesFromTypeInterfaces(Type modelType)
{
var interfaces = modelType.GetInterfaces().ToList().Distinct();
var list = new List<Tuple<string, string, Type>>();
foreach (var interfaceType in interfaces)
{
var mixinAttribute = interfaceType.FirstAttribute<MixinAttribute>();
if (mixinAttribute != null)
{
if(mixinAttribute.Type == modelType) continue;
var contentTypeAttribute = mixinAttribute.Type.FirstAttribute<ContentTypeAttribute>();
var contentTypeAlias = contentTypeAttribute == null ? mixinAttribute.Type.Name.ToUmbracoAlias() : contentTypeAttribute.Alias;
var tuple = new Tuple<string, string, Type>(contentTypeAlias, mixinAttribute.Type.FullName, mixinAttribute.Type);
list.Add(tuple);
}
}
return list;
}
/// <summary>
/// Convention that converts a class decorated with the ContentTypeAttribute to an initial ContentType
/// </summary>
/// <param name="attribute"><see cref="ContentTypeAttribute"/> to use for mapping a <see cref="IContentType"/></param>
/// <param name="modelType">Type of the current class</param>
/// <param name="existing"> </param>
/// <returns>A Lazy <see cref="IContentType"/></returns>
private static Lazy<IContentType> ContentTypeConvention(ContentTypeAttribute attribute, Type modelType, IContentType existing)
{
var children = attribute.AllowedChildContentTypes == null
? new List<ContentTypeSort>()
: AllowedChildContentTypesConvention(
attribute.AllowedChildContentTypes, modelType);
var templates = attribute.AllowedTemplates == null
? new List<ITemplate>()
: AllowedTemplatesConvention(attribute.AllowedTemplates);
if(existing != null)
{
if (children.Any())
existing.AllowedContentTypes = children;
if (templates.Any())
existing.AllowedTemplates = templates;
return new Lazy<IContentType>(() => existing);
}
var contentType = new ContentType(-1)
{
Alias = attribute.Alias,
Description = attribute.Description,
Icon = attribute.IconUrl,
Thumbnail = attribute.Thumbnail,
Name = string.IsNullOrEmpty(attribute.Name)
? modelType.Name.SplitPascalCasing()
: attribute.Name,
AllowedContentTypes = children,
AllowedTemplates = templates
};
return new Lazy<IContentType>(() => contentType);
}
/// <summary>
/// Convention to resolve referenced templates
/// </summary>
/// <param name="templateNames"></param>
/// <returns></returns>
private static IEnumerable<ITemplate> AllowedTemplatesConvention(IEnumerable<string> templateNames)
{
var templates = new List<ITemplate>();
var engine = UmbracoConfig.For.UmbracoSettings().Templates.DefaultRenderingEngine;
foreach (var templateName in templateNames)
{
var @alias = engine == RenderingEngine.Mvc
? templateName.Replace(".cshtml", "").Replace(".vbhtml", "")
: templateName.Replace(".masterpage", "");
var template = ApplicationContext.Current.Services.FileService.GetTemplate(@alias);
if(template == null)
{
var name = engine == RenderingEngine.Mvc
? string.Concat(@alias, ".cshtml")
: string.Concat(@alias, ".masterpage");
template = new Template(string.Empty, name, @alias) { Content = string.Empty};
ApplicationContext.Current.Services.FileService.SaveTemplate(template);
}
templates.Add(template);
}
return templates;
}
/// <summary>
/// Convention to resolve referenced child content types
/// </summary>
/// <param name="types"></param>
/// <param name="currentType"> </param>
/// <returns></returns>
private static IEnumerable<ContentTypeSort> AllowedChildContentTypesConvention(IEnumerable<Type> types, Type currentType)
{
var contentTypeSorts = new List<ContentTypeSort>();
int order = 0;
foreach (var type in types)
{
if(type == currentType) continue;//If the referenced type is equal to the current type we skip it to avoid a circular dependency
var isResolved = _contentTypeCache.ContainsKey(type.FullName);
var lazy = isResolved ? _contentTypeCache[type.FullName].ContentType : GetContentTypeDefinition(type);
var contentTypeSort = new ContentTypeSort(new Lazy<int>(() => lazy.Value.Id), order, lazy.Value.Alias);
contentTypeSorts.Add(contentTypeSort);
order++;
}
return contentTypeSorts;
}
/// <summary>
/// Convention that converts a simple POCO to an initial ContentType
/// </summary>
/// <param name="modelType">Type of the object to map to a <see cref="IContentType"/></param>
/// <param name="existing"> </param>
/// <returns>A Lazy <see cref="IContentType"/></returns>
private static Lazy<IContentType> PlainPocoConvention(Type modelType, IContentType existing)
{
if(existing != null)
return new Lazy<IContentType>(() => existing);
var contentType = new ContentType(-1)
{
Alias = modelType.Name.ToUmbracoAlias(),
Description = string.Empty,
Icon = "folder.gif",
Thumbnail = "folder.png",
Name = modelType.Name.SplitPascalCasing(),
AllowedTemplates = new List<ITemplate>(),
AllowedContentTypes = new List<ContentTypeSort>()
};
return new Lazy<IContentType>(() => contentType);
}
}
}

View File

@@ -0,0 +1,143 @@
using System;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Services;
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.interfaces;
namespace Umbraco.Tests.CodeFirst.Definitions
{
public static class Conventions
{
/// <summary>
/// Convention to get a DataTypeDefinition from the PropertyTypeAttribute or the type of the property itself
/// </summary>
/// <param name="attribute"></param>
/// <param name="type"></param>
/// <returns></returns>
public static IDataTypeDefinition GetDataTypeDefinitionByAttributeOrType(PropertyTypeAttribute attribute, Type type)
{
if (attribute != null)
{
var instance = Activator.CreateInstance(attribute.Type);
var dataType = instance as IDataType;
var definition = GetDataTypeByControlId(dataType.Id);
//If the DataTypeDefinition doesn't exist we create a new one
if (definition == null)
{
definition = new DataTypeDefinition(-1, dataType.Id)
{
DatabaseType = attribute.DatabaseType,
Name = dataType.DataTypeName
};
ApplicationContext.Current.Services.DataTypeService.Save(definition, 0);
}
return definition;
}
return GetPredefinedDataTypeDefinitionByType(type);
}
/// <summary>
/// Convention to get predefined DataTypeDefinitions based on the Type of the property
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static IDataTypeDefinition GetPredefinedDataTypeDefinitionByType(Type type)
{
if (type == typeof(bool))
{
return GetDataTypeByControlId(new Guid(Constants.PropertyEditors.TrueFalse));// Yes/No DataType
}
if (type == typeof(int))
{
return GetDataTypeByControlId(new Guid(Constants.PropertyEditors.Integer));// Number DataType
}
if (type == typeof(DateTime))
{
return GetDataTypeByControlId(new Guid(Constants.PropertyEditors.Date));// Date Picker DataType
}
return GetDataTypeByControlId(new Guid(Constants.PropertyEditors.Textbox));// Standard textfield
}
/// <summary>
/// Gets the <see cref="IDataTypeDefinition"/> from the DataTypeService by its control Id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static IDataTypeDefinition GetDataTypeByControlId(Guid id)
{
var definitions = ApplicationContext.Current.Services.DataTypeService.GetDataTypeDefinitionByControlId(id);
return definitions.FirstOrDefault();
}
/// <summary>
/// Creates a new DataTypeDefinition based on the Type in the PropertyTypeAttribute
/// </summary>
/// <param name="attribute"></param>
/// <param name="dataTypeDefinitionName"></param>
/// <returns></returns>
public static IDataTypeDefinition CreateDataTypeDefinitionFromAttribute(PropertyTypeAttribute attribute, string dataTypeDefinitionName)
{
var instance = Activator.CreateInstance(attribute.Type);
var dataType = instance as IDataType;
var definition = new DataTypeDefinition(-1, dataType.Id)
{
DatabaseType = attribute.DatabaseType,
Name = dataTypeDefinitionName
};
ApplicationContext.Current.Services.DataTypeService.Save(definition, 0);
return definition;
}
/// <summary>
/// Creates a PreValue for a <see cref="IDataTypeDefinition"/>
/// </summary>
/// <param name="dataTypeDefinitionId"></param>
/// <param name="value"></param>
/// <param name="sortOrder"></param>
/// <param name="alias"></param>
public static void CreatePrevalueForDataTypeDefinition(int dataTypeDefinitionId, string value, int sortOrder, string alias)
{
var poco = new DataTypePreValueDto
{
Alias = alias,
DataTypeNodeId = dataTypeDefinitionId,
SortOrder = sortOrder,
Value = value
};
ApplicationContext.Current.DatabaseContext.Database.Insert(poco);
}
/// <summary>
/// Convention to get the Alias of the PropertyType from the AliasAttribute or the property itself
/// </summary>
/// <param name="attribute"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public static string GetPropertyTypeAlias(AliasAttribute attribute, string propertyName)
{
return attribute == null ? propertyName.ToUmbracoAlias() : attribute.Alias;
}
/// <summary>
/// Convention to get the Name of the PropertyType from the AliasAttribute or the property itself
/// </summary>
/// <param name="attribute"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public static string GetPropertyTypeName(AliasAttribute attribute, string propertyName)
{
if (attribute == null)
return propertyName.SplitPascalCasing();
return string.IsNullOrEmpty(attribute.Name) ? propertyName.SplitPascalCasing() : attribute.Name;
}
}
}

View File

@@ -0,0 +1,12 @@
using System;
using Umbraco.Core.Models;
namespace Umbraco.Tests.CodeFirst.Definitions
{
public class DependencyField
{
public string Alias { get; set; }
public string[] DependsOn { get; set; }
public Lazy<IContentType> ContentType { get; set; }
}
}

View File

@@ -0,0 +1,24 @@
using System;
using Umbraco.Core.Models;
namespace Umbraco.Tests.CodeFirst.Definitions
{
public class PropertyDefinition
{
public string Alias { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Order { get; set; }
public IDataTypeDefinition DataTypeDefinition { get; set; }
public string PropertyGroup { get; set; }
public bool Mandatory { get; set; }
public string ValidationRegExp { get; set; }
}
}

View File

@@ -0,0 +1,23 @@
using Umbraco.Web.Mvc;
namespace Umbraco.Tests.CodeFirst.Mvc
{
public abstract class UmbracoTemplatePage<T> : UmbracoTemplatePage where T : class
{
protected override void InitializePage()
{
base.InitializePage();
//set the model to the current node if it is not set, this is generally not the case
if (Model != null)
{
//Map CurrentContent here
}
}
/// <summary>
/// Returns the a strongly typed model
/// </summary>
public T CurrentContent { get; private set; }
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using Umbraco.Core;
namespace Umbraco.Tests.CodeFirst
{
/// <summary>
/// Used for TypeInheritanceTest and CodeFirstTests
/// </summary>
internal static class PluginManagerExtensions
{
public static IEnumerable<Type> ResolveContentTypeBaseTypes(this PluginManager resolver)
{
return resolver.ResolveTypes<ContentTypeBase>();
}
}
}

View File

@@ -0,0 +1,151 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Tests.CodeFirst.TestModels;
using Umbraco.Tests.PublishedContent;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
namespace Umbraco.Tests.CodeFirst
{
[DatabaseTestBehavior(DatabaseBehavior.NoDatabasePerFixture)]
[TestFixture]
public class StronglyTypedMapperTest : PublishedContentTestBase
{
[Test]
public void Type_Test()
{
var doc = GetNode(1);
var currentContent = ContentTypeMapper.Map<Home>(doc);
Assert.That(currentContent.SiteName, Is.EqualTo("Test site"));
Assert.That(currentContent.SiteDescription, Is.EqualTo("this is a test site"));
}
[Test]
public void Children_Of_Type_Test()
{
var doc = GetNode(1);
var currentContent = ContentTypeMapper.Map<Home>(doc);
var result = currentContent.ChildrenOfType<NewsLandingPage>().ToArray();
Assert.AreEqual("page2/alias, 2ndpagealias", result[0].PageTitle);
}
[Test]
public void Descendants_Of_Type_Test()
{
var doc = GetNode(1);
var currentContent = ContentTypeMapper.Map<Home>(doc);
var result = currentContent.Descendants<NewsArticle>().ToArray();
Assert.AreEqual("John doe", result[0].ArticleAuthor);
Assert.AreEqual("John Smith", result[1].ArticleAuthor);
}
[Test]
public void Can_Split_Pascal_Casing()
{
string name = "SiteName";
string result = Regex.Replace(name, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ");
Assert.That(result, Is.EqualTo("Site Name"));
string name2 = "MySiteDefinitionCase";
string result2 = Regex.Replace(name2, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ");
Assert.That(result2, Is.EqualTo("My Site Definition Case"));
}
#region Test setup
public override void Initialize()
{
// required so we can access property.Value
//PropertyValueConvertersResolver.Current = new PropertyValueConvertersResolver();
base.Initialize();
// need to specify a custom callback for unit tests
// AutoPublishedContentTypes generates properties automatically
// when they are requested, but we must declare those that we
// explicitely want to be here...
var propertyTypes = new[]
{
// AutoPublishedContentType will auto-generate other properties
new PublishedPropertyType("siteDescription", 0, "?"),
new PublishedPropertyType("siteName", 0, "?"),
new PublishedPropertyType("articleContent", 0, "?"),
new PublishedPropertyType("articleAuthor", 0, "?"),
new PublishedPropertyType("articleDate", 0, "?"),
new PublishedPropertyType("pageTitle", 0, "?"),
};
var type = new AutoPublishedContentType(0, "anything", propertyTypes);
PublishedContentType.GetPublishedContentTypeCallback = (alias) => type;
Debug.Print("INIT STRONG {0}",
PublishedContentType.Get(PublishedItemType.Content, "anything")
.PropertyTypes.Count());
}
public override void TearDown()
{
TestHelper.CleanUmbracoSettingsConfig();
base.TearDown();
}
protected override string GetXmlContent(int templateId)
{
return @"<?xml version=""1.0"" encoding=""utf-8""?>
<!DOCTYPE root[
<!ELEMENT Home ANY>
<!ATTLIST Home id ID #REQUIRED>
<!ELEMENT NewsArticle ANY>
<!ATTLIST NewsArticle id ID #REQUIRED>
<!ELEMENT NewsLandingPage ANY>
<!ATTLIST NewsLandingPage id ID #REQUIRED>
<!ELEMENT ContentPage ANY>
<!ATTLIST ContentPage id ID #REQUIRED>
]>
<root id=""-1"">
<Home id=""1"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""10"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1"" isDoc="""">
<siteName><![CDATA[Test site]]></siteName>
<siteDescription><![CDATA[this is a test site]]></siteDescription>
<bodyContent><![CDATA[This is some body content on the home page]]></bodyContent>
<NewsLandingPage id=""2"" parentID=""1"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""11"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""news"" urlName=""news"" writerName=""admin"" creatorName=""admin"" path=""-1,1,2"" isDoc="""">
<bodyContent><![CDATA[This is some body content on the news landing page]]></bodyContent>
<pageTitle><![CDATA[page2/alias, 2ndpagealias]]></pageTitle>
<NewsArticle id=""3"" parentID=""2"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""12"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Something happened"" urlName=""something-happened"" writerName=""admin"" creatorName=""admin"" path=""-1,1,2,3"" isDoc="""">
<articleContent><![CDATA[Some cool stuff happened today]]></articleContent>
<articleDate><![CDATA[2012-01-02 12:33:44]]></articleDate>
<articleAuthor><![CDATA[John doe]]></articleAuthor>
</NewsArticle>
<NewsArticle id=""4"" parentID=""2"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""12"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Then another thing"" urlName=""then-another-thing"" writerName=""admin"" creatorName=""admin"" path=""-1,1,2,4"" isDoc="""">
<articleContent><![CDATA[Today, other cool things occurred]]></articleContent>
<articleDate><![CDATA[2012-01-03 15:33:44]]></articleDate>
<articleAuthor><![CDATA[John Smith]]></articleAuthor>
</NewsArticle>
</NewsLandingPage>
<ContentPage id=""5"" parentID=""1"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""13"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""First Content Page"" urlName=""content-page-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1,5"" isDoc="""">
<bodyContent><![CDATA[This is some body content on the first content page]]></bodyContent>
</ContentPage>
<ContentPage id=""6"" parentID=""1"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""13"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""Second Content Page"" urlName=""content-page-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1,6"" isDoc="""">
<bodyContent><![CDATA[This is some body content on the second content page]]></bodyContent>
</ContentPage>
</Home>
</root>";
}
internal IPublishedContent GetNode(int id)
{
var ctx = UmbracoContext.Current;
var doc = ctx.ContentCache.GetById(id);
Assert.IsNotNull(doc);
return doc;
}
#endregion
}
}

View File

@@ -0,0 +1,14 @@
using System;
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.editorControls.textfield;
namespace Umbraco.Tests.CodeFirst.TestModels
{
public class AdvancedContentPage : SimpleContentPage
{
[PropertyType(typeof(TextFieldDataType), PropertyGroup = "Content")]
public string Author { get; set; }
public DateTime PublishDate { get; set; }
}
}

View File

@@ -0,0 +1,16 @@
using Umbraco.Tests.CodeFirst.Attributes;
namespace Umbraco.Tests.CodeFirst.TestModels.Composition
{
public class Base : ContentTypeBase, IBase
{
[Richtext(PropertyGroup = "Content")]
public string BodyContent { get; set; }
}
[Mixin(typeof(Base))]
public interface IBase
{
}
}

View File

@@ -0,0 +1,19 @@
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.editorControls.textfield;
using umbraco.editorControls.textfieldmultiple;
namespace Umbraco.Tests.CodeFirst.TestModels.Composition
{
public class Meta : ContentTypeBase, IMeta
{
[PropertyType(typeof(TextFieldDataType), PropertyGroup = "Content")]
public string MetaKeywords { get; set; }
[PropertyType(typeof(textfieldMultipleDataType))]
public string MetaDescription { get; set; }
}
[Mixin(typeof(Meta))]
public interface IMeta
{}
}

View File

@@ -0,0 +1,15 @@
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.editorControls.textfieldmultiple;
namespace Umbraco.Tests.CodeFirst.TestModels.Composition
{
public class MetaSeo : ContentTypeBase, IMetaSeo
{
[PropertyType(typeof(textfieldMultipleDataType))]
public string FriendlySeoStuff { get; set; }
}
[Mixin(typeof(MetaSeo))]
public interface IMetaSeo
{}
}

View File

@@ -0,0 +1,14 @@
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.editorControls.textfield;
namespace Umbraco.Tests.CodeFirst.TestModels.Composition
{
/// <summary>
/// Deriving class is parent, interfaces are compositions
/// </summary>
public class News : Base, IMetaSeo, IMeta
{
[PropertyType(typeof(TextFieldDataType), PropertyGroup = "Content")]
public string Author { get; set; }
}
}

View File

@@ -0,0 +1,10 @@
using Umbraco.Tests.CodeFirst.Attributes;
namespace Umbraco.Tests.CodeFirst.TestModels
{
public class ContentPage : ContentTypeBase
{
[Richtext(PropertyGroup = "Content")]
public string BodyContent { get; set; }
}
}

View File

@@ -0,0 +1,25 @@
using System;
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.editorControls.textfield;
namespace Umbraco.Tests.CodeFirst.TestModels
{
[ContentType("modelPage",
AllowedChildContentTypes = new[] { typeof(ContentPage) },
AllowedTemplates = new[]{"umbMaster"})]
public class DecoratedModelPage : ContentTypeBase
{
[PropertyType(typeof(TextFieldDataType), PropertyGroup = "Content")]
public string Author { get; set; }
[PropertyType(typeof(TextFieldDataType), PropertyGroup = "Content")]
public string Title { get; set; }
[Richtext(PropertyGroup = "Content")]
[Description("Richtext field to enter the main content of the page")]
public string BodyContent { get; set; }
[Alias("publishedDate", Name = "Publish Date")]
public DateTime PublishDate { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.editorControls.textfield;
using umbraco.editorControls.textfieldmultiple;
namespace Umbraco.Tests.CodeFirst.TestModels
{
[ContentType("home", AllowedChildContentTypes = new[] { typeof(ContentPage) })]
public class Home : ContentTypeBase
{
[PropertyType(typeof(TextFieldDataType))]
public string SiteName { get; set; }
[Alias("umbSiteDescription", Name = "Site Description")] // ignored by the mapper at the moment
[PropertyType(typeof(textfieldMultipleDataType))]
public string SiteDescription { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.editorControls.textfield;
using umbraco.editorControls.tinyMCE3;
namespace Umbraco.Tests.CodeFirst.TestModels
{
public class ModelWithNewDataType : ContentTypeBase
{
[PropertyType(typeof(TextFieldDataType), PropertyGroup = "Content")]
public string Title { get; set; }
[PropertyType(typeof(tinyMCE3dataType), PropertyGroup = "Content")]
public string BodyContent { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
using System;
namespace Umbraco.Tests.CodeFirst.TestModels
{
public class NewsArticle : ContentTypeBase
{
public string ArticleContent { get; set; }
public DateTime ArticleDate { get; set; }
public string ArticleAuthor { get; set; }
}
}

View File

@@ -0,0 +1,7 @@
namespace Umbraco.Tests.CodeFirst.TestModels
{
public class NewsLandingPage : ContentPage
{
public string PageTitle { get; set; }
}
}

View File

@@ -0,0 +1,10 @@
using Umbraco.Tests.CodeFirst.Attributes;
namespace Umbraco.Tests.CodeFirst.TestModels
{
public class NumericModel : ContentTypeBase
{
[Numeric("Number DataType", PreValue = "5", PropertyGroup = "Content")]
public int Number { get; set; }
}
}

View File

@@ -0,0 +1,23 @@
using System;
namespace Umbraco.Tests.CodeFirst.TestModels
{
//Name: Plain Poco Type - Alias: plainPocoType
public class PlainPocoType : ContentTypeBase
{
//Name: Title, Alias: title, DataType: Text Field
public string Title { get; set; }
//Name: Author, Alias: author, DataType: Text Field
public string Author { get; set; }
//Name: Is Finished, Alias: isFinished, DataType: Yes/No
public bool IsFinished { get; set; }
//Name: Weight, Alias: weight, DataType: Number
public int Weight { get; set; }
//Name: Publish Date, Alias: publishDate, DataType: Datepicker
public DateTime PublishDate { get; set; }
}
}

View File

@@ -0,0 +1,14 @@
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.editorControls.textfield;
namespace Umbraco.Tests.CodeFirst.TestModels
{
public class SimpleContentPage : ContentTypeBase
{
[PropertyType(typeof(TextFieldDataType), PropertyGroup = "Content")]
public string Title { get; set; }
[Richtext(PropertyGroup = "Content")]
public string BodyContent { get; set; }
}
}

View File

@@ -0,0 +1,14 @@
using Umbraco.Tests.CodeFirst.Attributes;
using umbraco.editorControls.textfield;
namespace Umbraco.Tests.CodeFirst.TestModels
{
public class TextPage : ContentTypeBase
{
[PropertyType(typeof(TextFieldDataType), PropertyGroup = "Content")]
public string Author { get; set; }
[PropertyType(typeof(TextFieldDataType), PropertyGroup = "Content")]
public string Title { get; set; }
}
}

View File

@@ -0,0 +1,118 @@
using System;
namespace Umbraco.Tests.CodeFirst
{
public class TopologicalSorter
{
#region - Private Members -
private readonly int[] _vertices; // list of vertices
private readonly int[,] _matrix; // adjacency matrix
private int _numVerts; // current number of vertices
private readonly int[] _sortedArray;
#endregion
#region - CTors -
public TopologicalSorter(int size)
{
_vertices = new int[size];
_matrix = new int[size, size];
_numVerts = 0;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
_matrix[i, j] = 0;
_sortedArray = new int[size]; // sorted vert labels
}
#endregion
#region - Public Methods -
public int AddVertex(int vertex)
{
_vertices[_numVerts++] = vertex;
return _numVerts - 1;
}
public void AddEdge(int start, int end)
{
_matrix[start, end] = 1;
}
public int[] Sort() // toplogical sort
{
while (_numVerts > 0) // while vertices remain,
{
// get a vertex with no successors, or -1
int currentVertex = noSuccessors();
if (currentVertex == -1) // must be a cycle
throw new Exception("Graph has cycles");
// insert vertex label in sorted array (start at end)
_sortedArray[_numVerts - 1] = _vertices[currentVertex];
deleteVertex(currentVertex); // delete vertex
}
// vertices all gone; return sortedArray
return _sortedArray;
}
#endregion
#region - Private Helper Methods -
// returns vert with no successors (or -1 if no such verts)
private int noSuccessors()
{
for (int row = 0; row < _numVerts; row++)
{
bool isEdge = false; // edge from row to column in adjMat
for (int col = 0; col < _numVerts; col++)
{
if (_matrix[row, col] > 0) // if edge to another,
{
isEdge = true;
break; // this vertex has a successor try another
}
}
if (!isEdge) // if no edges, has no successors
return row;
}
return -1; // no
}
private void deleteVertex(int delVert)
{
// if not last vertex, delete from vertexList
if (delVert != _numVerts - 1)
{
for (int j = delVert; j < _numVerts - 1; j++)
_vertices[j] = _vertices[j + 1];
for (int row = delVert; row < _numVerts - 1; row++)
moveRowUp(row, _numVerts);
for (int col = delVert; col < _numVerts - 1; col++)
moveColLeft(col, _numVerts - 1);
}
_numVerts--; // one less vertex
}
private void moveRowUp(int row, int length)
{
for (int col = 0; col < length; col++)
_matrix[row, col] = _matrix[row + 1, col];
}
private void moveColLeft(int col, int length)
{
for (int row = 0; row < length; row++)
_matrix[row, col] = _matrix[row, col + 1];
}
#endregion
}
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Profiling;
using Umbraco.Tests.CodeFirst.Attributes;
using Umbraco.Tests.CodeFirst.Definitions;
using Umbraco.Tests.CodeFirst.TestModels.Composition;
namespace Umbraco.Tests.CodeFirst
{
[TestFixture]
public class TypeInheritanceTest
{
private PluginManager _pluginManager;
[SetUp]
public void Initialize()
{
var logger = new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>());
//this ensures its reset
_pluginManager = new PluginManager(new ActivatorServiceProvider(), new NullCacheProvider(),
logger,
false)
{
AssembliesToScan = new[]
{
typeof (ContentTypeBase).Assembly
}
};
}
[Test]
public void Can_Get_Interfaces_From_Type()
{
var type = typeof (News);
var interfaces = type.GetInterfaces().ToList();
bool hasSeo = interfaces.Any(x => x.Name == typeof(IMetaSeo).Name);
bool hasMeta = interfaces.Any(x => x.Name == typeof(IMeta).Name);
Assert.That(hasSeo, Is.True);
Assert.That(hasMeta, Is.True);
Assert.That(interfaces.Count, Is.EqualTo(3));
}
[Test]
public void Can_Get_MixinAttribute_From_Types()
{
var type = typeof(News);
var interfaces = type.GetInterfaces().ToList();
var list = new List<string>();
foreach (var interfaceType in interfaces)
{
var mixinAttribute = interfaceType.FirstAttribute<MixinAttribute>();
if(mixinAttribute != null)
{
var modelType = mixinAttribute.Type;
var contentTypeAttribute = modelType.FirstAttribute<ContentTypeAttribute>();
var contentTypeAlias = contentTypeAttribute == null ? modelType.Name.ToUmbracoAlias() : contentTypeAttribute.Alias;
list.Add(contentTypeAlias);
}
}
Assert.That(list.Count, Is.EqualTo(3));
Assert.Contains("Meta", list);
Assert.Contains("MetaSeo", list);
Assert.Contains("Base", list);
}
[Test]
public void Ensure_Only_One_Type_List_Created()
{
var foundTypes = _pluginManager.ResolveContentTypeBaseTypes();
Assert.That(foundTypes.Count(), Is.EqualTo(15));
Assert.AreEqual(1, _pluginManager.TypeLists.Count(x => x.BaseType == typeof (ContentTypeBase) && x.AttributeType == null));
}
}
}

View File

@@ -149,7 +149,7 @@ namespace Umbraco.Tests.Collections
}
/// <summary>
/// Serves as the default hash function.
/// Serves as the default hash function.
/// </summary>
/// <returns>
/// A hash code for the current object.

View File

@@ -1,7 +1,6 @@
using System;
using System;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Collections;
namespace Umbraco.Tests.Collections
{
@@ -11,8 +10,8 @@ namespace Umbraco.Tests.Collections
[Test]
public void Keeps_Last()
{
var list = new OrderedHashSet<MyClass>(keepOldest: false);
var items = new[] { new MyClass("test"), new MyClass("test"), new MyClass("test") };
var list = new OrderedHashSet<MyClass>(keepOldest:false);
var items = new MyClass[] {new MyClass("test"), new MyClass("test"), new MyClass("test") };
foreach (var item in items)
{
list.Add(item);
@@ -27,7 +26,7 @@ namespace Umbraco.Tests.Collections
public void Keeps_First()
{
var list = new OrderedHashSet<MyClass>(keepOldest: true);
var items = new[] { new MyClass("test"), new MyClass("test"), new MyClass("test") };
var items = new MyClass[] { new MyClass("test"), new MyClass("test"), new MyClass("test") };
foreach (var item in items)
{
list.Add(item);
@@ -45,8 +44,8 @@ namespace Umbraco.Tests.Collections
Id = Guid.NewGuid();
}
public string Name { get; }
public Guid Id { get; }
public string Name { get; private set; }
public Guid Id { get; private set; }
public bool Equals(MyClass other)
{
@@ -60,7 +59,7 @@ namespace Umbraco.Tests.Collections
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((MyClass)obj);
return Equals((MyClass) obj);
}
public override int GetHashCode()
@@ -75,8 +74,8 @@ namespace Umbraco.Tests.Collections
public static bool operator !=(MyClass left, MyClass right)
{
return Equals(left, right) == false;
return !Equals(left, right);
}
}
}
}
}

View File

@@ -1,382 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using LightInject;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Components;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Mappers;
using Umbraco.Core.Scoping;
using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests.Components
{
[TestFixture]
public class ComponentTests
{
private static readonly List<Type> Composed = new List<Type>();
private static readonly List<string> Initialized = new List<string>();
private static IServiceContainer MockContainer(Action<Mock<IServiceContainer>> setup = null)
{
// fixme use IUmbracoDatabaseFactory vs UmbracoDatabaseFactory, clean it all up!
var testObjects = new TestObjects(null);
var logger = Mock.Of<ILogger>();
var s = testObjects.GetDefaultSqlSyntaxProviders(logger);
var f = new UmbracoDatabaseFactory(s, logger, new MapperCollection(Enumerable.Empty<BaseMapper>()));
var fs = new FileSystems(logger);
var p = new ScopeProvider(f, fs, logger);
var mock = new Mock<IServiceContainer>();
mock.Setup(x => x.GetInstance(typeof (ILogger))).Returns(logger);
mock.Setup(x => x.GetInstance(typeof (ProfilingLogger))).Returns(new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
mock.Setup(x => x.GetInstance(typeof (IUmbracoDatabaseFactory))).Returns(f);
mock.Setup(x => x.GetInstance(typeof (IScopeProvider))).Returns(p);
setup?.Invoke(mock);
return mock.Object;
}
[Test]
public void Boot1A()
{
var container = MockContainer();
var loader = new BootLoader(container);
Composed.Clear();
// 2 is Core and requires 4
// 3 is User - goes away with RuntimeLevel.Unknown
// => reorder components accordingly
loader.Boot(TypeArray<Component1, Component2, Component3, Component4>(), RuntimeLevel.Unknown);
AssertTypeArray(TypeArray<Component1, Component4, Component2>(), Composed);
}
[Test]
public void Boot1B()
{
var container = MockContainer();
var loader = new BootLoader(container);
Composed.Clear();
// 2 is Core and requires 4
// 3 is User - stays with RuntimeLevel.Run
// => reorder components accordingly
loader.Boot(TypeArray<Component1, Component2, Component3, Component4>(), RuntimeLevel.Run);
AssertTypeArray(TypeArray<Component1, Component4, Component2, Component3>(), Composed);
}
[Test]
public void Boot2()
{
var container = MockContainer();
var loader = new BootLoader(container);
Composed.Clear();
// 21 is required by 20
// => reorder components accordingly
loader.Boot(TypeArray<Component20, Component21>(), RuntimeLevel.Unknown);
AssertTypeArray(TypeArray<Component21, Component20>(), Composed);
}
[Test]
public void Boot3()
{
var container = MockContainer();
var loader = new BootLoader(container);
Composed.Clear();
// i23 requires 22
// 24, 25 implement i23
// 25 required by i23
// => reorder components accordingly
loader.Boot(TypeArray<Component22, Component24, Component25>(), RuntimeLevel.Unknown);
AssertTypeArray(TypeArray<Component22, Component25, Component24>(), Composed);
}
[Test]
public void BrokenRequire()
{
var container = MockContainer();
var thing = new BootLoader(container);
Composed.Clear();
try
{
// 2 is Core and requires 4
// 4 is missing
// => throw
thing.Boot(TypeArray < Component1, Component2, Component3>(), RuntimeLevel.Unknown);
Assert.Fail("Expected exception.");
}
catch (Exception e)
{
Assert.AreEqual("Broken component dependency: Umbraco.Tests.Components.ComponentTests+Component2 -> Umbraco.Tests.Components.ComponentTests+Component4.", e.Message);
}
}
[Test]
public void BrokenRequired()
{
var container = MockContainer();
var thing = new BootLoader(container);
Composed.Clear();
// 2 is Core and requires 4
// 13 is required by 1
// 1 is missing
// => reorder components accordingly
thing.Boot(TypeArray<Component2, Component4, Component13>(), RuntimeLevel.Unknown);
AssertTypeArray(TypeArray<Component4, Component2, Component13>(), Composed);
}
[Test]
public void Initialize()
{
var container = MockContainer(m =>
{
m.Setup(x => x.TryGetInstance(It.Is<Type>(t => t == typeof (ISomeResource)))).Returns(() => new SomeResource());
});
var thing = new BootLoader(container);
Composed.Clear();
thing.Boot(new[] { typeof(Component1), typeof(Component5) }, RuntimeLevel.Unknown);
Assert.AreEqual(2, Composed.Count);
Assert.AreEqual(typeof(Component1), Composed[0]);
Assert.AreEqual(typeof(Component5), Composed[1]);
Assert.AreEqual(1, Initialized.Count);
Assert.AreEqual("Umbraco.Tests.Components.ComponentTests+SomeResource", Initialized[0]);
}
[Test]
public void Requires1()
{
var container = MockContainer();
var thing = new BootLoader(container);
Composed.Clear();
thing.Boot(new[] { typeof(Component6), typeof(Component7), typeof(Component8) }, RuntimeLevel.Unknown);
Assert.AreEqual(2, Composed.Count);
Assert.AreEqual(typeof(Component6), Composed[0]);
Assert.AreEqual(typeof(Component8), Composed[1]);
}
[Test]
public void Requires2A()
{
var container = MockContainer();
var thing = new BootLoader(container);
Composed.Clear();
thing.Boot(new[] { typeof(Component9), typeof(Component2), typeof(Component4) }, RuntimeLevel.Unknown);
Assert.AreEqual(2, Composed.Count);
Assert.AreEqual(typeof(Component4), Composed[0]);
Assert.AreEqual(typeof(Component2), Composed[1]);
//Assert.AreEqual(typeof(Component9), Composed[2]); -- goes away with RuntimeLevel.Unknown
}
[Test]
public void Requires2B()
{
var container = MockContainer();
var thing = new BootLoader(container);
Composed.Clear();
thing.Boot(new[] { typeof(Component9), typeof(Component2), typeof(Component4) }, RuntimeLevel.Run);
Assert.AreEqual(3, Composed.Count);
Assert.AreEqual(typeof(Component4), Composed[0]);
Assert.AreEqual(typeof(Component2), Composed[1]);
Assert.AreEqual(typeof(Component9), Composed[2]);
}
[Test]
public void WeakDependencies()
{
var container = MockContainer();
var thing = new BootLoader(container);
Composed.Clear();
thing.Boot(new[] { typeof(Component10) }, RuntimeLevel.Unknown);
Assert.AreEqual(1, Composed.Count);
Assert.AreEqual(typeof(Component10), Composed[0]);
thing = new BootLoader(container);
Composed.Clear();
Assert.Throws<Exception>(() => thing.Boot(new[] { typeof(Component11) }, RuntimeLevel.Unknown));
thing = new BootLoader(container);
Composed.Clear();
Assert.Throws<Exception>(() => thing.Boot(new[] { typeof(Component2) }, RuntimeLevel.Unknown));
thing = new BootLoader(container);
Composed.Clear();
thing.Boot(new[] { typeof(Component12) }, RuntimeLevel.Unknown);
Assert.AreEqual(1, Composed.Count);
Assert.AreEqual(typeof(Component12), Composed[0]);
}
[Test]
public void DisableMissing()
{
var container = MockContainer();
var thing = new BootLoader(container);
Composed.Clear();
thing.Boot(new[] { typeof(Component6), typeof(Component8) }, RuntimeLevel.Unknown); // 8 disables 7 which is not in the list
Assert.AreEqual(2, Composed.Count);
Assert.AreEqual(typeof(Component6), Composed[0]);
Assert.AreEqual(typeof(Component8), Composed[1]);
}
#region Components
public class TestComponentBase : UmbracoComponentBase
{
public override void Compose(Composition composition)
{
base.Compose(composition);
Composed.Add(GetType());
}
}
public class Component1 : TestComponentBase
{ }
[RequireComponent(typeof(Component4))]
public class Component2 : TestComponentBase, IUmbracoCoreComponent
{ }
public class Component3 : TestComponentBase, IUmbracoUserComponent
{ }
public class Component4 : TestComponentBase
{ }
public class Component5 : TestComponentBase
{
public void Initialize(ISomeResource resource)
{
Initialized.Add(resource.GetType().FullName);
}
}
[DisableComponent]
public class Component6 : TestComponentBase
{ }
public class Component7 : TestComponentBase
{ }
[DisableComponent(typeof(Component7))]
[EnableComponent(typeof(Component6))]
public class Component8 : TestComponentBase
{ }
public interface ITestComponent : IUmbracoUserComponent
{ }
public class Component9 : TestComponentBase, ITestComponent
{ }
[RequireComponent(typeof(ITestComponent))]
public class Component10 : TestComponentBase
{ }
[RequireComponent(typeof(ITestComponent), false)]
public class Component11 : TestComponentBase
{ }
[RequireComponent(typeof(Component4), true)]
public class Component12 : TestComponentBase, IUmbracoCoreComponent
{ }
[RequiredComponent(typeof(Component1))]
public class Component13 : TestComponentBase
{ }
public interface ISomeResource { }
public class SomeResource : ISomeResource { }
public class Component20 : TestComponentBase
{ }
[RequiredComponent(typeof(Component20))]
public class Component21 : TestComponentBase
{ }
public class Component22 : TestComponentBase
{ }
[RequireComponent(typeof(Component22))]
public interface IComponent23 : IUmbracoComponent
{ }
public class Component24 : TestComponentBase, IComponent23
{ }
// should insert itself between 22 and anything i23
[RequiredComponent(typeof(IComponent23))]
//[RequireComponent(typeof(Component22))] - not needed, implement i23
public class Component25 : TestComponentBase, IComponent23
{ }
#endregion
#region TypeArray
// fixme - move to Testing
private static Type[] TypeArray<T1>()
{
return new[] { typeof(T1) };
}
private static Type[] TypeArray<T1, T2>()
{
return new[] { typeof(T1), typeof(T2) };
}
private static Type[] TypeArray<T1, T2, T3>()
{
return new[] { typeof(T1), typeof(T2), typeof(T3) };
}
private static Type[] TypeArray<T1, T2, T3, T4>()
{
return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) };
}
private static Type[] TypeArray<T1, T2, T3, T4, T5>()
{
return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) };
}
private static Type[] TypeArray<T1, T2, T3, T4, T5, T6>()
{
return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) };
}
private static Type[] TypeArray<T1, T2, T3, T4, T5, T6, T7>()
{
return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) };
}
private static Type[] TypeArray<T1, T2, T3, T4, T5, T6, T7, T8>()
{
return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) };
}
private static void AssertTypeArray(IReadOnlyList<Type> expected, IReadOnlyList<Type> test)
{
Assert.AreEqual(expected.Count, test.Count);
for (var i = 0; i < expected.Count; i++)
Assert.AreEqual(expected[i], test[i]);
}
#endregion
}
}

View File

@@ -1,486 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using LightInject;
using NUnit.Framework;
using Umbraco.Core.Composing;
namespace Umbraco.Tests.Composing
{
[TestFixture]
public class CollectionBuildersTests
{
private ServiceContainer _container;
[SetUp]
public void Setup()
{
Current.Reset();
_container = new ServiceContainer();
_container.ConfigureUmbracoCore();
}
[TearDown]
public void TearDown()
{
Current.Reset();
_container.Dispose();
_container = null;
}
[Test]
public void ContainsTypes()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsFalse(builder.Has<Resolved3>());
//Assert.IsFalse(col.ContainsType<Resolved4>()); // does not compile
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CanClearBuilderBeforeCollectionIsCreated()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
builder.Clear();
Assert.IsFalse(builder.Has<Resolved1>());
Assert.IsFalse(builder.Has<Resolved2>());
var col = builder.CreateCollection();
AssertCollection(col);
}
[Test]
public void CannotClearBuilderOnceCollectionIsCreated()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
var col = builder.CreateCollection();
Assert.Throws<InvalidOperationException>(() => builder.Clear());
}
[Test]
public void CanAppendToBuilder()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>();
builder.Append<Resolved1>();
builder.Append<Resolved2>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsFalse(builder.Has<Resolved3>());
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CannotAppendToBuilderOnceCollectionIsCreated()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>();
var col = builder.CreateCollection();
Assert.Throws<InvalidOperationException>(() =>
builder.Append<Resolved1>()
);
}
[Test]
public void CanAppendDuplicateToBuilderAndDeDuplicate()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>();
builder.Append<Resolved1>();
builder.Append<Resolved1>();
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved1));
}
[Test]
public void CannotAppendInvalidTypeToBUilder()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>();
//builder.Append<Resolved4>(); // does not compile
Assert.Throws<InvalidOperationException>(() =>
builder.Append(new[] { typeof (Resolved4) }) // throws
);
}
[Test]
public void CanRemoveFromBuilder()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Remove<Resolved2>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsFalse(builder.Has<Resolved2>());
Assert.IsFalse(builder.Has<Resolved3>());
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved1));
}
[Test]
public void CanRemoveMissingFromBuilder()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Remove<Resolved3>();
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CannotRemoveFromBuilderOnceCollectionIsCreated()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
var col = builder.CreateCollection();
Assert.Throws<InvalidOperationException>(() =>
builder.Remove<Resolved2>() // throws
);
}
[Test]
public void CanInsertIntoBuilder()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Insert<Resolved3>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved3), typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CannotInsertIntoBuilderOnceCollectionIsCreated()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
var col = builder.CreateCollection();
Assert.Throws<InvalidOperationException>(() =>
builder.Insert<Resolved3>() // throws
);
}
[Test]
public void CanInsertDuplicateIntoBuilderAndDeDuplicate()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Insert<Resolved2>();
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved2), typeof(Resolved1));
}
[Test]
public void CanInsertIntoEmptyBuilder()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>();
builder.Insert<Resolved2>();
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved2));
}
[Test]
public void CannotInsertIntoBuilderAtWrongIndex()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
Assert.Throws<ArgumentOutOfRangeException>(() =>
builder.Insert<Resolved3>(99) // throws
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
builder.Insert<Resolved3>(-1) // throws
);
}
[Test]
public void CanInsertIntoBuilderBefore()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertBefore<Resolved2, Resolved3>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved1), typeof(Resolved3), typeof(Resolved2));
}
[Test]
public void CannotInsertIntoBuilderBeforeOnceCollectionIsCreated()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
var col = builder.CreateCollection();
Assert.Throws<InvalidOperationException>(() =>
builder.InsertBefore<Resolved2, Resolved3>()
);
}
[Test]
public void CanInsertDuplicateIntoBuilderBeforeAndDeDuplicate()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertBefore<Resolved1, Resolved2>();
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved2), typeof(Resolved1));
}
[Test]
public void CannotInsertIntoBuilderBeforeMissing()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>();
Assert.Throws<InvalidOperationException>(() =>
builder.InsertBefore<Resolved2, Resolved3>()
);
}
[Test]
public void ScopeBuilderCreatesScopedCollection()
{
_container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
// CreateCollection creates a new collection each time
// but the container manages the scope, so to test the scope
// the collection must come from the container
var col1 = _container.GetInstance<TestCollection>();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2));
var col2 = _container.GetInstance<TestCollection>();
AssertCollection(col2, typeof(Resolved1), typeof(Resolved2));
AssertSameCollection(col1, col2);
}
[Test]
public void TransientBuilderCreatesTransientCollection()
{
_container.RegisterCollectionBuilder<TestCollectionBuilderTransient>()
.Append<Resolved1>()
.Append<Resolved2>();
// CreateCollection creates a new collection each time
// but the container manages the scope, so to test the scope
// the collection must come from the container
var col1 = _container.GetInstance<TestCollection>();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2));
var col2 = _container.GetInstance<TestCollection>();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2));
AssertNotSameCollection(col1, col2);
}
[Test]
public void BuilderRespectsTypesOrder()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilderTransient>()
.Append<Resolved3>()
.Insert<Resolved1>()
.InsertBefore<Resolved3, Resolved2>();
var col1 = builder.CreateCollection();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2), typeof(Resolved3));
}
[Test]
public void ScopeBuilderRespectsContainerScope()
{
_container.RegisterCollectionBuilder<TestCollectionBuilderScope>()
.Append<Resolved1>()
.Append<Resolved2>();
// CreateCollection creates a new collection each time
// but the container manages the scope, so to test the scope
// the collection must come from the container
var scope1 = _container.BeginScope();
var col1A = _container.GetInstance<TestCollection>();
AssertCollection(col1A, typeof(Resolved1), typeof(Resolved2));
var col1B = _container.GetInstance<TestCollection>();
AssertCollection(col1B, typeof(Resolved1), typeof(Resolved2));
AssertSameCollection(col1A, col1B);
_container.ScopeManagerProvider.GetScopeManager(_container).CurrentScope.Dispose();
var scope2 = _container.BeginScope();
var col2 = _container.GetInstance<TestCollection>();
AssertCollection(col2, typeof(Resolved1), typeof(Resolved2));
AssertNotSameCollection(col1A, col2);
_container.ScopeManagerProvider.GetScopeManager(_container).CurrentScope.Dispose();
}
[Test]
public void WeightedBuilderCreatesWeightedCollection()
{
var builder = _container.RegisterCollectionBuilder<TestCollectionBuilderWeighted>()
.Add<Resolved1>()
.Add<Resolved2>();
var col = builder.CreateCollection();
AssertCollection(col, typeof(Resolved2), typeof(Resolved1));
}
#region Assertions
private static void AssertCollection(IEnumerable<Resolved> col, params Type[] expected)
{
var colA = col.ToArray();
Assert.AreEqual(expected.Length, colA.Length);
for (var i = 0; i < expected.Length; i++)
Assert.IsInstanceOf(expected[i], colA[i]);
}
private static void AssertSameCollection(IEnumerable<Resolved> col1, IEnumerable<Resolved> col2)
{
Assert.AreSame(col1, col2);
var col1A = col1.ToArray();
var col2A = col2.ToArray();
Assert.AreEqual(col1A.Length, col2A.Length);
for (var i = 0; i < col1A.Length; i++)
Assert.AreSame(col1A[i], col2A[i]);
}
private static void AssertNotSameCollection(IEnumerable<Resolved> col1, IEnumerable<Resolved> col2)
{
Assert.AreNotSame(col1, col2);
var col1A = col1.ToArray();
var col2A = col2.ToArray();
Assert.AreEqual(col1A.Length, col2A.Length);
for (var i = 0; i < col1A.Length; i++)
Assert.AreNotSame(col1A[i], col2A[i]);
}
#endregion
#region Test Objects
public abstract class Resolved
{ }
public class Resolved1 : Resolved
{ }
[Weight(5)] // default is 10
public class Resolved2 : Resolved
{ }
public class Resolved3 : Resolved
{ }
public class Resolved4 // not! : Resolved
{ }
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollectionBuilder : OrderedCollectionBuilderBase<TestCollectionBuilder, TestCollection, Resolved>
{
public TestCollectionBuilder(IServiceContainer container)
: base(container)
{ }
protected override TestCollectionBuilder This => this;
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollectionBuilderTransient : OrderedCollectionBuilderBase<TestCollectionBuilderTransient, TestCollection, Resolved>
{
public TestCollectionBuilderTransient(IServiceContainer container)
: base(container)
{ }
protected override TestCollectionBuilderTransient This => this;
protected override ILifetime CollectionLifetime => null; // transient
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollectionBuilderScope : OrderedCollectionBuilderBase<TestCollectionBuilderScope, TestCollection, Resolved>
{
public TestCollectionBuilderScope(IServiceContainer container)
: base(container)
{ }
protected override TestCollectionBuilderScope This => this;
protected override ILifetime CollectionLifetime => new PerScopeLifetime();
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollectionBuilderWeighted : WeightedCollectionBuilderBase<TestCollectionBuilderWeighted, TestCollection, Resolved>
{
public TestCollectionBuilderWeighted(IServiceContainer container)
: base(container)
{ }
protected override TestCollectionBuilderWeighted This => this;
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollection : BuilderCollectionBase<Resolved>
{
public TestCollection(IEnumerable<Resolved> items)
: base(items)
{ }
}
#endregion
}
}

View File

@@ -1,41 +0,0 @@
using System.Collections.Generic;
using System.Reflection;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests.Composing
{
public abstract class ComposingTestBase
{
protected TypeLoader TypeLoader { get; private set; }
protected ProfilingLogger ProfilingLogger { get; private set; }
[SetUp]
public void Initialize()
{
ProfilingLogger = new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>());
TypeLoader = new TypeLoader(NullCacheProvider.Instance, SettingsForTests.GenerateMockGlobalSettings(), ProfilingLogger, detectChanges: false)
{
AssembliesToScan = AssembliesToScan
};
}
[TearDown]
public void TearDown()
{
Current.Reset();
}
protected virtual IEnumerable<Assembly> AssembliesToScan
=> new[]
{
GetType().Assembly // this assembly only
};
}
}

View File

@@ -1,187 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using LightInject;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Composing;
namespace Umbraco.Tests.Composing
{
[TestFixture]
public class LazyCollectionBuilderTests
{
[SetUp]
public void Initialize()
{
Current.Reset();
}
[TearDown]
public void TearDown()
{
Current.Reset();
}
// note
// lazy collection builder does not throw on duplicate, just uses distinct types
// so we don't have a test for duplicates as we had with resolvers in v7
[Test]
public void LazyCollectionBuilderHandlesTypes()
{
var container = new ServiceContainer();
container.ConfigureUmbracoCore();
container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Add<TransientObject3>()
.Add<TransientObject2>()
.Add<TransientObject3>()
.Add<TransientObject1>();
var values = container.GetInstance<TestCollection>();
Assert.AreEqual(3, values.Count());
Assert.IsTrue(values.Select(x => x.GetType())
.ContainsAll(new[] { typeof(TransientObject1), typeof(TransientObject2), typeof(TransientObject3) }));
var other = container.GetInstance<TestCollection>();
Assert.AreNotSame(values, other); // transient
var o1 = other.FirstOrDefault(x => x is TransientObject1);
Assert.IsFalse(values.Contains(o1)); // transient
}
[Test]
public void LazyCollectionBuilderHandlesProducers()
{
var container = new ServiceContainer();
container.ConfigureUmbracoCore();
container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Add(() => new[] { typeof(TransientObject3), typeof(TransientObject2) })
.Add(() => new[] { typeof(TransientObject3), typeof(TransientObject2) })
.Add(() => new[] { typeof(TransientObject1) });
var values = container.GetInstance<TestCollection>();
Assert.AreEqual(3, values.Count());
Assert.IsTrue(values.Select(x => x.GetType())
.ContainsAll(new[] { typeof(TransientObject1), typeof(TransientObject2), typeof(TransientObject3) }));
var other = container.GetInstance<TestCollection>();
Assert.AreNotSame(values, other); // transient
var o1 = other.FirstOrDefault(x => x is TransientObject1);
Assert.IsFalse(values.Contains(o1)); // transient
}
[Test]
public void LazyCollectionBuilderHandlesTypesAndProducers()
{
var container = new ServiceContainer();
container.ConfigureUmbracoCore();
container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Add<TransientObject3>()
.Add<TransientObject2>()
.Add<TransientObject3>()
.Add(() => new[] { typeof(TransientObject1) });
var values = container.GetInstance<TestCollection>();
Assert.AreEqual(3, values.Count());
Assert.IsTrue(values.Select(x => x.GetType())
.ContainsAll(new[] { typeof(TransientObject1), typeof(TransientObject2), typeof(TransientObject3) }));
var other = container.GetInstance<TestCollection>();
Assert.AreNotSame(values, other); // transient
var o1 = other.FirstOrDefault(x => x is TransientObject1);
Assert.IsFalse(values.Contains(o1)); // transient
}
[Test]
public void LazyCollectionBuilderThrowsOnIllegalTypes()
{
var container = new ServiceContainer();
container.ConfigureUmbracoCore();
container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Add<TransientObject3>()
// illegal, does not implement the interface!
//.Add<TransientObject4>()
// legal so far...
.Add(() => new[] { typeof(TransientObject4) });
Assert.Throws<InvalidOperationException>(() =>
{
// but throws here when trying to register the types
var values = container.GetInstance<TestCollection>();
});
}
[Test]
public void LazyCollectionBuilderCanExcludeTypes()
{
var container = new ServiceContainer();
container.ConfigureUmbracoCore();
container.RegisterCollectionBuilder<TestCollectionBuilder>()
.Add<TransientObject3>()
.Add(() => new[] { typeof(TransientObject3), typeof(TransientObject2), typeof(TransientObject1) })
.Exclude<TransientObject3>();
var values = container.GetInstance<TestCollection>();
Assert.AreEqual(2, values.Count());
Assert.IsFalse(values.Select(x => x.GetType())
.Contains(typeof(TransientObject3)));
Assert.IsTrue(values.Select(x => x.GetType())
.ContainsAll(new[] { typeof(TransientObject1), typeof(TransientObject2) }));
var other = container.GetInstance<TestCollection>();
Assert.AreNotSame(values, other); // transient
var o1 = other.FirstOrDefault(x => x is TransientObject1);
Assert.IsFalse(values.Contains(o1)); // transient
}
#region Test Objects
private interface ITestInterface
{ }
private class TransientObject1 : ITestInterface
{ }
private class TransientObject2 : ITestInterface
{ }
private class TransientObject3 : ITestInterface
{ }
private class TransientObject4
{ }
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollectionBuilder : LazyCollectionBuilderBase<TestCollectionBuilder, TestCollection, ITestInterface>
{
public TestCollectionBuilder(IServiceContainer container)
: base(container)
{ }
protected override TestCollectionBuilder This => this;
protected override ILifetime CollectionLifetime => null; // transient
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollection : BuilderCollectionBase<ITestInterface>
{
public TestCollection(IEnumerable<ITestInterface> items)
: base(items)
{ }
}
#endregion
}
}

View File

@@ -1,83 +0,0 @@
using System;
using System.Linq;
using System.Xml;
using LightInject;
using NUnit.Framework;
using Umbraco.Core.Composing;
using Umbraco.Core._Legacy.PackageActions;
namespace Umbraco.Tests.Composing
{
[TestFixture]
public class PackageActionCollectionTests : ComposingTestBase
{
[Test]
public void PackageActionCollectionBuilderWorks()
{
var container = new ServiceContainer();
container.ConfigureUmbracoCore();
container.RegisterCollectionBuilder<PackageActionCollectionBuilder>()
.Add(() => TypeLoader.GetPackageActions());
var actions = Current.PackageActions;
Assert.AreEqual(2, actions.Count());
// order is unspecified, but both must be there
bool hasAction1 = actions.ElementAt(0) is PackageAction1 || actions.ElementAt(1) is PackageAction1;
bool hasAction2 = actions.ElementAt(0) is PackageAction2 || actions.ElementAt(1) is PackageAction2;
Assert.IsTrue(hasAction1);
Assert.IsTrue(hasAction2);
}
#region Test Objects
public class PackageAction1 : IPackageAction
{
public bool Execute(string packageName, XmlNode xmlData)
{
throw new NotImplementedException();
}
public string Alias()
{
return "pa1";
}
public bool Undo(string packageName, XmlNode xmlData)
{
throw new NotImplementedException();
}
public XmlNode SampleXml()
{
throw new NotImplementedException();
}
}
public class PackageAction2 : IPackageAction
{
public bool Execute(string packageName, XmlNode xmlData)
{
throw new NotImplementedException();
}
public string Alias()
{
return "pa2";
}
public bool Undo(string packageName, XmlNode xmlData)
{
throw new NotImplementedException();
}
public XmlNode SampleXml()
{
throw new NotImplementedException();
}
}
#endregion
}
}

View File

@@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using Umbraco.Core.Composing;
namespace Umbraco.Tests.Composing
{
/// <summary>
/// Used for PluginTypeResolverTests
/// </summary>
internal static class TypeLoaderExtensions
{
public static IEnumerable<Type> ResolveFindMeTypes(this TypeLoader resolver)
{
return resolver.GetTypes<TypeLoaderTests.IFindMe>();
}
}
}

View File

@@ -1,317 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Moq;
using NUnit.Framework;
using umbraco;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.PropertyEditors;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.PropertyEditors;
namespace Umbraco.Tests.Composing
{
[TestFixture]
public class TypeLoaderTests
{
private TypeLoader _typeLoader;
[SetUp]
public void Initialize()
{
// this ensures it's reset
_typeLoader = new TypeLoader(NullCacheProvider.Instance, SettingsForTests.GenerateMockGlobalSettings(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
foreach (var file in Directory.GetFiles(IOHelper.MapPath("~/App_Data/TEMP/TypesCache")))
File.Delete(file);
// for testing, we'll specify which assemblies are scanned for the PluginTypeResolver
// TODO: Should probably update this so it only searches this assembly and add custom types to be found
_typeLoader.AssembliesToScan = new[]
{
this.GetType().Assembly,
typeof(System.Guid).Assembly,
typeof(NUnit.Framework.Assert).Assembly,
typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly,
typeof(System.Xml.NameTable).Assembly,
typeof(System.Configuration.GenericEnumConverter).Assembly,
typeof(System.Web.SiteMap).Assembly,
//typeof(TabPage).Assembly,
typeof(System.Web.Mvc.ActionResult).Assembly,
typeof(TypeFinder).Assembly,
typeof(UmbracoContext).Assembly
};
}
[TearDown]
public void TearDown()
{
_typeLoader = null;
}
private DirectoryInfo PrepareFolder()
{
var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
var dir = Directory.CreateDirectory(Path.Combine(assDir.FullName, "TypeLoader", Guid.NewGuid().ToString("N")));
foreach (var f in dir.GetFiles())
{
f.Delete();
}
return dir;
}
//[Test]
//public void Scan_Vs_Load_Benchmark()
//{
// var typeLoader = new TypeLoader(false);
// var watch = new Stopwatch();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = Type.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type3 = Type.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type4 = Type.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type5 = Type.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds);
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = BuildManager.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type3 = BuildManager.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type4 = BuildManager.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type5 = BuildManager.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds);
// watch.Reset();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var refreshers = typeLoader.GetTypes<ICacheRefresher>(false);
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (2nd round): " + watch.ElapsedMilliseconds);
//}
////NOTE: This test shows that Type.GetType is 100% faster than Assembly.Load(..).GetType(...) so we'll use that :)
//[Test]
//public void Load_Type_Benchmark()
//{
// var watch = new Stopwatch();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = Type.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type3 = Type.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type4 = Type.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type5 = Type.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds);
// watch.Reset();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null")
// .GetType("umbraco.macroCacheRefresh");
// var type3 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null")
// .GetType("umbraco.templateCacheRefresh");
// var type4 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null")
// .GetType("umbraco.presentation.cache.MediaLibraryRefreshers");
// var type5 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null")
// .GetType("umbraco.presentation.cache.pageRefresher");
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (2nd round): " + watch.ElapsedMilliseconds);
// watch.Reset();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = BuildManager.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type3 = BuildManager.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type4 = BuildManager.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type5 = BuildManager.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds);
//}
[Test]
public void Detect_Legacy_Plugin_File_List()
{
var filePath = _typeLoader.GetTypesListFilePath();
var fileDir = Path.GetDirectoryName(filePath);
Directory.CreateDirectory(fileDir);
File.WriteAllText(filePath, @"<?xml version=""1.0"" encoding=""utf-8""?>
<plugins>
<baseType type=""umbraco.interfaces.ICacheRefresher"">
<add type=""umbraco.macroCacheRefresh, umbraco, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</baseType>
</plugins>");
Assert.IsEmpty(_typeLoader.ReadCache()); // uber-legacy cannot be read
File.Delete(filePath);
File.WriteAllText(filePath, @"<?xml version=""1.0"" encoding=""utf-8""?>
<plugins>
<baseType type=""umbraco.interfaces.ICacheRefresher"" resolutionType=""FindAllTypes"">
<add type=""umbraco.macroCacheRefresh, umbraco, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</baseType>
</plugins>");
Assert.IsEmpty(_typeLoader.ReadCache()); // legacy cannot be read
File.Delete(filePath);
File.WriteAllText(filePath, @"IContentFinder
MyContentFinder
AnotherContentFinder
");
Assert.IsNotNull(_typeLoader.ReadCache()); // works
}
[Test]
public void Create_Cached_Plugin_File()
{
var types = new[] { typeof (TypeLoader), typeof (TypeLoaderTests), typeof (UmbracoContext) };
var typeList1 = new TypeLoader.TypeList(typeof (object), null);
foreach (var type in types) typeList1.Add(type);
_typeLoader.AddTypeList(typeList1);
_typeLoader.WriteCache();
var plugins = _typeLoader.TryGetCached(typeof (object), null);
var diffType = _typeLoader.TryGetCached(typeof (object), typeof (ObsoleteAttribute));
Assert.IsTrue(plugins.Success);
//this will be false since there is no cache of that type resolution kind
Assert.IsFalse(diffType.Success);
Assert.AreEqual(3, plugins.Result.Count());
var shouldContain = types.Select(x => x.AssemblyQualifiedName);
//ensure they are all found
Assert.IsTrue(plugins.Result.ContainsAll(shouldContain));
}
[Test]
public void Get_Plugins_Hash()
{
//Arrange
var dir = PrepareFolder();
var d1 = dir.CreateSubdirectory("1");
var d2 = dir.CreateSubdirectory("2");
var d3 = dir.CreateSubdirectory("3");
var d4 = dir.CreateSubdirectory("4");
var f1 = new FileInfo(Path.Combine(d1.FullName, "test1.dll"));
var f2 = new FileInfo(Path.Combine(d1.FullName, "test2.dll"));
var f3 = new FileInfo(Path.Combine(d2.FullName, "test1.dll"));
var f4 = new FileInfo(Path.Combine(d2.FullName, "test2.dll"));
var f5 = new FileInfo(Path.Combine(d3.FullName, "test1.dll"));
var f6 = new FileInfo(Path.Combine(d3.FullName, "test2.dll"));
var f7 = new FileInfo(Path.Combine(d4.FullName, "test1.dll"));
f1.CreateText().Close();
f2.CreateText().Close();
f3.CreateText().Close();
f4.CreateText().Close();
f5.CreateText().Close();
f6.CreateText().Close();
f7.CreateText().Close();
var list1 = new[] { f1, f2, f3, f4, f5, f6 };
var list2 = new[] { f1, f3, f5 };
var list3 = new[] { f1, f3, f5, f7 };
//Act
var hash1 = TypeLoader.GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var hash2 = TypeLoader.GetFileHash(list2, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var hash3 = TypeLoader.GetFileHash(list3, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
//Assert
Assert.AreNotEqual(hash1, hash2);
Assert.AreNotEqual(hash1, hash3);
Assert.AreNotEqual(hash2, hash3);
Assert.AreEqual(hash1, TypeLoader.GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())));
}
[Test]
public void Ensure_Only_One_Type_List_Created()
{
_ = _typeLoader.ResolveFindMeTypes();
_ = _typeLoader.ResolveFindMeTypes();
Assert.AreEqual(1, _typeLoader.TypeLists.Count(x => x.BaseType == typeof(IFindMe) && x.AttributeType == null));
}
[Test]
public void Resolves_Assigned_Mappers()
{
var foundTypes1 = _typeLoader.GetAssignedMapperTypes();
Assert.AreEqual(29, foundTypes1.Count());
}
[Test]
public void Resolves_Types()
{
var foundTypes1 = _typeLoader.ResolveFindMeTypes();
Assert.AreEqual(2, foundTypes1.Count());
}
[Test]
public void GetDataEditors()
{
var types = _typeLoader.GetDataEditors();
Assert.AreEqual(39, types.Count());
}
/// <summary>
/// This demonstrates this issue: http://issues.umbraco.org/issue/U4-3505 - the TypeList was returning a list of assignable types
/// not explicit types which is sort of ideal but is confusing so we'll do it the less confusing way.
/// </summary>
[Test]
public void TypeList_Resolves_Explicit_Types()
{
var types = new HashSet<TypeLoader.TypeList>();
var propEditors = new TypeLoader.TypeList(typeof (DataEditor), null);
propEditors.Add(typeof(LabelPropertyEditor));
types.Add(propEditors);
var found = types.SingleOrDefault(x => x.BaseType == typeof (DataEditor) && x.AttributeType == null);
Assert.IsNotNull(found);
//This should not find a type list of this type
var shouldNotFind = types.SingleOrDefault(x => x.BaseType == typeof (IDataEditor) && x.AttributeType == null);
Assert.IsNull(shouldNotFind);
}
public interface IFindMe : IDiscoverable
{
}
public class FindMe1 : IFindMe
{
}
public class FindMe2 : IFindMe
{
}
}
}

View File

@@ -1,114 +1,114 @@
<?xml version="1.0" encoding="utf-8"?>
<dashBoard>
<section alias="StartupSettingsDashboardSection">
<areas>
<area>settings</area>
</areas>
<tab caption="Get Started">
<control showOnce="true" addPanel="true" panelCaption="hello">
views/dashboard/settings/settingsdashboardintro.html
</control>
<control showOnce="false" addPanel="false" panelCaption="">
views/dashboard/settings/settingsdashboardvideos.html
</control>
</tab>
<tab caption="Examine Management">
<control>dashboard/ExamineManagement.ascx</control>
</tab>
</section>
<section alias="StartupDeveloperDashboardSection">
<areas>
<area>developer</area>
</areas>
<tab caption="Get Started">
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/developer/developerdashboardintro.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/developer/developerdashboardvideos.html
</control>
</tab>
</section>
<section alias="StartupMediaDashboardSection">
<areas>
<area>media</area>
</areas>
<tab caption="Content">
<control showOnce="false" addPanel="false" panelCaption="">
views/dashboard/media/mediafolderbrowser.html
</control>
</tab>
<tab caption="Get Started">
<access>
<grant>admin</grant>
</access>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/media/mediadashboardintro.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/media/desktopmediauploader.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/media/mediadashboardvideos.html
</control>
</tab>
</section>
<section alias="StartupDashboardSection">
<access>
<deny>translator</deny>
<grant>hello</grant>
<grantBySection>world</grantBySection>
</access>
<areas>
<area>content</area>
</areas>
<tab caption="Get Started">
<access>
<grant>admin</grant>
</access>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/default/startupdashboardintro.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/default/startupdashboardkits.html
<access>
<deny>editor</deny>
<deny>writer</deny>
</access>
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/default/startupdashboardvideos.html
</control>
</tab>
<tab caption="Last Edits">
<control addPanel="true" MaxRecords="30">dashboard/latestEdits.ascx</control>
</tab>
<tab caption="Change Password">
<control addPanel="true">
views/dashboard/changepassword.html
</control>
</tab>
</section>
<section alias="StartupMemberDashboardSection">
<areas>
<area>default</area>
<area>member</area>
</areas>
<tab caption="Get Started">
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/members/membersdashboardintro.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
members/membersearch.ascx
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/members/membersdashboardvideos.html
</control>
</tab>
</section>
</dashBoard>
<?xml version="1.0" encoding="utf-8"?>
<dashBoard>
<section alias="StartupSettingsDashboardSection">
<areas>
<area>settings</area>
</areas>
<tab caption="Get Started">
<control showOnce="true" addPanel="true" panelCaption="hello">
views/dashboard/settings/settingsdashboardintro.html
</control>
<control showOnce="false" addPanel="false" panelCaption="">
views/dashboard/settings/settingsdashboardvideos.html
</control>
</tab>
</section>
<section alias="StartupDeveloperDashboardSection">
<areas>
<area>developer</area>
</areas>
<tab caption="Get Started">
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/developer/developerdashboardintro.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/developer/developerdashboardvideos.html
</control>
</tab>
<tab caption="Examine Management">
<control>dashboard/ExamineManagement.ascx</control>
</tab>
</section>
<section alias="StartupMediaDashboardSection">
<areas>
<area>media</area>
</areas>
<tab caption="Content">
<control showOnce="false" addPanel="false" panelCaption="">
views/dashboard/media/mediafolderbrowser.html
</control>
</tab>
<tab caption="Get Started">
<access>
<grant>admin</grant>
</access>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/media/mediadashboardintro.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/media/desktopmediauploader.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/media/mediadashboardvideos.html
</control>
</tab>
</section>
<section alias="StartupDashboardSection">
<access>
<deny>translator</deny>
<grant>hello</grant>
<grantBySection>world</grantBySection>
</access>
<areas>
<area>content</area>
</areas>
<tab caption="Get Started">
<access>
<grant>admin</grant>
</access>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/default/startupdashboardintro.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/default/startupdashboardkits.html
<access>
<deny>editor</deny>
<deny>writer</deny>
</access>
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/default/startupdashboardvideos.html
</control>
</tab>
<tab caption="Last Edits">
<control addPanel="true" MaxRecords="30">dashboard/latestEdits.ascx</control>
</tab>
<tab caption="Change Password">
<control addPanel="true">
views/dashboard/changepassword.html
</control>
</tab>
</section>
<section alias="StartupMemberDashboardSection">
<areas>
<area>default</area>
<area>member</area>
</areas>
<tab caption="Get Started">
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/members/membersdashboardintro.html
</control>
<control showOnce="true" addPanel="true" panelCaption="">
members/membersearch.ascx
</control>
<control showOnce="true" addPanel="true" panelCaption="">
views/dashboard/members/membersdashboardvideos.html
</control>
</tab>
</section>
</dashBoard>

View File

@@ -1,127 +1,116 @@
using System.Configuration;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core.Configuration.Dashboard;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests.Configurations.DashboardSettings
{
[TestFixture]
public class DashboardSettingsTests
{
[SetUp]
public void Init()
{
var config = new FileInfo(TestHelper.MapPathForTest("~/Configurations/DashboardSettings/web.config"));
var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = config.FullName };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
SettingsSection = configuration.GetSection("umbracoConfiguration/dashBoard") as DashboardSection;
Assert.IsNotNull(SettingsSection);
}
protected IDashboardSection SettingsSection { get; private set; }
[Test]
public void Test_Sections()
{
Assert.AreEqual(5, SettingsSection.Sections.Count());
Assert.AreEqual("StartupSettingsDashboardSection", SettingsSection.Sections.ElementAt(0).Alias);
Assert.AreEqual("StartupDeveloperDashboardSection", SettingsSection.Sections.ElementAt(1).Alias);
Assert.AreEqual("StartupMediaDashboardSection", SettingsSection.Sections.ElementAt(2).Alias);
Assert.AreEqual("StartupDashboardSection", SettingsSection.Sections.ElementAt(3).Alias);
Assert.AreEqual("StartupMemberDashboardSection", SettingsSection.Sections.ElementAt(4).Alias);
}
[Test]
public void Test_Section_Area()
{
Assert.AreEqual("settings", SettingsSection.Sections.ElementAt(0).Areas.First());
Assert.AreEqual("developer", SettingsSection.Sections.ElementAt(1).Areas.First());
Assert.AreEqual("media", SettingsSection.Sections.ElementAt(2).Areas.First());
Assert.AreEqual("content", SettingsSection.Sections.ElementAt(3).Areas.First());
Assert.AreEqual("default", SettingsSection.Sections.ElementAt(4).Areas.First());
Assert.AreEqual("member", SettingsSection.Sections.ElementAt(4).Areas.Last());
}
[Test]
public void Test_Section_Access()
{
Assert.AreEqual(3, SettingsSection.Sections.ElementAt(3).AccessRights.Rules.Count());
Assert.AreEqual("translator", SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(0).Value);
Assert.AreEqual(AccessType.Deny, SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(0).Action);
Assert.AreEqual("hello", SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(1).Value);
Assert.AreEqual(AccessType.Grant, SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(1).Action);
Assert.AreEqual("world", SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(2).Value);
Assert.AreEqual(AccessType.GrantBySection, SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(2).Action);
}
[Test]
public void Test_Section_Tabs()
{
//Element 0 Alias "StartupSettingsDashboardSection"
Assert.AreEqual(2, SettingsSection.Sections.ElementAt(0).Tabs.Count());
//Element 1 Alias "StartupDeveloperDashboardSection"
Assert.AreEqual(1, SettingsSection.Sections.ElementAt(1).Tabs.Count());
//Element 2 Alias "StartupMediaDashboardSection"
Assert.AreEqual(2, SettingsSection.Sections.ElementAt(2).Tabs.Count());
//Element 3 Alias "StartupDashboardSection"
Assert.AreEqual(3, SettingsSection.Sections.ElementAt(3).Tabs.Count());
//Element 4 Alias "StartupMemberDashboardSection"
Assert.AreEqual(1, SettingsSection.Sections.ElementAt(4).Tabs.Count());
}
[Test]
public void Test_Tab()
{
Assert.AreEqual("Get Started", SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Caption);
Assert.AreEqual(2, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.Count());
}
[Test]
public void Test_Tab_Access()
{
Assert.AreEqual(1, SettingsSection.Sections.ElementAt(2).Tabs.ElementAt(1).AccessRights.Rules.Count());
Assert.AreEqual(AccessType.Grant, SettingsSection.Sections.ElementAt(2).Tabs.ElementAt(1).AccessRights.Rules.ElementAt(0).Action);
Assert.AreEqual("admin", SettingsSection.Sections.ElementAt(2).Tabs.ElementAt(1).AccessRights.Rules.ElementAt(0).Value);
}
[Test]
public void Test_Control()
{
Assert.AreEqual(true, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(0).ShowOnce);
Assert.AreEqual(true, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(0).AddPanel);
Assert.AreEqual("hello", SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(0).PanelCaption);
Assert.AreEqual("views/dashboard/settings/settingsdashboardintro.html",
SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(0).ControlPath);
Assert.AreEqual(false, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(1).ShowOnce);
Assert.AreEqual(false, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(1).AddPanel);
Assert.AreEqual("", SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(1).PanelCaption);
Assert.AreEqual("views/dashboard/settings/settingsdashboardvideos.html",
SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(1).ControlPath);
}
[Test]
public void Test_Control_Access()
{
Assert.AreEqual(2, SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.Count());
Assert.AreEqual(AccessType.Deny, SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.ElementAt(0).Action);
Assert.AreEqual("editor", SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.ElementAt(0).Value);
Assert.AreEqual(AccessType.Deny, SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.ElementAt(1).Action);
Assert.AreEqual("writer", SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.ElementAt(1).Value);
}
}
}
using System.Configuration;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core.Configuration.Dashboard;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests.Configurations.DashboardSettings
{
[TestFixture]
public class DashboardSettingsTests
{
[SetUp]
public void Init()
{
var config = new FileInfo(TestHelper.MapPathForTest("~/Configurations/DashboardSettings/web.config"));
var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = config.FullName };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
SettingsSection = configuration.GetSection("umbracoConfiguration/dashBoard") as DashboardSection;
Assert.IsNotNull(SettingsSection);
}
protected IDashboardSection SettingsSection { get; private set; }
[Test]
public void Test_Sections()
{
Assert.AreEqual(5, SettingsSection.Sections.Count());
Assert.AreEqual("StartupSettingsDashboardSection", SettingsSection.Sections.ElementAt(0).Alias);
Assert.AreEqual("StartupDeveloperDashboardSection", SettingsSection.Sections.ElementAt(1).Alias);
Assert.AreEqual("StartupMediaDashboardSection", SettingsSection.Sections.ElementAt(2).Alias);
Assert.AreEqual("StartupDashboardSection", SettingsSection.Sections.ElementAt(3).Alias);
Assert.AreEqual("StartupMemberDashboardSection", SettingsSection.Sections.ElementAt(4).Alias);
}
[Test]
public void Test_Section_Area()
{
Assert.AreEqual("settings", SettingsSection.Sections.ElementAt(0).Areas.First());
Assert.AreEqual("developer", SettingsSection.Sections.ElementAt(1).Areas.First());
Assert.AreEqual("media", SettingsSection.Sections.ElementAt(2).Areas.First());
Assert.AreEqual("content", SettingsSection.Sections.ElementAt(3).Areas.First());
Assert.AreEqual("default", SettingsSection.Sections.ElementAt(4).Areas.First());
Assert.AreEqual("member", SettingsSection.Sections.ElementAt(4).Areas.Last());
}
[Test]
public void Test_Section_Access()
{
Assert.AreEqual(3, SettingsSection.Sections.ElementAt(3).AccessRights.Rules.Count());
Assert.AreEqual("translator", SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(0).Value);
Assert.AreEqual(AccessType.Deny, SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(0).Action);
Assert.AreEqual("hello", SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(1).Value);
Assert.AreEqual(AccessType.Grant, SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(1).Action);
Assert.AreEqual("world", SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(2).Value);
Assert.AreEqual(AccessType.GrantBySection, SettingsSection.Sections.ElementAt(3).AccessRights.Rules.ElementAt(2).Action);
}
[Test]
public void Test_Section_Tabs()
{
Assert.AreEqual(1, SettingsSection.Sections.ElementAt(0).Tabs.Count());
Assert.AreEqual(2, SettingsSection.Sections.ElementAt(1).Tabs.Count());
Assert.AreEqual(3, SettingsSection.Sections.ElementAt(3).Tabs.Count());
}
[Test]
public void Test_Tab()
{
Assert.AreEqual("Get Started", SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Caption);
Assert.AreEqual(2, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.Count());
}
[Test]
public void Test_Tab_Access()
{
Assert.AreEqual(1, SettingsSection.Sections.ElementAt(2).Tabs.ElementAt(1).AccessRights.Rules.Count());
Assert.AreEqual(AccessType.Grant, SettingsSection.Sections.ElementAt(2).Tabs.ElementAt(1).AccessRights.Rules.ElementAt(0).Action);
Assert.AreEqual("admin", SettingsSection.Sections.ElementAt(2).Tabs.ElementAt(1).AccessRights.Rules.ElementAt(0).Value);
}
[Test]
public void Test_Control()
{
Assert.AreEqual(true, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(0).ShowOnce);
Assert.AreEqual(true, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(0).AddPanel);
Assert.AreEqual("hello", SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(0).PanelCaption);
Assert.AreEqual("views/dashboard/settings/settingsdashboardintro.html",
SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(0).ControlPath);
Assert.AreEqual(false, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(1).ShowOnce);
Assert.AreEqual(false, SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(1).AddPanel);
Assert.AreEqual("", SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(1).PanelCaption);
Assert.AreEqual("views/dashboard/settings/settingsdashboardvideos.html",
SettingsSection.Sections.ElementAt(0).Tabs.ElementAt(0).Controls.ElementAt(1).ControlPath);
}
[Test]
public void Test_Control_Access()
{
Assert.AreEqual(2, SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.Count());
Assert.AreEqual(AccessType.Deny, SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.ElementAt(0).Action);
Assert.AreEqual("editor", SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.ElementAt(0).Value);
Assert.AreEqual(AccessType.Deny, SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.ElementAt(1).Action);
Assert.AreEqual("writer", SettingsSection.Sections.ElementAt(3).Tabs.ElementAt(0).Controls.ElementAt(1).AccessRights.Rules.ElementAt(1).Value);
}
}
}

View File

@@ -1,14 +1,14 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="umbracoConfiguration">
<section name="dashBoard" type="Umbraco.Core.Configuration.Dashboard.DashboardSection, Umbraco.Core" requirePermission="false" />
</sectionGroup>
</configSections>
<umbracoConfiguration>
<dashBoard configSource="Dashboard.config" />
</umbracoConfiguration>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="umbracoConfiguration">
<section name="dashBoard" type="Umbraco.Core.Configuration.Dashboard.DashboardSection, Umbraco.Core" requirePermission="false" />
</sectionGroup>
</configSections>
<umbracoConfiguration>
<dashBoard configSource="Dashboard.config" />
</umbracoConfiguration>
</configuration>

View File

@@ -1,25 +1,25 @@
using System;
using System.Configuration;
using System.Linq;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
namespace Umbraco.Tests.Configurations
{
[TestFixture]
public class FileSystemProviderTests
{
[Test]
public void Can_Get_Media_Provider()
{
var config = (FileSystemProvidersSection)ConfigurationManager.GetSection("umbracoConfiguration/FileSystemProviders");
var providerConfig = config.Providers["media"];
Assert.That(providerConfig, Is.Not.Null);
Assert.That(providerConfig.Parameters.AllKeys.Any(), Is.True);
}
}
}
using System;
using System.Configuration;
using System.Linq;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
namespace Umbraco.Tests.Configurations
{
[TestFixture]
public class FileSystemProviderTests
{
[Test]
public void Can_Get_Media_Provider()
{
var config = (FileSystemProvidersSection)ConfigurationManager.GetSection("umbracoConfiguration/FileSystemProviders");
var providerConfig = config.Providers["media"];
Assert.That(providerConfig, Is.Not.Null);
Assert.That(providerConfig.Parameters.AllKeys.Any(), Is.True);
}
}
}

View File

@@ -1,6 +1,5 @@
using System.Web.Mvc;
using System.Web.Mvc;
using System.Web.Routing;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
@@ -9,33 +8,36 @@ using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests.Configurations
{
[TestFixture]
public class GlobalSettingsTests : BaseWebTest
{
private string _root;
public class GlobalSettingsTests : BaseWebTest
{
public override void SetUp()
{
base.SetUp();
_root = SystemDirectories.Root;
}
public override void Initialize()
{
base.Initialize();
SettingsForTests.UmbracoPath = "~/umbraco";
}
public override void TearDown()
{
base.TearDown();
SystemDirectories.Root = _root;
}
public override void TearDown()
{
//ensure this is reset
SystemDirectories.Root = null;
SettingsForTests.UmbracoPath = "~/umbraco";
//reset the app config
base.TearDown();
}
[Test]
public void Is_Debug_Mode()
{
Assert.That(GlobalSettings.DebugMode, Is.EqualTo(true));
Assert.That(Umbraco.Core.Configuration.GlobalSettings.DebugMode, Is.EqualTo(true));
}
[Ignore("fixme - ignored test")]
[Ignore]
[Test]
public void Is_Version_From_Assembly_Correct()
{
Assert.That(UmbracoVersion.SemanticVersion, Is.EqualTo("6.0.0"));
Assert.That(UmbracoVersion.GetSemanticVersion(), Is.EqualTo("6.0.0"));
}
[TestCase("~/umbraco", "/", "umbraco")]
@@ -43,79 +45,75 @@ namespace Umbraco.Tests.Configurations
[TestCase("~/customPath", "/MyVirtualDir/", "custompath")]
[TestCase("~/some-wacky/nestedPath", "/MyVirtualDir", "some-wacky-nestedpath")]
[TestCase("~/some-wacky/nestedPath", "/MyVirtualDir/NestedVDir/", "some-wacky-nestedpath")]
public void Umbraco_Mvc_Area(string path, string rootPath, string outcome)
public void Umbraco_Mvc_Area(string path, string rootPath, string outcome)
{
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
globalSettingsMock.Setup(x => x.Path).Returns(IOHelper.ResolveUrl(path));
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
SettingsForTests.UmbracoPath = path;
SystemDirectories.Root = rootPath;
Assert.AreEqual(outcome, UmbracoConfig.For.GlobalSettings().GetUmbracoMvcArea());
Assert.AreEqual(outcome, Umbraco.Core.Configuration.GlobalSettings.UmbracoMvcArea);
}
[TestCase("/umbraco/umbraco.aspx")]
[TestCase("/umbraco/editContent.aspx")]
[TestCase("/install/default.aspx")]
[TestCase("/install/")]
[TestCase("/install")]
[TestCase("/install/?installStep=asdf")]
[TestCase("/install/test.aspx")]
[TestCase("/config/splashes/booting.aspx")]
public void Is_Reserved_Path_Or_Url(string url)
{
var globalSettings = TestObjects.GetGlobalSettings();
Assert.IsTrue(globalSettings.IsReservedPathOrUrl(url));
}
[TestCase("/umbraco/umbraco.aspx")]
[TestCase("/umbraco/editContent.aspx")]
[TestCase("/install/default.aspx")]
[TestCase("/install/")]
[TestCase("/install")]
[TestCase("/install/?installStep=asdf")]
[TestCase("/install/test.aspx")]
[TestCase("/config/splashes/booting.aspx")]
public void Is_Reserved_Path_Or_Url(string url)
{
Assert.IsTrue(Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url));
}
[TestCase("/base/somebasehandler")]
[TestCase("/")]
[TestCase("/home.aspx")]
[TestCase("/umbraco-test")]
[TestCase("/install-test")]
[TestCase("/install.aspx")]
public void Is_Not_Reserved_Path_Or_Url(string url)
{
var globalSettings = TestObjects.GetGlobalSettings();
Assert.IsFalse(globalSettings.IsReservedPathOrUrl(url));
}
[TestCase("/umbraco_client/Tree/treeIcons.css")]
[TestCase("/umbraco_client/Tree/Themes/umbraco/style.css")]
[TestCase("/umbraco_client/scrollingmenu/style.css")]
[TestCase("/base/somebasehandler")]
[TestCase("/")]
[TestCase("/home.aspx")]
[TestCase("/umbraco-test")]
[TestCase("/install-test")]
[TestCase("/install.aspx")]
public void Is_Not_Reserved_Path_Or_Url(string url)
{
Assert.IsFalse(Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url));
}
[TestCase("/Do/Not/match", false)]
[TestCase("/Umbraco/RenderMvcs", false)]
[TestCase("/Umbraco/RenderMvc", true)]
[TestCase("/Umbraco/RenderMvc/Index", true)]
[TestCase("/Umbraco/RenderMvc/Index/1234", true)]
[TestCase("/Umbraco/RenderMvc/Index/1234/9876", false)]
[TestCase("/api", true)]
[TestCase("/api/WebApiTest", true)]
[TestCase("/api/WebApiTest/1234", true)]
[TestCase("/api/WebApiTest/Index/1234", false)]
public void Is_Reserved_By_Route(string url, bool shouldMatch)
{
//reset the app config, we only want to test routes not the hard coded paths
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
globalSettingsMock.Setup(x => x.ReservedPaths).Returns("");
globalSettingsMock.Setup(x => x.ReservedUrls).Returns("");
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
[TestCase("/Do/Not/match", false)]
[TestCase("/Umbraco/RenderMvcs", false)]
[TestCase("/Umbraco/RenderMvc", true)]
[TestCase("/Umbraco/RenderMvc/Index", true)]
[TestCase("/Umbraco/RenderMvc/Index/1234", true)]
[TestCase("/Umbraco/RenderMvc/Index/1234/9876", false)]
[TestCase("/api", true)]
[TestCase("/api/WebApiTest", true)]
[TestCase("/api/WebApiTest/1234", true)]
[TestCase("/api/WebApiTest/Index/1234", false)]
public void Is_Reserved_By_Route(string url, bool shouldMatch)
{
//reset the app config, we only want to test routes not the hard coded paths
Umbraco.Core.Configuration.GlobalSettings.ReservedPaths = "";
Umbraco.Core.Configuration.GlobalSettings.ReservedUrls = "";
var routes = new RouteCollection();
var routes = new RouteCollection();
routes.MapRoute(
"Umbraco_default",
"Umbraco/RenderMvc/{action}/{id}",
new { controller = "RenderMvc", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
"WebAPI",
"api/{controller}/{id}",
new { controller = "WebApiTestController", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
"Umbraco_default",
"Umbraco/RenderMvc/{action}/{id}",
new { controller = "RenderMvc", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
"WebAPI",
"api/{controller}/{id}",
new { controller = "WebApiTestController", action = "Index", id = UrlParameter.Optional });
var context = new FakeHttpContextFactory(url);
var context = new FakeHttpContextFactory(url);
Assert.AreEqual(
shouldMatch,
globalSettingsMock.Object.IsReservedPathOrUrl(url, context.HttpContext, routes));
}
}
}
Assert.AreEqual(
shouldMatch,
Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url, context.HttpContext, routes));
}
}
}

View File

@@ -0,0 +1,32 @@
using System.Configuration;
using NUnit.Framework;
using Umbraco.Core.Configuration.InfrastructureSettings;
namespace Umbraco.Tests.Configurations
{
[TestFixture]
public class RepositorySettingsTests
{
[Test]
public void Can_Get_Repository_From_Config()
{
Infrastructure infrastructure = Infrastructure.Instance;
Repositories repositories = infrastructure.Repositories;
Repository repository = repositories.Repository["IContentRepository"];
Assert.That(repository, Is.Not.Null);
Assert.AreEqual(repository.InterfaceShortTypeName, "IContentRepository");
Assert.AreEqual(repository.RepositoryFullTypeName, "Umbraco.Core.Persistence.Repositories.ContentRepository, Umbraco.Core");
Assert.AreEqual(repository.CacheProviderFullTypeName, "Umbraco.Core.Persistence.Caching.RuntimeCacheProvider, Umbraco.Core");
}
[Test]
public void Can_Get_PublishingStrategy_From_Config()
{
Infrastructure infrastructure = Infrastructure.Instance;
PublishingProvider strategy = infrastructure.PublishingStrategy;
Assert.That(strategy.Type, Is.EqualTo("Umbraco.Web.Publishing.PublishingStrategy, Umbraco.Web"));
}
}
}

View File

@@ -1,45 +1,51 @@
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ContentElementDefaultTests : ContentElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void DisableHtmlEmail()
{
Assert.IsTrue(SettingsSection.Content.DisableHtmlEmail == false);
}
[Test]
public override void Can_Set_Multiple()
{
Assert.IsTrue(SettingsSection.Content.Error404Collection.Count() == 1);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(0).Culture == null);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(0).ContentId == 1);
}
[Test]
public override void ImageAutoFillProperties()
{
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.Count() == 1);
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).Alias == "umbracoFile");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).WidthFieldAlias == "umbracoWidth");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).HeightFieldAlias == "umbracoHeight");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).LengthFieldAlias == "umbracoBytes");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).ExtensionFieldAlias == "umbracoExtension");
}
[Test]
public override void XmlContentCheckForDiskChanges()
{
Assert.IsTrue(SettingsSection.Content.XmlContentCheckForDiskChanges == false);
}
}
}
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ContentElementDefaultTests : ContentElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void DisableHtmlEmail()
{
Assert.IsTrue(SettingsSection.Content.DisableHtmlEmail == false);
}
[Test]
public override void Can_Set_Multiple()
{
Assert.IsTrue(SettingsSection.Content.Error404Collection.Count() == 1);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(0).Culture == null);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(0).ContentId == 1);
}
[Test]
public override void ImageAutoFillProperties()
{
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.Count() == 1);
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).Alias == "umbracoFile");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).WidthFieldAlias == "umbracoWidth");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).HeightFieldAlias == "umbracoHeight");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).LengthFieldAlias == "umbracoBytes");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).ExtensionFieldAlias == "umbracoExtension");
}
[Test]
public override void TidyCharEncoding()
{
Assert.IsTrue(SettingsSection.Content.TidyCharEncoding == "UTF8");
}
[Test]
public override void XmlContentCheckForDiskChanges()
{
Assert.IsTrue(SettingsSection.Content.XmlContentCheckForDiskChanges == false);
}
}
}

View File

@@ -1,198 +1,216 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Macros;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ContentElementTests : UmbracoSettingsTests
{
[Test]
public void EmailAddress()
{
Assert.AreEqual(SettingsSection.Content.NotificationEmailAddress, "robot@umbraco.dk");
}
[Test]
public virtual void DisableHtmlEmail()
{
Assert.IsTrue(SettingsSection.Content.DisableHtmlEmail);
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ContentElementTests : UmbracoSettingsTests
{
[Test]
public void EmailAddress()
{
Assert.IsTrue(SettingsSection.Content.NotificationEmailAddress == "robot@umbraco.dk");
}
[Test]
public virtual void DisableHtmlEmail()
{
Assert.IsTrue(SettingsSection.Content.DisableHtmlEmail == true);
}
[Test]
public virtual void Can_Set_Multiple()
{
Assert.IsTrue(SettingsSection.Content.Error404Collection.Count() == 3);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(0).Culture == "default");
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(0).ContentId == 1047);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(0).HasContentId);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(0).HasContentKey);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(1).Culture == "en-US");
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(1).ContentXPath == "$site/error [@name = 'error']");
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(1).HasContentId);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(1).HasContentKey);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(2).Culture == "en-UK");
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(2).ContentKey == new Guid("8560867F-B88F-4C74-A9A4-679D8E5B3BFC"));
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(2).HasContentKey);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(2).HasContentId);
}
[Test]
public void ScriptFolderPath()
{
Assert.IsTrue(SettingsSection.Content.ScriptFolderPath == "/scripts");
}
[Test]
public void ScriptFileTypes()
{
Assert.IsTrue(SettingsSection.Content.ScriptFileTypes.All(x => "js,xml".Split(',').Contains(x)));
}
[Test]
public void DisableScriptEditor()
{
Assert.IsTrue(SettingsSection.Content.ScriptEditorDisable == false);
}
[Test]
public void ImageFileTypes()
{
Assert.IsTrue(SettingsSection.Content.ImageFileTypes.All(x => "jpeg,jpg,gif,bmp,png,tiff,tif".Split(',').Contains(x)));
}
[Test]
public void AllowedAttributes()
{
Assert.IsTrue(SettingsSection.Content.ImageTagAllowedAttributes.All(x => "src,alt,border,class,style,align,id,name,onclick,usemap".Split(',').Contains(x)));
}
[Test]
public virtual void ImageAutoFillProperties()
{
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.Count() == 2);
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).Alias == "umbracoFile");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).WidthFieldAlias == "umbracoWidth");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).HeightFieldAlias == "umbracoHeight");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).LengthFieldAlias == "umbracoBytes");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).ExtensionFieldAlias == "umbracoExtension");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).Alias == "umbracoFile2");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).WidthFieldAlias == "umbracoWidth2");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).HeightFieldAlias == "umbracoHeight2");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).LengthFieldAlias == "umbracoBytes2");
Assert.IsTrue(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).ExtensionFieldAlias == "umbracoExtension2");
}
[Test]
public void UploadAllowDirectories()
{
Assert.IsTrue(SettingsSection.Content.UploadAllowDirectories == true);
}
[Test]
public void DefaultDocumentTypeProperty()
{
Assert.IsTrue(SettingsSection.Content.DefaultDocumentTypeProperty == "Textstring");
}
[Test]
public void GlobalPreviewStorageEnabled()
{
Assert.IsTrue(SettingsSection.Content.GlobalPreviewStorageEnabled == false);
}
[Test]
public void CloneXmlContent()
{
Assert.IsTrue(SettingsSection.Content.CloneXmlContent == true);
}
[Test]
public void EnsureUniqueNaming()
{
Assert.IsTrue(SettingsSection.Content.EnsureUniqueNaming == true);
}
[Test]
public void TidyEditorContent()
{
Assert.IsTrue(SettingsSection.Content.TidyEditorContent == false);
}
[Test]
public virtual void TidyCharEncoding()
{
Assert.IsTrue(SettingsSection.Content.TidyCharEncoding == "Raw");
}
[Test]
public void UseLegacyXmlSchema()
{
Assert.IsTrue(SettingsSection.Content.UseLegacyXmlSchema == false);
}
[Test]
public void ForceSafeAliases()
{
Assert.IsTrue(SettingsSection.Content.ForceSafeAliases == true);
}
[Test]
public void XmlCacheEnabled()
{
Assert.IsTrue(SettingsSection.Content.XmlCacheEnabled == true);
}
[Test]
public void ContinouslyUpdateXmlDiskCache()
{
Assert.IsTrue(SettingsSection.Content.ContinouslyUpdateXmlDiskCache == true);
}
[Test]
public virtual void XmlContentCheckForDiskChanges()
{
Assert.IsTrue(SettingsSection.Content.XmlContentCheckForDiskChanges == true);
}
[Test]
public void EnableSplashWhileLoading()
{
Assert.IsTrue(SettingsSection.Content.EnableSplashWhileLoading == false);
}
[Test]
public void PropertyContextHelpOption()
{
Assert.IsTrue(SettingsSection.Content.PropertyContextHelpOption == "text");
}
[Test]
public void PreviewBadge()
{
Assert.IsTrue(SettingsSection.Content.PreviewBadge == @"<a id=""umbracoPreviewBadge"" style=""z-index:99999; position: absolute; top: 0; right: 0; border: 0; width: 149px; height: 149px; background: url('{1}/preview/previewModeBadge.png') no-repeat;"" href=""{0}/endPreview.aspx?redir={2}""><span style=""display:none;"">In Preview Mode - click to end</span></a>");
}
[Test]
public void UmbracoLibraryCacheDuration()
{
Assert.IsTrue(SettingsSection.Content.UmbracoLibraryCacheDuration == 1800);
}
[Test]
public void ResolveUrlsFromTextString()
{
Assert.IsFalse(SettingsSection.Content.ResolveUrlsFromTextString);
}
[Test]
public void MacroErrors()
{
Assert.IsTrue(SettingsSection.Content.MacroErrorBehaviour == MacroErrorBehaviour.Inline);
}
[Test]
public void DisallowedUploadFiles()
{
Assert.IsTrue(SettingsSection.Content.DisallowedUploadFiles.All(x => "ashx,aspx,ascx,config,cshtml,vbhtml,asmx,air,axd".Split(',').Contains(x)));
}
[Test]
public virtual void Can_Set_Multiple()
{
Assert.AreEqual(SettingsSection.Content.Error404Collection.Count(), 3);
Assert.AreEqual(SettingsSection.Content.Error404Collection.ElementAt(0).Culture, "default");
Assert.AreEqual(SettingsSection.Content.Error404Collection.ElementAt(0).ContentId, 1047);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(0).HasContentId);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(0).HasContentKey);
Assert.AreEqual(SettingsSection.Content.Error404Collection.ElementAt(1).Culture, "en-US");
Assert.AreEqual(SettingsSection.Content.Error404Collection.ElementAt(1).ContentXPath, "$site/error [@name = 'error']");
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(1).HasContentId);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(1).HasContentKey);
Assert.AreEqual(SettingsSection.Content.Error404Collection.ElementAt(2).Culture, "en-UK");
Assert.AreEqual(SettingsSection.Content.Error404Collection.ElementAt(2).ContentKey, new Guid("8560867F-B88F-4C74-A9A4-679D8E5B3BFC"));
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(2).HasContentKey);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(2).HasContentId);
}
[Test]
public void ScriptFolderPath()
{
Assert.AreEqual(SettingsSection.Content.ScriptFolderPath, "/scripts");
}
[Test]
public void ScriptFileTypes()
{
Assert.IsTrue(SettingsSection.Content.ScriptFileTypes.All(x => "js,xml".Split(',').Contains(x)));
}
[Test]
public void DisableScriptEditor()
{
Assert.AreEqual(SettingsSection.Content.ScriptEditorDisable, false);
}
[Test]
public void ImageFileTypes()
{
Assert.IsTrue(SettingsSection.Content.ImageFileTypes.All(x => "jpeg,jpg,gif,bmp,png,tiff,tif".Split(',').Contains(x)));
}
[Test]
public void AllowedAttributes()
{
Assert.IsTrue(SettingsSection.Content.ImageTagAllowedAttributes.All(x => "src,alt,border,class,style,align,id,name,onclick,usemap".Split(',').Contains(x)));
}
[Test]
public virtual void ImageAutoFillProperties()
{
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.Count(), 2);
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).Alias, "umbracoFile");
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).WidthFieldAlias, "umbracoWidth");
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).HeightFieldAlias, "umbracoHeight");
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).LengthFieldAlias, "umbracoBytes");
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).ExtensionFieldAlias, "umbracoExtension");
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).Alias, "umbracoFile2");
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).WidthFieldAlias, "umbracoWidth2");
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).HeightFieldAlias, "umbracoHeight2");
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).LengthFieldAlias, "umbracoBytes2");
Assert.AreEqual(SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).ExtensionFieldAlias, "umbracoExtension2");
}
[Test]
public void UploadAllowDirectories()
{
Assert.IsTrue(SettingsSection.Content.UploadAllowDirectories);
}
[Test]
public void DefaultDocumentTypeProperty()
{
Assert.AreEqual(SettingsSection.Content.DefaultDocumentTypeProperty, "Textstring");
}
[Test]
public void GlobalPreviewStorageEnabled()
{
Assert.IsFalse(SettingsSection.Content.GlobalPreviewStorageEnabled);
}
[Test]
public void CloneXmlContent()
{
Assert.IsTrue(SettingsSection.Content.CloneXmlContent);
}
[Test]
public void EnsureUniqueNaming()
{
Assert.IsTrue(SettingsSection.Content.EnsureUniqueNaming);
}
[Test]
public void ForceSafeAliases()
{
Assert.IsTrue(SettingsSection.Content.ForceSafeAliases);
}
[Test]
public void XmlCacheEnabled()
{
Assert.IsTrue(SettingsSection.Content.XmlCacheEnabled);
}
[Test]
public void ContinouslyUpdateXmlDiskCache()
{
Assert.IsTrue(SettingsSection.Content.ContinouslyUpdateXmlDiskCache);
}
[Test]
public virtual void XmlContentCheckForDiskChanges()
{
Assert.IsTrue(SettingsSection.Content.XmlContentCheckForDiskChanges);
}
[Test]
public void EnableSplashWhileLoading()
{
Assert.IsFalse(SettingsSection.Content.EnableSplashWhileLoading);
}
[Test]
public void PropertyContextHelpOption()
{
Assert.AreEqual(SettingsSection.Content.PropertyContextHelpOption, "text");
}
[Test]
public void PreviewBadge()
{
Assert.AreEqual(SettingsSection.Content.PreviewBadge, @"<a id=""umbracoPreviewBadge"" style=""z-index:99999; position: absolute; top: 0; right: 0; border: 0; width: 149px; height: 149px; background: url('{0}/assets/img/preview-mode-badge.png') no-repeat;"" href=""#"" OnClick=""javascript:window.top.location.href = '{0}/endPreview.aspx?redir={1}'""><span style=""display:none;"">In Preview Mode - click to end</span></a>");
}
[Test]
public void ResolveUrlsFromTextString()
{
Assert.IsFalse(SettingsSection.Content.ResolveUrlsFromTextString);
}
[Test]
public void MacroErrors()
{
Assert.AreEqual(SettingsSection.Content.MacroErrorBehaviour, MacroErrorBehaviour.Inline);
}
[Test]
public void DisallowedUploadFiles()
{
Assert.IsTrue(SettingsSection.Content.DisallowedUploadFiles.All(x => "ashx,aspx,ascx,config,cshtml,vbhtml,asmx,air,axd".Split(',').Contains(x)));
}
[Test]
public void AllowedUploadFiles()
{
Assert.IsTrue(SettingsSection.Content.AllowedUploadFiles.All(x => "jpg,gif,png".Split(',').Contains(x)));
}
[Test]
[TestCase("png", true)]
[TestCase("jpg", true)]
[Test]
public void AllowedUploadFiles()
{
Assert.IsTrue(SettingsSection.Content.AllowedUploadFiles.All(x => "jpg,gif,png".Split(',').Contains(x)));
}
[Test]
[TestCase("png", true)]
[TestCase("jpg", true)]
[TestCase("gif", true)]
// TODO: Why does it flip to TestingDefaults=true for these two tests on AppVeyor. WHY?
//[TestCase("bmp", false)]
//[TestCase("php", false)]
[TestCase("ashx", false)]
[TestCase("config", false)]
public void IsFileAllowedForUpload_WithWhitelist(string extension, bool expected)
// TODO: Why does it flip to TestingDefaults=true for these two tests on AppVeyor. WHY?
//[TestCase("bmp", false)]
//[TestCase("php", false)]
[TestCase("ashx", false)]
[TestCase("config", false)]
public void IsFileAllowedForUpload_WithWhitelist(string extension, bool expected)
{
// Make really sure that defaults are NOT used
// Make really sure that defaults are NOT used
TestingDefaults = false;
Debug.WriteLine("Extension being tested", extension);
Debug.WriteLine("AllowedUploadFiles: {0}", SettingsSection.Content.AllowedUploadFiles);
Debug.WriteLine("DisallowedUploadFiles: {0}", SettingsSection.Content.DisallowedUploadFiles);
var allowedContainsExtension = SettingsSection.Content.AllowedUploadFiles.Any(x => x.InvariantEquals(extension));
var disallowedContainsExtension = SettingsSection.Content.DisallowedUploadFiles.Any(x => x.InvariantEquals(extension));
Debug.WriteLine("AllowedContainsExtension: {0}", allowedContainsExtension);
Debug.WriteLine("DisallowedContainsExtension: {0}", disallowedContainsExtension);
Assert.AreEqual(SettingsSection.Content.IsFileAllowedForUpload(extension), expected);
}
}
}
Debug.WriteLine("Extension being tested", extension);
Debug.WriteLine("AllowedUploadFiles: {0}", SettingsSection.Content.AllowedUploadFiles);
Debug.WriteLine("DisallowedUploadFiles: {0}", SettingsSection.Content.DisallowedUploadFiles);
var allowedContainsExtension = SettingsSection.Content.AllowedUploadFiles.Any(x => x.InvariantEquals(extension));
var disallowedContainsExtension = SettingsSection.Content.DisallowedUploadFiles.Any(x => x.InvariantEquals(extension));
Debug.WriteLine("AllowedContainsExtension: {0}", allowedContainsExtension);
Debug.WriteLine("DisallowedContainsExtension: {0}", disallowedContainsExtension);
Assert.AreEqual(SettingsSection.Content.IsFileAllowedForUpload(extension), expected);
}
}
}

View File

@@ -0,0 +1,13 @@
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class DeveloperElementDefaultTests : DeveloperElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}

View File

@@ -0,0 +1,17 @@
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class DeveloperElementTests : UmbracoSettingsTests
{
[Test]
public void AppCodeFileExtensions()
{
Assert.IsTrue(SettingsSection.Developer.AppCodeFileExtensions.Count() == 2);
Assert.IsTrue(SettingsSection.Developer.AppCodeFileExtensions.All(
x => "cs,vb".Split(',').Contains(x.Extension)));
}
}
}

View File

@@ -0,0 +1,27 @@
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class DistributedCallElementDefaultTests : DistributedCallElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void Enabled()
{
Assert.IsTrue(SettingsSection.DistributedCall.Enabled == false);
}
[Test]
public override void Servers()
{
Assert.IsTrue(SettingsSection.DistributedCall.Servers.Count() == 0);
}
}
}

View File

@@ -0,0 +1,32 @@
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class DistributedCallElementTests : UmbracoSettingsTests
{
[Test]
public virtual void Enabled()
{
Assert.IsTrue(SettingsSection.DistributedCall.Enabled == true);
}
[Test]
public void UserId()
{
Assert.IsTrue(SettingsSection.DistributedCall.UserId == 0);
}
[Test]
public virtual void Servers()
{
Assert.IsTrue(SettingsSection.DistributedCall.Servers.Count() == 2);
Assert.IsTrue(SettingsSection.DistributedCall.Servers.ElementAt(0).ServerAddress == "127.0.0.1");
Assert.IsTrue(SettingsSection.DistributedCall.Servers.ElementAt(1).ServerAddress == "127.0.0.2");
Assert.IsTrue(SettingsSection.DistributedCall.Servers.ElementAt(1).ForceProtocol == "https");
Assert.IsTrue(SettingsSection.DistributedCall.Servers.ElementAt(1).ForcePortnumber == "443");
}
}
}

View File

@@ -1,30 +1,50 @@
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class LoggingElementDefaultTests : LoggingElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void DisabledLogTypes()
{
Assert.IsTrue(SettingsSection.Logging.DisabledLogTypes.Any() == false);
}
[Test]
public override void CleaningMiliseconds()
{
Assert.IsTrue(SettingsSection.Logging.CleaningMiliseconds == -1);
}
[Test]
public override void MaxLogAge()
{
Assert.IsTrue(SettingsSection.Logging.MaxLogAge == -1);
}
}
}
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class LoggingElementDefaultTests : LoggingElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void ExternalLoggerConfigured()
{
Assert.IsTrue(SettingsSection.Logging.ExternalLoggerIsConfigured == false);
}
[Test]
public override void ExternalLogger_Assembly()
{
Assert.IsTrue(SettingsSection.Logging.ExternalLoggerIsConfigured == false);
}
[Test]
public override void ExternalLogger_LogAuditTrail()
{
Assert.IsTrue(SettingsSection.Logging.ExternalLoggerIsConfigured == false);
}
[Test]
public override void ExternalLogger_Type()
{
Assert.IsTrue(SettingsSection.Logging.ExternalLoggerIsConfigured == false);
}
[Test]
public override void DisabledLogTypes()
{
Assert.IsTrue(SettingsSection.Logging.DisabledLogTypes.Count() == 0);
}
[Test]
public override void CleaningMiliseconds()
{
Assert.IsTrue(SettingsSection.Logging.CleaningMiliseconds == -1);
}
[Test]
public override void MaxLogAge()
{
Assert.IsTrue(SettingsSection.Logging.MaxLogAge == -1);
}
}
}

View File

@@ -1,43 +1,67 @@
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class LoggingElementTests : UmbracoSettingsTests
{
[Test]
public void EnableLogging()
{
Assert.IsTrue(SettingsSection.Logging.EnableLogging == true);
}
[Test]
public virtual void DisabledLogTypes()
{
Assert.IsTrue(SettingsSection.Logging.DisabledLogTypes.Count() == 2);
Assert.IsTrue(SettingsSection.Logging.DisabledLogTypes.ElementAt(0).LogTypeAlias == "[alias-of-log-type-in-lowercase]");
Assert.IsTrue(SettingsSection.Logging.DisabledLogTypes.ElementAt(1).LogTypeAlias == "anotherlogalias");
}
[Test]
public void AutoCleanLogs()
{
Assert.IsTrue(SettingsSection.Logging.AutoCleanLogs == false);
}
[Test]
public virtual void CleaningMiliseconds()
{
Assert.IsTrue(SettingsSection.Logging.CleaningMiliseconds == 86400);
}
[Test]
public virtual void MaxLogAge()
{
Assert.IsTrue(SettingsSection.Logging.MaxLogAge == 1440);
}
}
}
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class LoggingElementTests : UmbracoSettingsTests
{
[Test]
public virtual void ExternalLoggerConfigured()
{
Assert.IsTrue(SettingsSection.Logging.ExternalLoggerIsConfigured == true);
}
[Test]
public void EnableLogging()
{
Assert.IsTrue(SettingsSection.Logging.EnableLogging == true);
}
[Test]
public void EnableAsyncLogging()
{
Assert.IsTrue(SettingsSection.Logging.EnableAsyncLogging == true);
}
[Test]
public virtual void DisabledLogTypes()
{
Assert.IsTrue(SettingsSection.Logging.DisabledLogTypes.Count() == 2);
Assert.IsTrue(SettingsSection.Logging.DisabledLogTypes.ElementAt(0).LogTypeAlias == "[alias-of-log-type-in-lowercase]");
Assert.IsTrue(SettingsSection.Logging.DisabledLogTypes.ElementAt(1).LogTypeAlias == "anotherlogalias");
}
[Test]
public virtual void ExternalLogger_Assembly()
{
Assert.IsTrue(SettingsSection.Logging.ExternalLoggerAssembly == "~/bin/assemblyFileName.dll");
}
[Test]
public virtual void ExternalLogger_Type()
{
Assert.IsTrue(SettingsSection.Logging.ExternalLoggerType == "fully.qualified.namespace.and.type");
}
[Test]
public virtual void ExternalLogger_LogAuditTrail()
{
Assert.IsTrue(SettingsSection.Logging.ExternalLoggerEnableAuditTrail == false);
}
[Test]
public void AutoCleanLogs()
{
Assert.IsTrue(SettingsSection.Logging.AutoCleanLogs == false);
}
[Test]
public virtual void CleaningMiliseconds()
{
Assert.IsTrue(SettingsSection.Logging.CleaningMiliseconds == 86400);
}
[Test]
public virtual void MaxLogAge()
{
Assert.IsTrue(SettingsSection.Logging.MaxLogAge == 1440);
}
}
}

View File

@@ -1,14 +1,14 @@
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ProvidersElementDefaultTests : ProvidersElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ProvidersElementDefaultTests : ProvidersElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}

View File

@@ -1,15 +1,15 @@
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ProvidersElementTests : UmbracoSettingsTests
{
[Test]
public void Users()
{
Assert.IsTrue(SettingsSection.Providers.DefaultBackOfficeUserProvider == "UsersMembershipProvider");
}
}
}
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ProvidersElementTests : UmbracoSettingsTests
{
[Test]
public void Users()
{
Assert.IsTrue(SettingsSection.Providers.DefaultBackOfficeUserProvider == "UsersMembershipProvider");
}
}
}

View File

@@ -1,13 +1,13 @@
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class RequestHandlerElementDefaultTests : RequestHandlerElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class RequestHandlerElementDefaultTests : RequestHandlerElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}

View File

@@ -1,44 +1,44 @@
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class RequestHandlerElementTests : UmbracoSettingsTests
{
[Test]
public void UseDomainPrefixes()
{
Assert.IsTrue(SettingsSection.RequestHandler.UseDomainPrefixes == false);
}
[Test]
public void AddTrailingSlash()
{
Assert.IsTrue(SettingsSection.RequestHandler.AddTrailingSlash == true);
}
[Test]
public void RemoveDoubleDashes()
{
Assert.IsTrue(SettingsSection.RequestHandler.RemoveDoubleDashes == true);
}
[Test]
public void CharCollection()
{
var chars = @" ,"",',%,.,;,/,\,:,#,+,*,&,?,æ,ø,å,ä,ö,ü,ß,Ä,Ö,|,<,>";
var items = chars.Split(',');
Assert.AreEqual(items.Length, SettingsSection.RequestHandler.CharCollection.Count());
Assert.IsTrue(SettingsSection.RequestHandler.CharCollection
.All(x => items.Contains(x.Char)));
var vals = @"-,plus,star,ae,oe,aa,ae,oe,ue,ss,ae,oe,-";
var splitVals = vals.Split(',');
Assert.AreEqual(splitVals.Length, SettingsSection.RequestHandler.CharCollection.Count(x => x.Replacement.IsNullOrWhiteSpace() == false));
Assert.IsTrue(SettingsSection.RequestHandler.CharCollection
.All(x => string.IsNullOrEmpty(x.Replacement) || vals.Split(',').Contains(x.Replacement)));
}
}
}
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class RequestHandlerElementTests : UmbracoSettingsTests
{
[Test]
public void UseDomainPrefixes()
{
Assert.IsTrue(SettingsSection.RequestHandler.UseDomainPrefixes == false);
}
[Test]
public void AddTrailingSlash()
{
Assert.IsTrue(SettingsSection.RequestHandler.AddTrailingSlash == true);
}
[Test]
public void RemoveDoubleDashes()
{
Assert.IsTrue(SettingsSection.RequestHandler.RemoveDoubleDashes == true);
}
[Test]
public void CharCollection()
{
var chars = @" ,"",',%,.,;,/,\,:,#,+,*,&,?,æ,ø,å,ä,ö,ü,ß,Ä,Ö,|,<,>";
var items = chars.Split(',');
Assert.AreEqual(items.Length, SettingsSection.RequestHandler.CharCollection.Count());
Assert.IsTrue(SettingsSection.RequestHandler.CharCollection
.All(x => items.Contains(x.Char)));
var vals = @"-,plus,star,ae,oe,aa,ae,oe,ue,ss,ae,oe,-";
var splitVals = vals.Split(',');
Assert.AreEqual(splitVals.Length, SettingsSection.RequestHandler.CharCollection.Count(x => x.Replacement.IsNullOrWhiteSpace() == false));
Assert.IsTrue(SettingsSection.RequestHandler.CharCollection
.All(x => string.IsNullOrEmpty(x.Replacement) || vals.Split(',').Contains(x.Replacement)));
}
}
}

View File

@@ -1,20 +1,20 @@
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ScheduledTasksElementDefaultTests : ScheduledTasksElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void Tasks()
{
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.Any() == false);
}
}
}
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ScheduledTasksElementDefaultTests : ScheduledTasksElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void Tasks()
{
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.Count() == 0);
}
}
}

View File

@@ -1,24 +1,24 @@
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ScheduledTasksElementTests : UmbracoSettingsTests
{
[Test]
public virtual void Tasks()
{
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.Count() == 2);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(0).Alias == "test60");
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(0).Log == true);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(0).Interval == 60);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(0).Url == "http://localhost/umbraco/test.aspx");
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(1).Alias == "testtest");
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(1).Log == false);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(1).Interval == 61);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(1).Url == "http://localhost/umbraco/test1.aspx");
}
}
}
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ScheduledTasksElementTests : UmbracoSettingsTests
{
[Test]
public virtual void Tasks()
{
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.Count() == 2);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(0).Alias == "test60");
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(0).Log == true);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(0).Interval == 60);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(0).Url == "http://localhost/umbraco/test.aspx");
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(1).Alias == "testtest");
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(1).Log == false);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(1).Interval == 61);
Assert.IsTrue(SettingsSection.ScheduledTasks.Tasks.ElementAt(1).Url == "http://localhost/umbraco/test1.aspx");
}
}
}

View File

@@ -0,0 +1,21 @@
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ScriptingElementDefaultTests : ScriptingElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void DataTypeModelStaticMappings()
{
Assert.AreEqual(0, SettingsSection.Scripting.DataTypeModelStaticMappings.Count());
}
}
}

View File

@@ -0,0 +1,45 @@
using System;
using System.Linq;
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ScriptingElementTests : UmbracoSettingsTests
{
[Test]
public void NotDynamicXmlDocumentElements()
{
Assert.IsTrue(SettingsSection.Scripting.NotDynamicXmlDocumentElements
.All(x => "p,div,ul,span".Split(',').Contains(x.Element)));
}
[Test]
public virtual void DataTypeModelStaticMappings()
{
var mappings = SettingsSection.Scripting.DataTypeModelStaticMappings.ToArray();
Assert.IsTrue(mappings[0].DataTypeGuid == Guid.Parse("A3DB4034-BCB0-4E69-B3EE-DD4E6ECA74C2"));
Assert.IsTrue(mappings[0].MappingName == "MyName.1");
Assert.IsTrue(mappings[1].NodeTypeAlias == "textPage2");
Assert.IsTrue(mappings[1].PropertyTypeAlias == "propertyAlias2");
Assert.IsTrue(mappings[1].MappingName == "MyName.2");
Assert.IsTrue(mappings[2].DataTypeGuid == Guid.Parse("BD14E709-45BE-431C-B228-6255CDEDFCD5"));
Assert.IsTrue(mappings[2].NodeTypeAlias == "textPage3");
Assert.IsTrue(mappings[2].PropertyTypeAlias == "propertyAlias3");
Assert.IsTrue(mappings[2].MappingName == "MyName.3");
Assert.IsTrue(mappings[3].DataTypeGuid == Guid.Parse("FCE8187E-0366-4833-953A-E5ECA11AA23A"));
Assert.IsTrue(mappings[3].NodeTypeAlias == "textPage4");
Assert.IsTrue(mappings[3].MappingName == "MyName.4");
Assert.IsTrue(mappings[4].DataTypeGuid == Guid.Parse("9139315A-6681-4C45-B89F-BE48D30F9AB9"));
Assert.IsTrue(mappings[4].PropertyTypeAlias == "propertyAlias5");
Assert.IsTrue(mappings[4].MappingName == "MyName.5");
Assert.IsTrue(mappings[5].PropertyTypeAlias == "propertyAlias6");
Assert.IsTrue(mappings[5].MappingName == "MyName.6");
}
}
}

View File

@@ -1,13 +1,13 @@
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class SecurityElementDefaultTests : SecurityElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class SecurityElementDefaultTests : SecurityElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}

View File

@@ -1,39 +1,39 @@
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class SecurityElementTests : UmbracoSettingsTests
{
[Test]
public void KeepUserLoggedIn()
{
Assert.IsTrue(SettingsSection.Security.KeepUserLoggedIn == true);
}
[Test]
public void HideDisabledUsersInBackoffice()
{
Assert.IsTrue(SettingsSection.Security.HideDisabledUsersInBackoffice == false);
}
[Test]
public void AllowPasswordReset()
{
Assert.IsTrue(SettingsSection.Security.AllowPasswordReset == true);
}
[Test]
public void AuthCookieDomain()
{
Assert.IsTrue(SettingsSection.Security.AuthCookieDomain == null);
}
[Test]
public void AuthCookieName()
{
Assert.IsTrue(SettingsSection.Security.AuthCookieName == "UMB_UCONTEXT");
}
}
}
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class SecurityElementTests : UmbracoSettingsTests
{
[Test]
public void KeepUserLoggedIn()
{
Assert.IsTrue(SettingsSection.Security.KeepUserLoggedIn == true);
}
[Test]
public void HideDisabledUsersInBackoffice()
{
Assert.IsTrue(SettingsSection.Security.HideDisabledUsersInBackoffice == false);
}
[Test]
public void AllowPasswordReset()
{
Assert.IsTrue(SettingsSection.Security.AllowPasswordReset == true);
}
[Test]
public void AuthCookieDomain()
{
Assert.IsTrue(SettingsSection.Security.AuthCookieDomain == null);
}
[Test]
public void AuthCookieName()
{
Assert.IsTrue(SettingsSection.Security.AuthCookieName == Constants.Web.AuthCookieName);
}
}
}

View File

@@ -1,13 +1,13 @@
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class TemplateElementDefaultTests : TemplateElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class TemplateElementDefaultTests : TemplateElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}

View File

@@ -1,16 +1,30 @@
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class TemplateElementTests : UmbracoSettingsTests
{
[Test]
public void DefaultRenderingEngine()
{
Assert.IsTrue(SettingsSection.Templates.DefaultRenderingEngine == RenderingEngine.Mvc);
}
}
}
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class TemplateElementTests : UmbracoSettingsTests
{
[Test]
public void UseAspNetMasterPages()
{
Assert.IsTrue(SettingsSection.Templates.UseAspNetMasterPages == true);
}
[Test]
public void EnableSkinSupport()
{
Assert.IsTrue(SettingsSection.Templates.EnableSkinSupport);
}
[Test]
public void DefaultRenderingEngine()
{
Assert.IsTrue(SettingsSection.Templates.DefaultRenderingEngine == RenderingEngine.Mvc);
}
[Test]
public void EnableTemplateFolders()
{
Assert.IsTrue(SettingsSection.Templates.EnableTemplateFolders == false);
}
}
}

View File

@@ -1,37 +1,37 @@
using System.Configuration;
using System.Diagnostics;
using System.IO;
using NUnit.Framework;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
public abstract class UmbracoSettingsTests
{
protected virtual bool TestingDefaults { get; set; }
[SetUp]
public void Init()
{
var config = new FileInfo(TestHelper.MapPathForTest("~/Configurations/UmbracoSettings/web.config"));
var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = config.FullName };
using System.Configuration;
using System.Diagnostics;
using System.IO;
using NUnit.Framework;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Tests.TestHelpers;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
public abstract class UmbracoSettingsTests
{
protected virtual bool TestingDefaults { get; set; }
[SetUp]
public void Init()
{
var config = new FileInfo(TestHelper.MapPathForTest("~/Configurations/UmbracoSettings/web.config"));
var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = config.FullName };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
Debug.WriteLine("Testing defaults? {0}", TestingDefaults);
if (TestingDefaults)
{
SettingsSection = configuration.GetSection("umbracoConfiguration/defaultSettings") as UmbracoSettingsSection;
}
else
{
SettingsSection = configuration.GetSection("umbracoConfiguration/settings") as UmbracoSettingsSection;
}
Assert.IsNotNull(SettingsSection);
}
protected IUmbracoSettingsSection SettingsSection { get; private set; }
}
}
Debug.WriteLine("Testing defaults? {0}", TestingDefaults);
if (TestingDefaults)
{
SettingsSection = configuration.GetSection("umbracoConfiguration/defaultSettings") as UmbracoSettingsSection;
}
else
{
SettingsSection = configuration.GetSection("umbracoConfiguration/settings") as UmbracoSettingsSection;
}
Assert.IsNotNull(SettingsSection);
}
protected IUmbracoSettingsSection SettingsSection { get; private set; }
}
}

View File

@@ -0,0 +1,13 @@
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ViewstateMoverModuleElementDefaultTests : ViewstateMoverModuleElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
}
}

View File

@@ -0,0 +1,14 @@
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ViewstateMoverModuleElementTests : UmbracoSettingsTests
{
[Test]
public void Enable()
{
Assert.IsTrue(SettingsSection.ViewStateMoverModule.Enable == false);
}
}
}

View File

@@ -1,44 +1,44 @@
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class WebRoutingElementDefaultTests : WebRoutingElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void UrlProviderMode()
{
Assert.IsTrue(SettingsSection.WebRouting.UrlProviderMode == "AutoLegacy");
}
[Test]
public void DisableAlternativeTemplates()
{
Assert.IsTrue(SettingsSection.WebRouting.DisableAlternativeTemplates == false);
}
[Test]
public void ValidateAlternativeTemplates()
{
Assert.IsTrue(SettingsSection.WebRouting.ValidateAlternativeTemplates == false);
}
[Test]
public void DisableFindContentByIdPath()
{
Assert.IsTrue(SettingsSection.WebRouting.DisableFindContentByIdPath == false);
}
[Test]
public void DisableRedirectUrlTracking()
{
Assert.IsTrue(SettingsSection.WebRouting.DisableRedirectUrlTracking == false);
}
}
}
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class WebRoutingElementDefaultTests : WebRoutingElementTests
{
protected override bool TestingDefaults
{
get { return true; }
}
[Test]
public override void UrlProviderMode()
{
Assert.IsTrue(SettingsSection.WebRouting.UrlProviderMode == "AutoLegacy");
}
[Test]
public void DisableAlternativeTemplates()
{
Assert.IsTrue(SettingsSection.WebRouting.DisableAlternativeTemplates == false);
}
[Test]
public void ValidateAlternativeTemplates()
{
Assert.IsTrue(SettingsSection.WebRouting.ValidateAlternativeTemplates == false);
}
[Test]
public void DisableFindContentByIdPath()
{
Assert.IsTrue(SettingsSection.WebRouting.DisableFindContentByIdPath == false);
}
[Test]
public void DisableRedirectUrlTracking()
{
Assert.IsTrue(SettingsSection.WebRouting.DisableRedirectUrlTracking == false);
}
}
}

View File

@@ -1,26 +1,26 @@
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class WebRoutingElementTests : UmbracoSettingsTests
{
[Test]
public void TrySkipIisCustomErrors()
{
Assert.IsTrue(SettingsSection.WebRouting.TrySkipIisCustomErrors == false);
}
[Test]
public void InternalRedirectPreservesTemplate()
{
Assert.IsTrue(SettingsSection.WebRouting.TrySkipIisCustomErrors == false);
}
[Test]
public virtual void UrlProviderMode()
{
Assert.IsTrue(SettingsSection.WebRouting.UrlProviderMode == "AutoLegacy");
}
}
}
using NUnit.Framework;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class WebRoutingElementTests : UmbracoSettingsTests
{
[Test]
public void TrySkipIisCustomErrors()
{
Assert.IsTrue(SettingsSection.WebRouting.TrySkipIisCustomErrors == false);
}
[Test]
public void InternalRedirectPreservesTemplate()
{
Assert.IsTrue(SettingsSection.WebRouting.TrySkipIisCustomErrors == false);
}
[Test]
public virtual void UrlProviderMode()
{
Assert.IsTrue(SettingsSection.WebRouting.UrlProviderMode == "AutoLegacy");
}
}
}

Some files were not shown because too many files have changed in this diff Show More