Merge remote-tracking branch 'origin/netcore/netcore' into netcore/task/9779-publishedsnapshot-slight-cleanup

This commit is contained in:
Shannon
2020-12-23 11:12:55 +11:00
240 changed files with 5786 additions and 5279 deletions

View File

@@ -1,7 +1,6 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Microsoft.Extensions.DependencyInjection;
using Umbraco.Core.Events;
@@ -27,22 +26,5 @@ namespace Umbraco.Core.DependencyInjection
builder.Services.AddTransient(typeof(INotificationHandler<TNotification>), typeof(TNotificationHandler));
return builder;
}
/// <summary>
/// Registers a notification handler against the Umbraco service collection.
/// </summary>
/// <typeparam name="TNotification">The type of notification.</typeparam>
/// <typeparam name="TNotificationHandler">The type of notificiation handler.</typeparam>
/// <param name="builder">The Umbraco builder.</param>
/// <param name="factory">Factory method</param>
/// <returns>The <see cref="IUmbracoBuilder"/>.</returns>
public static IUmbracoBuilder AddNotificationHandler<TNotification, TNotificationHandler>(this IUmbracoBuilder builder, Func<IServiceProvider, TNotificationHandler> factory)
where TNotificationHandler : class, INotificationHandler<TNotification>
where TNotification : INotification
{
// Register the handler as transient. This ensures that anything can be injected into it.
builder.Services.AddTransient(typeof(INotificationHandler<TNotification>), factory);
return builder;
}
}
}

View File

@@ -1,14 +1,13 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Net;
namespace Umbraco.Core.Manifest
{
public class ManifestWatcher : DisposableObjectSlim
public class ManifestWatcher : IDisposable
{
private static readonly object Locker = new object();
private static volatile bool _isRestarting;
@@ -16,6 +15,7 @@ namespace Umbraco.Core.Manifest
private readonly ILogger<ManifestWatcher> _logger;
private readonly IUmbracoApplicationLifetime _umbracoApplicationLifetime;
private readonly List<FileSystemWatcher> _fws = new List<FileSystemWatcher>();
private bool _disposed;
public ManifestWatcher(ILogger<ManifestWatcher> logger, IUmbracoApplicationLifetime umbracoApplicationLifetime)
{
@@ -48,7 +48,10 @@ namespace Umbraco.Core.Manifest
private void FswChanged(object sender, FileSystemEventArgs e)
{
if (e.Name.InvariantContains("package.manifest") == false) return;
if (!e.Name.InvariantContains("package.manifest"))
{
return;
}
// ensure the app is not restarted multiple times for multiple
// savings during the same app domain execution - restart once
@@ -59,14 +62,25 @@ namespace Umbraco.Core.Manifest
_isRestarting = true;
_logger.LogInformation("Manifest has changed, app pool is restarting ({Path})", e.FullPath);
_umbracoApplicationLifetime.Restart();
Dispose(); // uh? if the app restarts then this should be disposed anyways?
}
}
protected override void DisposeResources()
private void Dispose(bool disposing)
{
foreach (var fw in _fws)
fw.Dispose();
// ReSharper disable InvertIf
if (disposing && !_disposed)
{
foreach (FileSystemWatcher fw in _fws)
{
fw.Dispose();
}
_disposed = true;
}
// ReSharper restore InvertIf
}
public void Dispose() => Dispose(true);
}
}

View File

@@ -1,9 +1,8 @@
using System;
using System;
using NCrontab;
namespace Umbraco.Core.Configuration
{
public class NCronTabParser : ICronTabParser
{
public bool IsValidCronTab(string cronTab)

View File

@@ -0,0 +1,45 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Hosting;
using Umbraco.Core.Manifest;
namespace Umbraco.Infrastructure.Runtime
{
/// <summary>
/// Starts monitoring AppPlugins directory during debug runs, to restart site when a plugin manifest changes.
/// </summary>
public sealed class AppPluginsManifestWatcherNotificationHandler : INotificationHandler<UmbracoApplicationStarting>
{
private readonly ManifestWatcher _manifestWatcher;
private readonly IHostingEnvironment _hostingEnvironment;
public AppPluginsManifestWatcherNotificationHandler(ManifestWatcher manifestWatcher, IHostingEnvironment hostingEnvironment)
{
_manifestWatcher = manifestWatcher ?? throw new ArgumentNullException(nameof(manifestWatcher));
_hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
}
public Task HandleAsync(UmbracoApplicationStarting notification, CancellationToken cancellationToken)
{
if (!_hostingEnvironment.IsDebugMode)
{
return Task.CompletedTask;
}
var appPlugins = _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.AppPlugins);
if (!Directory.Exists(appPlugins))
{
return Task.CompletedTask;
}
_manifestWatcher.Start(Directory.GetDirectories(appPlugins));
return Task.CompletedTask;
}
}
}

View File

@@ -71,8 +71,7 @@ namespace Umbraco.Infrastructure.Runtime
builder.AddNotificationHandler<UmbracoApplicationStarting, EssentialDirectoryCreator>();
builder.Services.AddSingleton<ManifestWatcher>();
builder.AddNotificationHandler<UmbracoApplicationStarting, ManifestWatcher>(factory => factory.GetRequiredService<ManifestWatcher>());
builder.AddNotificationHandler<UmbracoApplicationStopping, ManifestWatcher>(factory => factory.GetRequiredService<ManifestWatcher>());
builder.AddNotificationHandler<UmbracoApplicationStarting, AppPluginsManifestWatcherNotificationHandler>();
// composers
builder

View File

@@ -1,65 +0,0 @@
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Hosting;
using Umbraco.Net;
namespace Umbraco.Infrastructure.Runtime
{
public sealed class ManifestWatcher :
INotificationHandler<UmbracoApplicationStarting>,
INotificationHandler<UmbracoApplicationStopping>
{
private readonly IHostingEnvironment _hosting;
private readonly ILoggerFactory _loggerFactory;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IUmbracoApplicationLifetime _umbracoApplicationLifetime;
// if configured and in debug mode, a ManifestWatcher watches App_Plugins folders for
// package.manifest chances and restarts the application on any change
private Core.Manifest.ManifestWatcher _mw;
public ManifestWatcher(IHostingEnvironment hosting, ILoggerFactory loggerFactory, IHostingEnvironment hostingEnvironment, IUmbracoApplicationLifetime umbracoApplicationLifetime)
{
_hosting = hosting;
_loggerFactory = loggerFactory;
_hostingEnvironment = hostingEnvironment;
_umbracoApplicationLifetime = umbracoApplicationLifetime;
}
public Task HandleAsync(UmbracoApplicationStarting notification, CancellationToken cancellationToken)
{
if (_hosting.IsDebugMode == false)
{
return Task.CompletedTask;
}
var appPlugins = _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.AppPlugins);
if (Directory.Exists(appPlugins) == false)
{
return Task.CompletedTask;
}
_mw = new Core.Manifest.ManifestWatcher(_loggerFactory.CreateLogger<Core.Manifest.ManifestWatcher>(), _umbracoApplicationLifetime);
_mw.Start(Directory.GetDirectories(appPlugins));
return Task.CompletedTask;
}
public Task HandleAsync(UmbracoApplicationStopping notification, CancellationToken cancellationToken)
{
if (_mw == null)
{
return Task.CompletedTask;
}
_mw.Dispose();
_mw = null;
return Task.CompletedTask;
}
}
}

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -70,7 +71,7 @@ namespace Umbraco.Tests.Integration.Testing
}
[TearDown]
public virtual void TearDown()
public async Task TearDownAsync()
{
if (_testTeardown != null)
{
@@ -86,7 +87,7 @@ namespace Umbraco.Tests.Integration.Testing
// Ensure CoreRuntime stopped (now it's a HostedService)
IHost host = Services.GetRequiredService<IHost>();
host.StopAsync().GetAwaiter().GetResult();
await host.StopAsync();
host.Dispose();
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Linq;
using System.Reflection;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using AutoFixture;
using AutoFixture.AutoMoq;
using AutoFixture.Kernel;
@@ -14,7 +15,6 @@ using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.Security;
using Umbraco.Tests.Common.Builders;
using Umbraco.Web.BackOffice.Controllers;
using Umbraco.Web.BackOffice.Routing;
using Umbraco.Web.Common.Install;
@@ -23,20 +23,6 @@ using Umbraco.Web.WebApi;
namespace Umbraco.Tests.UnitTests.AutoFixture
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true)]
public class InlineAutoMoqDataAttribute : InlineAutoDataAttribute
{
/// <summary>
/// Uses AutoFixture to automatically mock (using Moq) the injected types. E.g when injecting interfaces.
/// AutoFixture is used to generate concrete types. If the concrete type required some types injected, the
/// [Frozen] can be used to ensure the same variable is injected and available as parameter for the test
/// </summary>
public InlineAutoMoqDataAttribute(params object[] arguments) : base(() => AutoMoqDataAttribute.AutoMockCustomizations.Default, arguments)
{
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor)]
public class AutoMoqDataAttribute : AutoDataAttribute
{
@@ -45,7 +31,8 @@ namespace Umbraco.Tests.UnitTests.AutoFixture
/// AutoFixture is used to generate concrete types. If the concrete type required some types injected, the
/// [Frozen] can be used to ensure the same variable is injected and available as parameter for the test
/// </summary>
public AutoMoqDataAttribute() : base(() => AutoMockCustomizations.Default)
public AutoMoqDataAttribute()
: base(() => AutoMockCustomizations.Default)
{
}
@@ -58,8 +45,8 @@ namespace Umbraco.Tests.UnitTests.AutoFixture
public void Customize(IFixture fixture)
{
fixture.Customize<BackOfficeIdentityUser>(
u => u.FromFactory<string ,string, string>(
(a,b,c) => BackOfficeIdentityUser.CreateNew(new GlobalSettings(),a,b,c)));
u => u.FromFactory<string, string, string>(
(a, b, c) => BackOfficeIdentityUser.CreateNew(new GlobalSettings(), a, b, c)));
fixture
.Customize(new ConstructorCustomization(typeof(UsersController), new GreedyConstructorQuery()))
.Customize(new ConstructorCustomization(typeof(InstallController), new GreedyConstructorQuery()))
@@ -68,6 +55,7 @@ namespace Umbraco.Tests.UnitTests.AutoFixture
.Customize(new ConstructorCustomization(typeof(BackOfficeUserManager), new GreedyConstructorQuery()));
fixture.Customize(new AutoMoqCustomization());
// When requesting an IUserStore ensure we actually uses a IUserLockoutStore
fixture.Customize<IUserStore<BackOfficeIdentityUser>>(cc => cc.FromFactory(() => Mock.Of<IUserLockoutStore<BackOfficeIdentityUser>>()));
@@ -93,13 +81,11 @@ namespace Umbraco.Tests.UnitTests.AutoFixture
Mock.Of<IRuntimeState>(x => x.Level == RuntimeLevel.Run))));
var connectionStrings = new ConnectionStrings();
fixture.Customize<ConnectionStrings>(x => x.FromFactory(() => connectionStrings ));
fixture.Customize<ConnectionStrings>(x => x.FromFactory(() => connectionStrings));
var httpContextAccessor = new HttpContextAccessor { HttpContext = new DefaultHttpContext() };
fixture.Customize<HttpContext>(x => x.FromFactory(() => httpContextAccessor.HttpContext));
fixture.Customize<IHttpContextAccessor>(x => x.FromFactory(() => httpContextAccessor));
}
}
}

View File

@@ -0,0 +1,22 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using AutoFixture.NUnit3;
namespace Umbraco.Tests.UnitTests.AutoFixture
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true)]
public class InlineAutoMoqDataAttribute : InlineAutoDataAttribute
{
/// <summary>
/// Uses AutoFixture to automatically mock (using Moq) the injected types. E.g when injecting interfaces.
/// AutoFixture is used to generate concrete types. If the concrete type required some types injected, the
/// [Frozen] can be used to ensure the same variable is injected and available as parameter for the test
/// </summary>
public InlineAutoMoqDataAttribute(params object[] arguments)
: base(() => AutoMoqDataAttribute.AutoMockCustomizations.Default, arguments)
{
}
}
}

View File

@@ -1,3 +1,6 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -5,14 +8,12 @@ using Moq;
using NPoco;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Core.DependencyInjection;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Mappers;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Tests.UnitTests.TestHelpers;
using Umbraco.Core.DependencyInjection;
namespace Umbraco.Tests.TestHelpers
{
@@ -23,26 +24,22 @@ namespace Umbraco.Tests.TestHelpers
protected ISqlContext SqlContext { get; private set; }
protected Sql<ISqlContext> Sql()
{
return NPoco.Sql.BuilderFor(SqlContext);
}
protected Sql<ISqlContext> Sql() => NPoco.Sql.BuilderFor(SqlContext);
[SetUp]
public virtual void Setup()
{
var container = TestHelper.GetServiceCollection();
var typeLoader = TestHelper.GetMockedTypeLoader();
IServiceCollection container = TestHelper.GetServiceCollection();
TypeLoader typeLoader = TestHelper.GetMockedTypeLoader();
var composition = new UmbracoBuilder(container, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
composition.WithCollectionBuilder<MapperCollectionBuilder>()
.AddCoreMappers();
composition.Services.AddUnique<ISqlContext>(_ => SqlContext);
composition.Services.AddUnique(_ => SqlContext);
var factory = composition.CreateServiceProvider();
IServiceProvider factory = composition.CreateServiceProvider();
var pocoMappers = new NPoco.MapperCollection { new PocoMapper() };
var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init());
var sqlSyntax = new SqlServerSyntaxProvider();

View File

@@ -1,7 +1,9 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Microsoft.Extensions.DependencyInjection;
using Umbraco.Core.DependencyInjection;
using Umbraco.Core.Composing;
namespace Umbraco.Tests.UnitTests.TestHelpers
{

View File

@@ -1,16 +1,17 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Moq;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.Tests.Common;
using Umbraco.Web;
using Umbraco.Web.Common.AspNetCore;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
namespace Umbraco.Tests.UnitTests.TestHelpers.Objects
{
@@ -19,15 +20,31 @@ namespace Umbraco.Tests.UnitTests.TestHelpers.Objects
/// </summary>
public class TestUmbracoContextFactory
{
public static IUmbracoContextFactory Create(GlobalSettings globalSettings = null,
public static IUmbracoContextFactory Create(
GlobalSettings globalSettings = null,
IUmbracoContextAccessor umbracoContextAccessor = null,
IHttpContextAccessor httpContextAccessor = null,
IPublishedUrlProvider publishedUrlProvider = null)
{
if (globalSettings == null) globalSettings = new GlobalSettings();
if (umbracoContextAccessor == null) umbracoContextAccessor = new TestUmbracoContextAccessor();
if (httpContextAccessor == null) httpContextAccessor = Mock.Of<IHttpContextAccessor>();
if (publishedUrlProvider == null) publishedUrlProvider = Mock.Of<IPublishedUrlProvider>();
if (globalSettings == null)
{
globalSettings = new GlobalSettings();
}
if (umbracoContextAccessor == null)
{
umbracoContextAccessor = new TestUmbracoContextAccessor();
}
if (httpContextAccessor == null)
{
httpContextAccessor = Mock.Of<IHttpContextAccessor>();
}
if (publishedUrlProvider == null)
{
publishedUrlProvider = Mock.Of<IPublishedUrlProvider>();
}
var contentCache = new Mock<IPublishedContentCache>();
var mediaCache = new Mock<IPublishedMediaCache>();
@@ -37,11 +54,10 @@ namespace Umbraco.Tests.UnitTests.TestHelpers.Objects
var snapshotService = new Mock<IPublishedSnapshotService>();
snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny<string>())).Returns(snapshot.Object);
var hostingEnvironment = Mock.Of<IHostingEnvironment>();
IHostingEnvironment hostingEnvironment = Mock.Of<IHostingEnvironment>();
var backofficeSecurityAccessorMock = new Mock<IBackOfficeSecurityAccessor>();
backofficeSecurityAccessorMock.Setup(x => x.BackOfficeSecurity).Returns(Mock.Of<IBackOfficeSecurity>());
var umbracoContextFactory = new UmbracoContextFactory(
umbracoContextAccessor,
snapshotService.Object,
@@ -52,8 +68,7 @@ namespace Umbraco.Tests.UnitTests.TestHelpers.Objects
new UriUtility(hostingEnvironment),
new AspNetCoreCookieManager(httpContextAccessor),
Mock.Of<IRequestAccessor>(),
backofficeSecurityAccessorMock.Object
);
backofficeSecurityAccessorMock.Object);
return umbracoContextFactory;
}

View File

@@ -1,20 +1,23 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Diagnostics;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
@@ -22,21 +25,19 @@ using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Entities;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Net;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Serialization;
using Umbraco.Core.Strings;
using Umbraco.Infrastructure.Persistence.Mappers;
using Umbraco.Net;
using Umbraco.Tests.Common;
using Umbraco.Web;
using Umbraco.Web.Common.AspNetCore;
using Umbraco.Web.Routing;
using File = System.IO.File;
using Microsoft.Extensions.Options;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Web.Common.AspNetCore;
using IHostingEnvironment = Umbraco.Core.Hosting.IHostingEnvironment;
using Umbraco.Infrastructure.Persistence.Mappers;
namespace Umbraco.Tests.TestHelpers
{
@@ -45,14 +46,13 @@ namespace Umbraco.Tests.TestHelpers
/// </summary>
public static class TestHelper
{
private static readonly TestHelperInternal _testHelperInternal = new TestHelperInternal();
private static IEmailSender _emailSender;
private static readonly TestHelperInternal s_testHelperInternal = new TestHelperInternal();
private class TestHelperInternal : TestHelperBase
{
public TestHelperInternal() : base(typeof(TestHelperInternal).Assembly)
public TestHelperInternal()
: base(typeof(TestHelperInternal).Assembly)
{
}
public override IDbProviderFactoryCreator DbProviderFactoryCreator { get; } = Mock.Of<IDbProviderFactoryCreator>();
@@ -68,9 +68,9 @@ namespace Umbraco.Tests.TestHelpers
{
var testPath = TestContext.CurrentContext.TestDirectory.Split("bin")[0];
return new AspNetCoreHostingEnvironment(
Mock.Of<IOptionsMonitor<HostingSettings>>(x=>x.CurrentValue == new HostingSettings()),
Mock.Of<IOptionsMonitor<HostingSettings>>(x => x.CurrentValue == new HostingSettings()),
Mock.Of<IWebHostEnvironment>(
x=>
x =>
x.WebRootPath == "/" &&
x.ContentRootPath == testPath));
}
@@ -82,13 +82,13 @@ namespace Umbraco.Tests.TestHelpers
=> Mock.Of<IIpResolver>();
}
public static ITypeFinder GetTypeFinder() => _testHelperInternal.GetTypeFinder();
public static ITypeFinder GetTypeFinder() => s_testHelperInternal.GetTypeFinder();
public static TypeLoader GetMockedTypeLoader() => _testHelperInternal.GetMockedTypeLoader();
public static TypeLoader GetMockedTypeLoader() => s_testHelperInternal.GetMockedTypeLoader();
public static Lazy<ISqlContext> GetMockSqlContext()
{
var sqlContext = Mock.Of<ISqlContext>();
ISqlContext sqlContext = Mock.Of<ISqlContext>();
var syntax = new SqlServerSyntaxProvider();
Mock.Get(sqlContext).Setup(x => x.SqlSyntax).Returns(syntax);
return new Lazy<ISqlContext>(() => sqlContext);
@@ -97,50 +97,48 @@ namespace Umbraco.Tests.TestHelpers
public static MapperConfigurationStore CreateMaps()
=> new MapperConfigurationStore();
//public static Configs GetConfigs() => _testHelperInternal.GetConfigs();
//// public static Configs GetConfigs() => _testHelperInternal.GetConfigs();
public static IBackOfficeInfo GetBackOfficeInfo() => _testHelperInternal.GetBackOfficeInfo();
public static IBackOfficeInfo GetBackOfficeInfo() => s_testHelperInternal.GetBackOfficeInfo();
// public static IConfigsFactory GetConfigsFactory() => _testHelperInternal.GetConfigsFactory();
//// public static IConfigsFactory GetConfigsFactory() => _testHelperInternal.GetConfigsFactory();
/// <summary>
/// Gets the working directory of the test project.
/// </summary>
/// <value>The assembly directory.</value>
public static string WorkingDirectory => _testHelperInternal.WorkingDirectory;
public static string WorkingDirectory => s_testHelperInternal.WorkingDirectory;
public static IShortStringHelper ShortStringHelper => _testHelperInternal.ShortStringHelper;
public static IJsonSerializer JsonSerializer => _testHelperInternal.JsonSerializer;
public static IVariationContextAccessor VariationContextAccessor => _testHelperInternal.VariationContextAccessor;
public static IDbProviderFactoryCreator DbProviderFactoryCreator => _testHelperInternal.DbProviderFactoryCreator;
public static IBulkSqlInsertProvider BulkSqlInsertProvider => _testHelperInternal.BulkSqlInsertProvider;
public static IMarchal Marchal => _testHelperInternal.Marchal;
public static CoreDebugSettings CoreDebugSettings => _testHelperInternal.CoreDebugSettings;
public static IShortStringHelper ShortStringHelper => s_testHelperInternal.ShortStringHelper;
public static IJsonSerializer JsonSerializer => s_testHelperInternal.JsonSerializer;
public static IIOHelper IOHelper => _testHelperInternal.IOHelper;
public static IMainDom MainDom => _testHelperInternal.MainDom;
public static UriUtility UriUtility => _testHelperInternal.UriUtility;
public static IVariationContextAccessor VariationContextAccessor => s_testHelperInternal.VariationContextAccessor;
public static IDbProviderFactoryCreator DbProviderFactoryCreator => s_testHelperInternal.DbProviderFactoryCreator;
public static IBulkSqlInsertProvider BulkSqlInsertProvider => s_testHelperInternal.BulkSqlInsertProvider;
public static IMarchal Marchal => s_testHelperInternal.Marchal;
public static CoreDebugSettings CoreDebugSettings => s_testHelperInternal.CoreDebugSettings;
public static IIOHelper IOHelper => s_testHelperInternal.IOHelper;
public static IMainDom MainDom => s_testHelperInternal.MainDom;
public static UriUtility UriUtility => s_testHelperInternal.UriUtility;
public static IEmailSender EmailSender { get; } = new EmailSender(Options.Create(new GlobalSettings()));
/// <summary>
/// Some test files are copied to the /bin (/bin/debug) on build, this is a utility to return their physical path based on a virtual path name
/// </summary>
/// <param name="relativePath"></param>
/// <returns></returns>
public static string MapPathForTestFiles(string relativePath) => _testHelperInternal.MapPathForTestFiles(relativePath);
public static string MapPathForTestFiles(string relativePath) => s_testHelperInternal.MapPathForTestFiles(relativePath);
public static void InitializeContentDirectories()
{
CreateDirectories(new[] { Constants.SystemDirectories.MvcViews, new GlobalSettings().UmbracoMediaPath, Constants.SystemDirectories.AppPlugins });
}
public static void InitializeContentDirectories() => CreateDirectories(new[] { Constants.SystemDirectories.MvcViews, new GlobalSettings().UmbracoMediaPath, Constants.SystemDirectories.AppPlugins });
public static void CleanContentDirectories()
{
CleanDirectories(new[] { Constants.SystemDirectories.MvcViews, new GlobalSettings().UmbracoMediaPath });
}
public static void CleanContentDirectories() => CleanDirectories(new[] { Constants.SystemDirectories.MvcViews, new GlobalSettings().UmbracoMediaPath });
public static void CreateDirectories(string[] directories)
{
@@ -148,7 +146,9 @@ namespace Umbraco.Tests.TestHelpers
{
var directoryInfo = new DirectoryInfo(IOHelper.MapPath(directory));
if (directoryInfo.Exists == false)
{
Directory.CreateDirectory(IOHelper.MapPath(directory));
}
}
}
@@ -156,15 +156,20 @@ namespace Umbraco.Tests.TestHelpers
{
var preserves = new Dictionary<string, string[]>
{
{ Constants.SystemDirectories.MvcViews, new[] {"dummy.txt"} }
{ Constants.SystemDirectories.MvcViews, new[] { "dummy.txt" } }
};
foreach (var directory in directories)
{
var directoryInfo = new DirectoryInfo(IOHelper.MapPath(directory));
var preserve = preserves.ContainsKey(directory) ? preserves[directory] : null;
if (directoryInfo.Exists)
foreach (var x in directoryInfo.GetFiles().Where(x => preserve == null || preserve.Contains(x.Name) == false))
x.Delete();
{
foreach (FileInfo fileInfo in directoryInfo.GetFiles().Where(x => preserve == null || preserve.Contains(x.Name) == false))
{
fileInfo.Delete();
}
}
}
}
@@ -174,7 +179,9 @@ namespace Umbraco.Tests.TestHelpers
var umbracoSettingsFile = Path.Combine(currDir.Parent.Parent.FullName, "config", "umbracoSettings.config");
if (File.Exists(umbracoSettingsFile))
{
File.Delete(umbracoSettingsFile);
}
}
// TODO: Move to Assertions or AssertHelper
@@ -183,17 +190,21 @@ namespace Umbraco.Tests.TestHelpers
{
const int dateDeltaMilliseconds = 500; // .5s
var properties = expected.GetType().GetProperties();
foreach (var property in properties)
PropertyInfo[] properties = expected.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
// ignore properties that are attributed with EditorBrowsableState.Never
var att = property.GetCustomAttribute<EditorBrowsableAttribute>(false);
EditorBrowsableAttribute att = property.GetCustomAttribute<EditorBrowsableAttribute>(false);
if (att != null && att.State == EditorBrowsableState.Never)
{
continue;
}
// ignore explicitely ignored properties
if (ignoreProperties != null && ignoreProperties.Contains(property.Name))
{
continue;
}
var actualValue = property.GetValue(actual, null);
var expectedValue = property.GetValue(expected, null);
@@ -204,31 +215,36 @@ namespace Umbraco.Tests.TestHelpers
private static void AssertAreEqual(PropertyInfo property, object expected, object actual, Func<IEnumerable, IEnumerable> sorter = null, int dateDeltaMilliseconds = 0)
{
if (!(expected is string) && expected is IEnumerable)
if (!(expected is string) && expected is IEnumerable enumerable)
{
// sort property collection by alias, not by property ids
// on members, built-in properties don't have ids (always zero)
if (expected is PropertyCollection)
sorter = e => ((PropertyCollection) e).OrderBy(x => x.Alias);
{
sorter = e => ((PropertyCollection)e).OrderBy(x => x.Alias);
}
// compare lists
AssertListsAreEqual(property, (IEnumerable) actual, (IEnumerable) expected, sorter, dateDeltaMilliseconds);
AssertListsAreEqual(property, (IEnumerable)actual, enumerable, sorter, dateDeltaMilliseconds);
}
else if (expected is DateTime expectedDateTime)
{
// compare date & time with delta
var actualDateTime = (DateTime) actual;
var actualDateTime = (DateTime)actual;
var delta = (actualDateTime - expectedDateTime).TotalMilliseconds;
Assert.IsTrue(Math.Abs(delta) <= dateDeltaMilliseconds, "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expected, actual);
}
else if (expected is Property expectedProperty)
{
// compare values
var actualProperty = (Property) actual;
var expectedPropertyValues = expectedProperty.Values.OrderBy(x => x.Culture).ThenBy(x => x.Segment).ToArray();
var actualPropertyValues = actualProperty.Values.OrderBy(x => x.Culture).ThenBy(x => x.Segment).ToArray();
var actualProperty = (Property)actual;
IPropertyValue[] expectedPropertyValues = expectedProperty.Values.OrderBy(x => x.Culture).ThenBy(x => x.Segment).ToArray();
IPropertyValue[] actualPropertyValues = actualProperty.Values.OrderBy(x => x.Culture).ThenBy(x => x.Segment).ToArray();
if (expectedPropertyValues.Length != actualPropertyValues.Length)
{
Assert.Fail($"{property.DeclaringType.Name}.{property.Name}: Expected {expectedPropertyValues.Length} but got {actualPropertyValues.Length}.");
}
for (var i = 0; i < expectedPropertyValues.Length; i++)
{
Assert.AreEqual(expectedPropertyValues[i].EditedValue, actualPropertyValues[i].EditedValue, $"{property.DeclaringType.Name}.{property.Name}: Expected draft value \"{expectedPropertyValues[i].EditedValue}\" but got \"{actualPropertyValues[i].EditedValue}\".");
@@ -238,22 +254,27 @@ namespace Umbraco.Tests.TestHelpers
else if (expected is IDataEditor expectedEditor)
{
Assert.IsInstanceOf<IDataEditor>(actual);
var actualEditor = (IDataEditor) actual;
var actualEditor = (IDataEditor)actual;
Assert.AreEqual(expectedEditor.Alias, actualEditor.Alias);
// what else shall we test?
}
else
{
// directly compare values
Assert.AreEqual(expected, actual, "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name,
expected?.ToString() ?? "<null>", actual?.ToString() ?? "<null>");
Assert.AreEqual(
expected,
actual,
"Property {0}.{1} does not match. Expected: {2} but was: {3}",
property.DeclaringType.Name,
property.Name,
expected?.ToString() ?? "<null>",
actual?.ToString() ?? "<null>");
}
}
private static void AssertListsAreEqual(PropertyInfo property, IEnumerable expected, IEnumerable actual, Func<IEnumerable, IEnumerable> sorter = null, int dateDeltaMilliseconds = 0)
{
if (sorter == null)
{
// this is pretty hackerific but saves us some code to write
@@ -261,7 +282,7 @@ namespace Umbraco.Tests.TestHelpers
{
// semi-generic way of ensuring any collection of IEntity are sorted by Ids for comparison
var entities = enumerable.OfType<IEntity>().ToList();
return entities.Count > 0 ? (IEnumerable) entities.OrderBy(x => x.Id) : entities;
return entities.Count > 0 ? (IEnumerable)entities.OrderBy(x => x.Id) : entities;
};
}
@@ -269,28 +290,30 @@ namespace Umbraco.Tests.TestHelpers
var actualListEx = sorter(actual).Cast<object>().ToList();
if (actualListEx.Count != expectedListEx.Count)
{
Assert.Fail("Collection {0}.{1} does not match. Expected IEnumerable containing {2} elements but was IEnumerable containing {3} elements", property.PropertyType.Name, property.Name, expectedListEx.Count, actualListEx.Count);
}
for (var i = 0; i < actualListEx.Count; i++)
{
AssertAreEqual(property, expectedListEx[i], actualListEx[i], sorter, dateDeltaMilliseconds);
}
}
public static IUmbracoVersion GetUmbracoVersion() => _testHelperInternal.GetUmbracoVersion();
public static IUmbracoVersion GetUmbracoVersion() => s_testHelperInternal.GetUmbracoVersion();
public static IServiceCollection GetServiceCollection() => new ServiceCollection().AddLazySupport();
public static IHostingEnvironment GetHostingEnvironment() => _testHelperInternal.GetHostingEnvironment();
public static IHostingEnvironment GetHostingEnvironment() => s_testHelperInternal.GetHostingEnvironment();
public static ILoggingConfiguration GetLoggingConfiguration(IHostingEnvironment hostingEnv) => _testHelperInternal.GetLoggingConfiguration(hostingEnv);
public static ILoggingConfiguration GetLoggingConfiguration(IHostingEnvironment hostingEnv) => s_testHelperInternal.GetLoggingConfiguration(hostingEnv);
public static IApplicationShutdownRegistry GetHostingEnvironmentLifetime() => _testHelperInternal.GetHostingEnvironmentLifetime();
public static IApplicationShutdownRegistry GetHostingEnvironmentLifetime() => s_testHelperInternal.GetHostingEnvironmentLifetime();
public static IIpResolver GetIpResolver() => _testHelperInternal.GetIpResolver();
public static IIpResolver GetIpResolver() => s_testHelperInternal.GetIpResolver();
public static IRequestCache GetRequestCache() => _testHelperInternal.GetRequestCache();
public static IRequestCache GetRequestCache() => s_testHelperInternal.GetRequestCache();
public static IPublishedUrlProvider GetPublishedUrlProvider() => _testHelperInternal.GetPublishedUrlProvider();
public static IPublishedUrlProvider GetPublishedUrlProvider() => s_testHelperInternal.GetPublishedUrlProvider();
}
}

View File

@@ -1,4 +1,7 @@
using NUnit.Framework;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;

View File

@@ -1,4 +1,7 @@
using NUnit.Framework;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.UnitTests.Umbraco.Core
@@ -9,10 +12,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
[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);
// Just making sure that it is ok to use TryParse as a condition.
var attempt = Attempt.If(int.TryParse("1234", out int value), value);
Assert.IsTrue(attempt.Success);
Assert.AreEqual(1234, attempt.Result);

View File

@@ -1,3 +1,6 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Security.Claims;
@@ -47,7 +50,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
[Test]
public void CreateAsync_When_User_Is_Null_Expect_ArgumentNullException()
{
var sut = CreateSut();
BackOfficeClaimsPrincipalFactory sut = CreateSut();
Assert.ThrowsAsync<ArgumentNullException>(async () => await sut.CreateAsync(null));
}
@@ -55,9 +58,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
[Test]
public async Task CreateAsync_Should_Create_Principal_With_Umbraco_Identity()
{
var sut = CreateSut();
BackOfficeClaimsPrincipalFactory sut = CreateSut();
var claimsPrincipal = await sut.CreateAsync(_testUser);
ClaimsPrincipal claimsPrincipal = await sut.CreateAsync(_testUser);
var umbracoBackOfficeIdentity = claimsPrincipal.Identity as UmbracoBackOfficeIdentity;
Assert.IsNotNull(umbracoBackOfficeIdentity);
@@ -67,9 +70,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
[TestCase(ClaimTypes.Name, TestUserName)]
public async Task CreateAsync_Should_Include_Claim(string expectedClaimType, object expectedClaimValue)
{
var sut = CreateSut();
BackOfficeClaimsPrincipalFactory sut = CreateSut();
var claimsPrincipal = await sut.CreateAsync(_testUser);
ClaimsPrincipal claimsPrincipal = await sut.CreateAsync(_testUser);
Assert.True(claimsPrincipal.HasClaim(expectedClaimType, expectedClaimValue.ToString()));
Assert.True(claimsPrincipal.GetUmbracoIdentity().HasClaim(expectedClaimType, expectedClaimValue.ToString()));
@@ -84,9 +87,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
_mockUserManager.Setup(x => x.SupportsUserSecurityStamp).Returns(true);
_mockUserManager.Setup(x => x.GetSecurityStampAsync(_testUser)).ReturnsAsync(_testUser.SecurityStamp);
var sut = CreateSut();
BackOfficeClaimsPrincipalFactory sut = CreateSut();
var claimsPrincipal = await sut.CreateAsync(_testUser);
ClaimsPrincipal claimsPrincipal = await sut.CreateAsync(_testUser);
Assert.True(claimsPrincipal.HasClaim(expectedClaimType, expectedClaimValue));
Assert.True(claimsPrincipal.GetUmbracoIdentity().HasClaim(expectedClaimType, expectedClaimValue));
@@ -100,11 +103,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
_testUser.Roles.Add(new IdentityUserRole<string> { RoleId = expectedClaimValue });
_mockUserManager.Setup(x => x.SupportsUserRole).Returns(true);
_mockUserManager.Setup(x => x.GetRolesAsync(_testUser)).ReturnsAsync(new[] {expectedClaimValue});
_mockUserManager.Setup(x => x.GetRolesAsync(_testUser)).ReturnsAsync(new[] { expectedClaimValue });
var sut = CreateSut();
BackOfficeClaimsPrincipalFactory sut = CreateSut();
var claimsPrincipal = await sut.CreateAsync(_testUser);
ClaimsPrincipal claimsPrincipal = await sut.CreateAsync(_testUser);
Assert.True(claimsPrincipal.HasClaim(expectedClaimType, expectedClaimValue));
}
@@ -115,14 +118,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
const string expectedClaimType = "custom";
const string expectedClaimValue = "val";
_testUser.Claims.Add(new IdentityUserClaim<string> { ClaimType = expectedClaimType, ClaimValue = expectedClaimValue});
_testUser.Claims.Add(new IdentityUserClaim<string> { ClaimType = expectedClaimType, ClaimValue = expectedClaimValue });
_mockUserManager.Setup(x => x.SupportsUserClaim).Returns(true);
_mockUserManager.Setup(x => x.GetClaimsAsync(_testUser)).ReturnsAsync(
new List<Claim> {new Claim(expectedClaimType, expectedClaimValue)});
new List<Claim> { new Claim(expectedClaimType, expectedClaimValue) });
var sut = CreateSut();
BackOfficeClaimsPrincipalFactory sut = CreateSut();
var claimsPrincipal = await sut.CreateAsync(_testUser);
ClaimsPrincipal claimsPrincipal = await sut.CreateAsync(_testUser);
Assert.True(claimsPrincipal.GetUmbracoIdentity().HasClaim(expectedClaimType, expectedClaimValue));
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using NUnit.Framework;
@@ -20,9 +23,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
public void ToErrorMessage_When_Single_Error_Expect_Error_Description()
{
const string expectedError = "invalid something";
var errors = new List<IdentityError> {new IdentityError {Code = "1", Description = expectedError}};
var errors = new List<IdentityError> { new IdentityError { Code = "1", Description = expectedError } };
var errorMessage = errors.ToErrorMessage();
string errorMessage = errors.ToErrorMessage();
Assert.AreEqual(expectedError, errorMessage);
}
@@ -34,11 +37,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
const string error2 = "invalid something else";
var errors = new List<IdentityError>
{
new IdentityError {Code = "1", Description = error1},
new IdentityError {Code = "2", Description = error2}
new IdentityError { Code = "1", Description = error1 },
new IdentityError { Code = "2", Description = error2 }
};
var errorMessage = errors.ToErrorMessage();
string errorMessage = errors.ToErrorMessage();
Assert.AreEqual($"{error1}, {error2}", errorMessage);
}

View File

@@ -1,3 +1,6 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using NUnit.Framework;
using Umbraco.Core.Security;
@@ -29,6 +32,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
Assert.AreEqual(name, normalizedName);
}
[Test]
[TestCase(null)]
[TestCase("")]

View File

@@ -1,3 +1,6 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Linq;
using System.Security.Claims;
@@ -10,7 +13,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
[TestFixture]
public class UmbracoBackOfficeIdentityTests
{
public const string TestIssuer = "TestIssuer";
[Test]
@@ -19,10 +21,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
var securityStamp = Guid.NewGuid().ToString();
var claimsIdentity = new ClaimsIdentity(new[]
{
//This is the id that 'identity' uses to check for the user id
// This is the id that 'identity' uses to check for the user id.
new Claim(ClaimTypes.NameIdentifier, "1234", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
//This is the id that 'identity' uses to check for the username
// This is the id that 'identity' uses to check for the username.
new Claim(ClaimTypes.Name, "testing", ClaimValueTypes.String, TestIssuer, TestIssuer),
new Claim(ClaimTypes.GivenName, "hello world", ClaimValueTypes.String, TestIssuer, TestIssuer),
new Claim(Constants.Security.StartContentNodeIdClaimType, "-1", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
new Claim(Constants.Security.StartMediaNodeIdClaimType, "5543", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
@@ -34,18 +38,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
new Claim(Constants.Security.SecurityStampClaimType, securityStamp, ClaimValueTypes.String, TestIssuer, TestIssuer),
});
if (!UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity, out var backofficeIdentity))
if (!UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity, out UmbracoBackOfficeIdentity backofficeIdentity))
{
Assert.Fail();
}
Assert.IsNull(backofficeIdentity.Actor);
Assert.AreEqual(1234, backofficeIdentity.Id);
//Assert.AreEqual(sessionId, backofficeIdentity.SessionId);
//// Assert.AreEqual(sessionId, backofficeIdentity.SessionId);
Assert.AreEqual(securityStamp, backofficeIdentity.SecurityStamp);
Assert.AreEqual("testing", backofficeIdentity.Username);
Assert.AreEqual("hello world", backofficeIdentity.RealName);
Assert.AreEqual(1, backofficeIdentity.StartContentNodes.Length);
Assert.IsTrue(backofficeIdentity.StartMediaNodes.UnsortedSequenceEqual(new[] { 5543, 5555 }));
Assert.IsTrue(new[] {"content", "media"}.SequenceEqual(backofficeIdentity.AllowedApplications));
Assert.IsTrue(new[] { "content", "media" }.SequenceEqual(backofficeIdentity.AllowedApplications));
Assert.AreEqual("en-us", backofficeIdentity.Culture);
Assert.IsTrue(new[] { "admin" }.SequenceEqual(backofficeIdentity.Roles));
@@ -62,7 +68,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
});
if (UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity, out _))
{
Assert.Fail();
}
Assert.Pass();
}
@@ -72,8 +80,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
{
var claimsIdentity = new ClaimsIdentity(new[]
{
//null or empty
new Claim(ClaimTypes.NameIdentifier, "", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
// Null or empty
new Claim(ClaimTypes.NameIdentifier, string.Empty, ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
new Claim(ClaimTypes.Name, "testing", ClaimValueTypes.String, TestIssuer, TestIssuer),
new Claim(ClaimTypes.GivenName, "hello world", ClaimValueTypes.String, TestIssuer, TestIssuer),
new Claim(Constants.Security.StartContentNodeIdClaimType, "-1", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
@@ -85,12 +93,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
});
if (UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity, out _))
{
Assert.Fail();
}
Assert.Pass();
}
[Test]
public void Create_With_Claims_And_User_Data()
{
@@ -102,14 +111,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
new Claim("TestClaim1", "test", ClaimValueTypes.Integer32, TestIssuer, TestIssuer)
});
var identity = new UmbracoBackOfficeIdentity(claimsIdentity,
"1234", "testing", "hello world", new[] { 654 }, new[] { 654 }, "en-us", securityStamp, new[] { "content", "media" }, new[] { "admin" });
var identity = new UmbracoBackOfficeIdentity(
claimsIdentity,
"1234",
"testing",
"hello world",
new[] { 654 },
new[] { 654 },
"en-us",
securityStamp,
new[] { "content", "media" },
new[] { "admin" });
Assert.AreEqual(12, identity.Claims.Count());
Assert.IsNull(identity.Actor);
}
[Test]
public void Clone()
{
@@ -121,11 +138,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice
// this will be filtered out during cloning
identity.AddClaim(new Claim(Constants.Security.TicketExpiresClaimType, "test"));
var cloned = identity.Clone();
ClaimsIdentity cloned = identity.Clone();
Assert.IsNull(cloned.Actor);
Assert.AreEqual(10, cloned.Claims.Count());
}
}
}

View File

@@ -1,4 +1,8 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core.Cache;
@@ -14,21 +18,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
[SetUp]
public virtual void Setup()
{
}
[TearDown]
public virtual void TearDown()
{
AppCache.Clear();
}
public virtual void TearDown() => AppCache.Clear();
[Test]
public void Throws_On_Reentry()
{
// don't run for DictionaryAppCache - not making sense
if (GetType() == typeof (DictionaryAppCacheTests))
if (GetType() == typeof(DictionaryAppCacheTests))
{
Assert.Ignore("Do not run for DictionaryAppCache.");
}
Exception exception = null;
var result = AppCache.Get("blah", () =>
@@ -41,6 +43,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
{
exception = e;
}
return "value";
});
Assert.IsNotNull(exception);
@@ -61,7 +64,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
throw new Exception("Do not cache this");
});
}
catch (Exception){}
catch (Exception)
{
}
try
{
@@ -71,10 +76,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
throw new Exception("Do not cache this");
});
}
catch (Exception){}
catch (Exception)
{
}
Assert.Greater(counter, 1);
}
[Test]
@@ -87,17 +93,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
result = AppCache.Get("Blah", () =>
{
counter++;
return "";
return string.Empty;
});
result = AppCache.Get("Blah", () =>
{
counter++;
return "";
return string.Empty;
});
Assert.AreEqual(1, counter);
}
[Test]
@@ -114,7 +119,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
Assert.AreEqual(4, GetTotalItemCount);
var result = AppCache.SearchByKey("Tes");
IEnumerable<object> result = AppCache.SearchByKey("Tes");
Assert.AreEqual(3, result.Count());
}
@@ -228,7 +233,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
Assert.AreEqual(4, GetTotalItemCount);
//Provider.ClearCacheObjectTypes("umbraco.MacroCacheContent");
////Provider.ClearCacheObjectTypes("umbraco.MacroCacheContent");
AppCache.ClearOfType<MacroCacheContent>();
Assert.AreEqual(1, GetTotalItemCount);
@@ -253,7 +258,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
Assert.AreEqual(1, GetTotalItemCount);
}
//just used for these tests
// Just used for these tests
private class MacroCacheContent
{
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
@@ -40,10 +43,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
new TestClone()
};
var val = _provider.GetCacheItem("test", () => original);
DeepCloneableList<TestClone> val = _provider.GetCacheItem("test", () => original);
Assert.AreEqual(original.Count, val.Count);
foreach (var item in val)
foreach (TestClone item in val)
{
Assert.IsTrue(item.IsClone);
}
@@ -84,21 +87,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
{
Debug.Print("get" + i);
if (i < 3)
{
throw new Exception("fail");
}
return "succ" + i;
}
private class TestClass : BeingDirtyBase, IDeepCloneable
{
public TestClass()
{
CloneId = Guid.NewGuid();
}
public TestClass() => CloneId = Guid.NewGuid();
private string _name;
public string Name
{
get => _name;
set => SetPropertyValueAndDetectChanges(value, ref _name, nameof(Name));
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
@@ -29,10 +32,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var isCached = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback(() =>
{
isCached = true;
});
.Callback(() => isCached = true);
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
@@ -58,15 +58,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var cached = new List<string>();
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback((string cacheKey, Func<object> o, TimeSpan? t, bool b, string[] s) =>
{
cached.Add(cacheKey);
});
cache.Setup(x => x.SearchByKey(It.IsAny<string>())).Returns(new AuditItem[] {});
.Callback((string cacheKey, Func<object> o, TimeSpan? t, bool b, string[] s) => cached.Add(cacheKey));
cache.Setup(x => x.SearchByKey(It.IsAny<string>())).Returns(new AuditItem[] { });
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
AuditItem[] unused = defaultPolicy.GetAll(new object[] {}, ids => new[]
AuditItem[] unused = defaultPolicy.GetAll(new object[] { }, ids => new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
@@ -87,7 +84,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
AuditItem[] found = defaultPolicy.GetAll(new object[] {}, ids => new[] { (AuditItem)null });
AuditItem[] found = defaultPolicy.GetAll(new object[] { }, ids => new[] { (AuditItem)null });
Assert.AreEqual(2, found.Length);
}
@@ -97,10 +94,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var cacheCleared = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Clear(It.IsAny<string>()))
.Callback(() =>
{
cacheCleared = true;
});
.Callback(() => cacheCleared = true);
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
try
@@ -109,7 +103,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
}
catch
{
//we need this catch or nunit throw up
// We need this catch or nunit throws up
}
finally
{
@@ -123,10 +117,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var cacheCleared = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Clear(It.IsAny<string>()))
.Callback(() =>
{
cacheCleared = true;
});
.Callback(() => cacheCleared = true);
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
try
@@ -135,7 +126,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
}
catch
{
//we need this catch or nunit throw up
// We need this catch or nunit throws up
}
finally
{

View File

@@ -1,4 +1,7 @@
using NUnit.Framework;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using NUnit.Framework;
using Umbraco.Core.Cache;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
@@ -16,15 +19,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache.DistributedCache
private global::Umbraco.Web.Cache.DistributedCache _distributedCache;
private IServerRegistrar ServerRegistrar { get; set; }
private TestServerMessenger ServerMessenger { get; set; }
[SetUp]
public void Setup()
{
ServerRegistrar = new TestServerRegistrar();
ServerMessenger = new TestServerMessenger();
ServerRegistrar = new TestServerRegistrar();
ServerMessenger = new TestServerMessenger();
var cacheRefresherCollection = new CacheRefresherCollection(new []
var cacheRefresherCollection = new CacheRefresherCollection(new[]
{
new TestCacheRefresher()
});
@@ -51,7 +55,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache.DistributedCache
_distributedCache.Refresh(
Guid.Parse("E0F452CB-DCB2-4E84-B5A5-4F01744C5C73"),
x => x.Id,
new TestObjectWithId{Id = i});
new TestObjectWithId { Id = i });
}
Assert.AreEqual(10, ServerMessenger.IntIdsRefreshed.Count);
@@ -90,8 +94,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache.DistributedCache
Assert.AreEqual(13, ServerMessenger.CountOfFullRefreshes);
}
#region Internal test classes
internal class TestObjectWithId
{
public int Id { get; set; }
@@ -105,18 +107,26 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache.DistributedCache
public string Name => "Test Cache Refresher";
public void RefreshAll() { }
public void RefreshAll()
{
}
public void Refresh(int id) { }
public void Refresh(int id)
{
}
public void Remove(int id) { }
public void Remove(int id)
{
}
public void Refresh(Guid id) { }
public void Refresh(Guid id)
{
}
}
internal class TestServerMessenger : IServerMessenger
{
//used for tests
// Used for tests
public List<int> IntIdsRefreshed = new List<int>();
public List<Guid> GuidIdsRefreshed = new List<Guid>();
public List<int> IntIdsRemoved = new List<int>();
@@ -129,50 +139,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache.DistributedCache
// doing nothing
}
public void PerformRefresh(ICacheRefresher refresher, string jsonPayload)
{
PayloadsRefreshed.Add(jsonPayload);
}
public void PerformRefresh(ICacheRefresher refresher, string jsonPayload) => PayloadsRefreshed.Add(jsonPayload);
public void PerformRefresh<T>(ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances)
{
IntIdsRefreshed.AddRange(instances.Select(getNumericId));
}
public void PerformRefresh<T>(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)
{
GuidIdsRefreshed.AddRange(instances.Select(getGuidId));
}
public void PerformRefresh<T>(ICacheRefresher refresher, Func<T, Guid> getGuidId, params T[] instances) => GuidIdsRefreshed.AddRange(instances.Select(getGuidId));
public void PerformRemove(ICacheRefresher refresher, string jsonPayload)
{
PayloadsRemoved.Add(jsonPayload);
}
public void PerformRemove(ICacheRefresher refresher, string jsonPayload) => PayloadsRemoved.Add(jsonPayload);
public void PerformRemove<T>(ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances)
{
IntIdsRemoved.AddRange(instances.Select(getNumericId));
}
public void PerformRemove<T>(ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances) => IntIdsRemoved.AddRange(instances.Select(getNumericId));
public void PerformRemove(ICacheRefresher refresher, params int[] numericIds)
{
IntIdsRemoved.AddRange(numericIds);
}
public void PerformRemove(ICacheRefresher refresher, params int[] numericIds) => IntIdsRemoved.AddRange(numericIds);
public void PerformRefresh(ICacheRefresher refresher, params int[] numericIds)
{
IntIdsRefreshed.AddRange(numericIds);
}
public void PerformRefresh(ICacheRefresher refresher, params int[] numericIds) => IntIdsRefreshed.AddRange(numericIds);
public void PerformRefresh(ICacheRefresher refresher, params Guid[] guidIds)
{
GuidIdsRefreshed.AddRange(guidIds);
}
public void PerformRefresh(ICacheRefresher refresher, params Guid[] guidIds) => GuidIdsRefreshed.AddRange(guidIds);
public void PerformRefreshAll(ICacheRefresher refresher)
{
CountOfFullRefreshes++;
}
public void PerformRefreshAll(ICacheRefresher refresher) => CountOfFullRefreshes++;
}
internal class TestServerRegistrar : IServerRegistrar
@@ -182,22 +165,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache.DistributedCache
new TestServerAddress("localhost")
};
public ServerRole GetCurrentServerRole()
{
throw new NotImplementedException();
}
public ServerRole GetCurrentServerRole() => throw new NotImplementedException();
}
public class TestServerAddress : IServerAddress
{
public TestServerAddress(string address)
{
ServerAddress = address;
}
public TestServerAddress(string address) => ServerAddress = address;
public string ServerAddress { get; private set; }
}
#endregion
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
@@ -29,7 +32,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
[Test]
public void Caches_Single()
{
var getAll = new[]
AuditItem[] getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
@@ -38,21 +41,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var isCached = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback(() =>
{
isCached = true;
});
.Callback(() => isCached = true);
var policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var unused = policy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), ids => getAll);
AuditItem unused = policy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), ids => getAll);
Assert.IsTrue(isCached);
}
[Test]
public void Get_Single_From_Cache()
{
var getAll = new[]
AuditItem[] getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
@@ -63,14 +63,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var found = defaultPolicy.Get(1, id => null, ids => getAll);
AuditItem found = defaultPolicy.Get(1, id => null, ids => getAll);
Assert.IsNotNull(found);
}
[Test]
public void Get_All_Caches_Empty_List()
{
var getAll = new AuditItem[] {};
var getAll = new AuditItem[] { };
var cached = new List<string>();
@@ -84,20 +84,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
list = o() as IList;
});
cache.Setup(x => x.Get(It.IsAny<string>())).Returns(() =>
{
//return null if this is the first pass
return cached.Any() ? new DeepCloneableList<AuditItem>(ListCloneBehavior.CloneOnce) : null;
});
// Return null if this is the first pass.
cache.Setup(x => x.Get(It.IsAny<string>()))
.Returns(() => cached.Any() ? new DeepCloneableList<AuditItem>(ListCloneBehavior.CloneOnce) : null);
var policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var found = policy.GetAll(new object[] {}, ids => getAll);
AuditItem[] 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!
// Do it again, ensure that its coming from the cache!
policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
found = policy.GetAll(new object[] { }, ids => getAll);
@@ -109,7 +108,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
[Test]
public void Get_All_Caches_As_Single_List()
{
var getAll = new[]
AuditItem[] getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
@@ -130,7 +129,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var found = defaultPolicy.GetAll(new object[] { }, ids => getAll);
AuditItem[] found = defaultPolicy.GetAll(new object[] { }, ids => getAll);
Assert.AreEqual(1, cached.Count);
Assert.IsNotNull(list);
@@ -139,7 +138,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
[Test]
public void Get_All_Without_Ids_From_Cache()
{
var getAll = new[] { (AuditItem)null };
AuditItem[] getAll = new[] { (AuditItem)null };
var cache = new Mock<IAppPolicyCache>();
@@ -151,14 +150,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var found = defaultPolicy.GetAll(new object[] { }, ids => getAll);
AuditItem[] found = defaultPolicy.GetAll(new object[] { }, ids => getAll);
Assert.AreEqual(2, found.Length);
}
[Test]
public void If_CreateOrUpdate_Throws_Cache_Is_Removed()
{
var getAll = new[]
AuditItem[] getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
@@ -167,19 +166,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var cacheCleared = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Clear(It.IsAny<string>()))
.Callback(() =>
{
cacheCleared = true;
});
.Callback(() => cacheCleared = true);
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, 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, AuditType.Copy, 123, "test", "blah"), item => throw new Exception("blah!"));
}
catch
{
//we need this catch or nunit throw up
// We need this catch or nunit throws up.
}
finally
{
@@ -190,7 +186,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
[Test]
public void If_Removes_Throws_Cache_Is_Removed()
{
var getAll = new[]
AuditItem[] getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
@@ -199,19 +195,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var cacheCleared = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Clear(It.IsAny<string>()))
.Callback(() =>
{
cacheCleared = true;
});
.Callback(() => cacheCleared = true);
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, 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, AuditType.Copy, 123, "test", "blah"), item => throw new Exception("blah!"));
}
catch
{
//we need this catch or nunit throw up
// We need this catch or nunit throws up.
}
finally
{

View File

@@ -1,4 +1,7 @@
using Microsoft.AspNetCore.Http;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using Microsoft.AspNetCore.Http;
using NUnit.Framework;
using Umbraco.Core.Cache;
@@ -13,7 +16,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
public override void Setup()
{
base.Setup();
_httpContext = new DefaultHttpContext();;
_httpContext = new DefaultHttpContext();
_appCache = new HttpRequestAppCache(() => _httpContext.Items);
}

View File

@@ -1,4 +1,7 @@
using System.Linq;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Linq;
using NUnit.Framework;
using Umbraco.Core.Cache;
@@ -9,10 +12,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
{
private ObjectCacheAppCache _provider;
protected override int GetTotalItemCount
{
get { return _provider.MemoryCache.Count(); }
}
protected override int GetTotalItemCount => _provider.MemoryCache.Count();
public override void Setup()
{
@@ -20,14 +20,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
_provider = new ObjectCacheAppCache();
}
internal override IAppCache AppCache
{
get { return _provider; }
}
internal override IAppCache AppCache => _provider;
internal override IAppPolicyCache AppPolicyCache
{
get { return _provider; }
}
internal override IAppPolicyCache AppPolicyCache => _provider;
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Services.Changes;
@@ -7,14 +10,14 @@ using Umbraco.Web.Cache;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
{
[TestFixture]
public class RefreshersTests
public class RefresherTests
{
[Test]
public void MediaCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new MediaCacheRefresher.JsonPayload(1234, Guid.NewGuid(), TreeChangeTypes.None) };
MediaCacheRefresher.JsonPayload[] source = new[] { new MediaCacheRefresher.JsonPayload(1234, Guid.NewGuid(), TreeChangeTypes.None) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<MediaCacheRefresher.JsonPayload[]>(json);
MediaCacheRefresher.JsonPayload[] payload = JsonConvert.DeserializeObject<MediaCacheRefresher.JsonPayload[]>(json);
Assert.AreEqual(source[0].Id, payload[0].Id);
Assert.AreEqual(source[0].Key, payload[0].Key);
Assert.AreEqual(source[0].ChangeTypes, payload[0].ChangeTypes);
@@ -23,9 +26,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
[Test]
public void ContentCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new ContentCacheRefresher.JsonPayload(1234, Guid.NewGuid(), TreeChangeTypes.None) };
ContentCacheRefresher.JsonPayload[] source = new[] { new ContentCacheRefresher.JsonPayload(1234, Guid.NewGuid(), TreeChangeTypes.None) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<ContentCacheRefresher.JsonPayload[]>(json);
ContentCacheRefresher.JsonPayload[] payload = JsonConvert.DeserializeObject<ContentCacheRefresher.JsonPayload[]>(json);
Assert.AreEqual(source[0].Id, payload[0].Id);
Assert.AreEqual(source[0].Key, payload[0].Key);
Assert.AreEqual(source[0].ChangeTypes, payload[0].ChangeTypes);
@@ -34,9 +37,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
[Test]
public void ContentTypeCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new ContentTypeCacheRefresher.JsonPayload("xxx", 1234, ContentTypeChangeTypes.None) };
ContentTypeCacheRefresher.JsonPayload[] source = new[] { new ContentTypeCacheRefresher.JsonPayload("xxx", 1234, ContentTypeChangeTypes.None) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<ContentTypeCacheRefresher.JsonPayload[]>(json);
ContentTypeCacheRefresher.JsonPayload[] 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);
@@ -45,9 +48,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
[Test]
public void DataTypeCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new DataTypeCacheRefresher.JsonPayload(1234, Guid.NewGuid(), true) };
DataTypeCacheRefresher.JsonPayload[] source = new[] { new DataTypeCacheRefresher.JsonPayload(1234, Guid.NewGuid(), true) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<DataTypeCacheRefresher.JsonPayload[]>(json);
DataTypeCacheRefresher.JsonPayload[] 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);
@@ -56,9 +59,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
[Test]
public void DomainCacheRefresherCanDeserializeJsonPayload()
{
var source = new[] { new DomainCacheRefresher.JsonPayload(1234, DomainChangeTypes.None) };
DomainCacheRefresher.JsonPayload[] source = new[] { new DomainCacheRefresher.JsonPayload(1234, DomainChangeTypes.None) };
var json = JsonConvert.SerializeObject(source);
var payload = JsonConvert.DeserializeObject<DomainCacheRefresher.JsonPayload[]>(json);
DomainCacheRefresher.JsonPayload[] 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,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Threading;
using NUnit.Framework;
using Umbraco.Core.Cache;
@@ -18,7 +21,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
Assert.AreEqual(now, AppCache.GetCacheItem<DateTime>("DateTimeTest"));
Assert.AreEqual(now, AppCache.GetCacheItem<DateTime?>("DateTimeTest"));
Thread.Sleep(300); //sleep longer than the cache expiration
Thread.Sleep(300); // sleep longer than the cache expiration
Assert.AreEqual(default(DateTime), AppCache.GetCacheItem<DateTime>("DateTimeTest"));
Assert.AreEqual(null, AppCache.GetCacheItem<DateTime?>("DateTimeTest"));

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
@@ -29,15 +32,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var cached = new List<string>();
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback((string cacheKey, Func<object> o, TimeSpan? t, bool b, string[] s) =>
{
cached.Add(cacheKey);
});
.Callback((string cacheKey, Func<object> o, TimeSpan? t, bool b, string[] s) => cached.Add(cacheKey));
cache.Setup(x => x.SearchByKey(It.IsAny<string>())).Returns(new AuditItem[] { });
var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var unused = defaultPolicy.GetAll(new object[] { }, ids => new[]
AuditItem[] unused = defaultPolicy.GetAll(new object[] { }, ids => new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
@@ -52,14 +52,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
var isCached = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback(() =>
{
isCached = true;
});
.Callback(() => isCached = true);
var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var unused = defaultPolicy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), ids => null);
AuditItem unused = defaultPolicy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), ids => null);
Assert.IsTrue(isCached);
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Security.Claims;
using NUnit.Framework;
@@ -27,7 +30,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
public void FindFirstValue_WhenMatchingClaimPresent_ExpectCorrectValue()
{
var expectedClaim = new Claim("test", "123", "string", "Umbraco");
var identity = new ClaimsIdentity(new List<Claim> {expectedClaim});
var identity = new ClaimsIdentity(new List<Claim> { expectedClaim });
var value = identity.FindFirstValue("test");
@@ -39,7 +42,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
{
var expectedClaim = new Claim("test", "123", "string", "Umbraco");
var dupeClaim = new Claim(expectedClaim.Type, Guid.NewGuid().ToString());
var identity = new ClaimsIdentity(new List<Claim> {expectedClaim, dupeClaim});
var identity = new ClaimsIdentity(new List<Claim> { expectedClaim, dupeClaim });
var value = identity.FindFirstValue("test");

View File

@@ -1,4 +1,7 @@
using System.Linq;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Linq;
using NUnit.Framework;
using Umbraco.Core.Collections;
using Umbraco.Tests.Common;
@@ -11,33 +14,35 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Collections
[Test]
public void Deep_Clones_Each_Item_Once()
{
var list = new DeepCloneableList<TestClone>(ListCloneBehavior.CloneOnce);
list.Add(new TestClone());
list.Add(new TestClone());
list.Add(new TestClone());
var list = new DeepCloneableList<TestClone>(ListCloneBehavior.CloneOnce)
{
new TestClone(),
new TestClone(),
new TestClone()
};
var cloned = list.DeepClone() as DeepCloneableList<TestClone>;
//Test that each item in the sequence is equal - based on the equality comparer of TestClone (i.e. it's ID)
// Test that each item in the sequence is equal - based on the equality comparer of TestClone (i.e. it's ID)
Assert.IsTrue(list.SequenceEqual(cloned));
//Test that each instance in the list is not the same one
foreach (var item in list)
// Test that each instance in the list is not the same one
foreach (TestClone item in list)
{
var clone = cloned.Single(x => x.Id == item.Id);
TestClone clone = cloned.Single(x => x.Id == item.Id);
Assert.AreNotSame(item, clone);
}
//clone again from the clone - since it's clone once the items should be the same
// Clone again from the clone - since it's clone once the items should be the same
var cloned2 = cloned.DeepClone() as DeepCloneableList<TestClone>;
//Test that each item in the sequence is equal - based on the equality comparer of TestClone (i.e. it's ID)
// Test that each item in the sequence is equal - based on the equality comparer of TestClone (i.e. it's ID)
Assert.IsTrue(cloned.SequenceEqual(cloned2));
//Test that each instance in the list is the same one
foreach (var item in cloned)
// Test that each instance in the list is the same one
foreach (TestClone item in cloned)
{
var clone = cloned2.Single(x => x.Id == item.Id);
TestClone clone = cloned2.Single(x => x.Id == item.Id);
Assert.AreSame(item, clone);
}
}
@@ -45,10 +50,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Collections
[Test]
public void Deep_Clones_All_Elements()
{
var list = new DeepCloneableList<TestClone>(ListCloneBehavior.Always);
list.Add(new TestClone());
list.Add(new TestClone());
list.Add(new TestClone());
var list = new DeepCloneableList<TestClone>(ListCloneBehavior.Always)
{
new TestClone(),
new TestClone(),
new TestClone()
};
var cloned = list.DeepClone() as DeepCloneableList<TestClone>;
@@ -60,14 +67,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Collections
[Test]
public void Clones_Each_Item()
{
var list = new DeepCloneableList<TestClone>(ListCloneBehavior.Always);
list.Add(new TestClone());
list.Add(new TestClone());
list.Add(new TestClone());
var list = new DeepCloneableList<TestClone>(ListCloneBehavior.Always)
{
new TestClone(),
new TestClone(),
new TestClone()
};
var cloned = (DeepCloneableList<TestClone>) list.DeepClone();
var cloned = (DeepCloneableList<TestClone>)list.DeepClone();
foreach (var item in cloned)
foreach (TestClone item in cloned)
{
Assert.IsTrue(item.IsClone);
}
@@ -76,20 +85,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Collections
[Test]
public void Cloned_Sequence_Equals()
{
var list = new DeepCloneableList<TestClone>(ListCloneBehavior.Always);
list.Add(new TestClone());
list.Add(new TestClone());
list.Add(new TestClone());
var list = new DeepCloneableList<TestClone>(ListCloneBehavior.Always)
{
new TestClone(),
new TestClone(),
new TestClone()
};
var cloned = (DeepCloneableList<TestClone>) list.DeepClone();
var cloned = (DeepCloneableList<TestClone>)list.DeepClone();
//Test that each item in the sequence is equal - based on the equality comparer of TestClone (i.e. it's ID)
// Test that each item in the sequence is equal - based on the equality comparer of TestClone (i.e. it's ID)
Assert.IsTrue(list.SequenceEqual(cloned));
//Test that each instance in the list is not the same one
foreach (var item in list)
// Test that each instance in the list is not the same one
foreach (TestClone item in list)
{
var clone = cloned.Single(x => x.Id == item.Id);
TestClone clone = cloned.Single(x => x.Id == item.Id);
Assert.AreNotSame(item, clone);
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using NUnit.Framework;
using Umbraco.Core.Collections;
@@ -11,8 +14,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Collections
public void Keeps_Last()
{
var list = new OrderedHashSet<MyClass>(keepOldest: false);
var items = new[] {new MyClass("test"), new MyClass("test"), new MyClass("test")};
foreach (var item in items)
MyClass[] items = new[] { new MyClass("test"), new MyClass("test"), new MyClass("test") };
foreach (MyClass item in items)
{
list.Add(item);
}
@@ -26,8 +29,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Collections
public void Keeps_First()
{
var list = new OrderedHashSet<MyClass>(keepOldest: true);
var items = new[] {new MyClass("test"), new MyClass("test"), new MyClass("test")};
foreach (var item in items)
MyClass[] items = new[] { new MyClass("test"), new MyClass("test"), new MyClass("test") };
foreach (MyClass item in items)
{
list.Add(item);
}
@@ -45,37 +48,49 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Collections
}
public string Name { get; }
public Guid Id { get; }
public bool Equals(MyClass other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return string.Equals(Name, other.Name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((MyClass) obj);
if (obj is null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((MyClass)obj);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public override int GetHashCode() => Name.GetHashCode();
public static bool operator ==(MyClass left, MyClass right)
{
return Equals(left, right);
}
public static bool operator ==(MyClass left, MyClass right) => Equals(left, right);
public static bool operator !=(MyClass left, MyClass right)
{
return Equals(left, right) == false;
}
public static bool operator !=(MyClass left, MyClass right) => Equals(left, right) == false;
}
}
}

View File

@@ -1,3 +1,6 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.IO;
@@ -35,16 +38,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
private static IServiceProvider MockFactory(Action<Mock<IServiceProvider>> setup = null)
{
// FIXME: use IUmbracoDatabaseFactory vs UmbracoDatabaseFactory, clean it all up!
var mock = new Mock<IServiceProvider>();
var loggerFactory = NullLoggerFactory.Instance;
var logger = loggerFactory.CreateLogger("GenericLogger");
NullLoggerFactory loggerFactory = NullLoggerFactory.Instance;
ILogger logger = loggerFactory.CreateLogger("GenericLogger");
var globalSettings = new GlobalSettings();
var connectionStrings = new ConnectionStrings();
var f = new UmbracoDatabaseFactory(loggerFactory.CreateLogger<UmbracoDatabaseFactory>(), loggerFactory, Options.Create(globalSettings), Options.Create(connectionStrings), new Lazy<IMapperCollection>(() => new MapperCollection(Enumerable.Empty<BaseMapper>())), TestHelper.DbProviderFactoryCreator);
var fs = new FileSystems(mock.Object, loggerFactory.CreateLogger<FileSystems>(), loggerFactory, IOHelper, Options.Create(globalSettings), Mock.Of<IHostingEnvironment>());
var coreDebug = new CoreDebugSettings();
var mediaFileSystem = Mock.Of<IMediaFileSystem>();
IMediaFileSystem mediaFileSystem = Mock.Of<IMediaFileSystem>();
var p = new ScopeProvider(f, fs, Options.Create(coreDebug), mediaFileSystem, loggerFactory.CreateLogger<ScopeProvider>(), loggerFactory, NoAppCache.Instance);
mock.Setup(x => x.GetService(typeof(ILogger))).Returns(logger);
@@ -58,57 +60,63 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
return mock.Object;
}
private static IServiceCollection MockRegister()
{
// Why mock something you can spin up an instance of?
return new ServiceCollection(); // Mock.Of<IServiceCollection>();
}
private static TypeLoader MockTypeLoader()
{
var ioHelper = IOHelper;
return new TypeLoader(Mock.Of<ITypeFinder>(), Mock.Of<IAppPolicyCache>(), new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of<ILogger<TypeLoader>>(), Mock.Of<IProfilingLogger>());
}
private static IServiceCollection MockRegister() => new ServiceCollection();
private static TypeLoader MockTypeLoader() => new TypeLoader(Mock.Of<ITypeFinder>(), Mock.Of<IAppPolicyCache>(), new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of<ILogger<TypeLoader>>(), Mock.Of<IProfilingLogger>());
[Test]
public void Boot1A()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = TypeArray<Composer1, Composer2, Composer4>();
Type[] types = TypeArray<Composer1, Composer2, Composer4>();
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
// 2 is Core and requires 4
// 3 is User
// => reorder components accordingly
composers.Compose();
AssertTypeArray(TypeArray<Composer1, Composer4, Composer2>(), Composed);
var factory = MockFactory(m =>
IServiceProvider factory = MockFactory(m =>
{
m.Setup(x => x.GetService(It.Is<Type>(t => t == typeof(ISomeResource)))).Returns(() => new SomeResource());
m.Setup(x => x.GetService(It.IsAny<Type>())).Returns<Type>((type) =>
{
if (type == typeof(Composer1))
{
return new Composer1();
}
if (type == typeof(Composer5))
{
return new Composer5();
}
if (type == typeof(Component5))
{
return new Component5(new SomeResource());
}
if (type == typeof(IProfilingLogger))
{
return new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>());
}
if (type == typeof(ILogger<ComponentCollection>))
{
return Mock.Of<ILogger<ComponentCollection>>();
}
throw new NotSupportedException(type.FullName);
});
});
var builder = composition.WithCollectionBuilder<ComponentCollectionBuilder>();
ComponentCollectionBuilder builder = composition.WithCollectionBuilder<ComponentCollectionBuilder>();
builder.RegisterWith(register);
var components = builder.CreateCollection(factory);
ComponentCollection components = builder.CreateCollection(factory);
Assert.IsEmpty(components);
components.Initialize();
@@ -120,12 +128,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void Boot1B()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = TypeArray<Composer1, Composer2, Composer3, Composer4>();
Type[] types = TypeArray<Composer1, Composer2, Composer3, Composer4>();
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
// 2 is Core and requires 4
// 3 is User - stays with RuntimeLevel.Run
// => reorder components accordingly
@@ -136,12 +145,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void Boot2()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = TypeArray<Composer20, Composer21>();
Type[] types = TypeArray<Composer20, Composer21>();
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
// 21 is required by 20
// => reorder components accordingly
composers.Compose();
@@ -151,12 +161,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void Boot3()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = TypeArray<Composer22, Composer24, Composer25>();
Type[] types = TypeArray<Composer22, Composer24, Composer25>();
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
// i23 requires 22
// 24, 25 implement i23
// 25 required by i23
@@ -168,10 +179,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void BrokenRequire()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = TypeArray<Composer1, Composer2, Composer3>();
Type[] types = TypeArray<Composer1, Composer2, Composer3>();
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
try
@@ -191,12 +202,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void BrokenRequired()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = TypeArray<Composer2, Composer4, Composer13>();
Type[] types = TypeArray<Composer2, Composer4, Composer13>();
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
// 2 is Core and requires 4
// 13 is required by 1
// 1 is missing
@@ -212,42 +224,63 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
Initialized.Clear();
Terminated.Clear();
var register = MockRegister();
var typeLoader = MockTypeLoader();
var factory = MockFactory(m =>
IServiceCollection register = MockRegister();
TypeLoader typeLoader = MockTypeLoader();
IServiceProvider factory = MockFactory(m =>
{
m.Setup(x => x.GetService(It.Is<Type>(t => t == typeof(ISomeResource)))).Returns(() => new SomeResource());
m.Setup(x => x.GetService(It.IsAny<Type>())).Returns<Type>((type) =>
{
if (type == typeof(Composer1))
{
return new Composer1();
}
if (type == typeof(Composer5))
{
return new Composer5();
}
if (type == typeof(Composer5a))
{
return new Composer5a();
}
if (type == typeof(Component5))
{
return new Component5(new SomeResource());
}
if (type == typeof(Component5a))
{
return new Component5a();
}
if (type == typeof(IProfilingLogger))
{
return new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>());
}
if (type == typeof(ILogger<ComponentCollection>))
{
return Mock.Of<ILogger<ComponentCollection>>();
}
throw new NotSupportedException(type.FullName);
});
});
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = new[] { typeof(Composer1), typeof(Composer5), typeof(Composer5a) };
Type[] types = new[] { typeof(Composer1), typeof(Composer5), typeof(Composer5a) };
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Assert.IsEmpty(Composed);
composers.Compose();
AssertTypeArray(TypeArray<Composer1, Composer5, Composer5a>(), Composed);
var builder = composition.WithCollectionBuilder<ComponentCollectionBuilder>();
ComponentCollectionBuilder builder = composition.WithCollectionBuilder<ComponentCollectionBuilder>();
builder.RegisterWith(register);
var components = builder.CreateCollection(factory);
ComponentCollection components = builder.CreateCollection(factory);
Assert.IsEmpty(Initialized);
components.Initialize();
@@ -261,10 +294,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void Requires1()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = new[] { typeof(Composer6), typeof(Composer7), typeof(Composer8) };
Type[] types = new[] { typeof(Composer6), typeof(Composer7), typeof(Composer8) };
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
composers.Compose();
@@ -276,10 +309,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void Requires2A()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = new[] { typeof(Composer9), typeof(Composer2), typeof(Composer4) };
Type[] types = new[] { typeof(Composer9), typeof(Composer2), typeof(Composer4) };
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
composers.Compose();
@@ -291,18 +324,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void Requires2B()
{
var register = MockRegister();
var typeLoader = MockTypeLoader();
var factory = MockFactory();
IServiceCollection register = MockRegister();
TypeLoader typeLoader = MockTypeLoader();
IServiceProvider factory = MockFactory();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = new[] { typeof(Composer9), typeof(Composer2), typeof(Composer4) };
Type[] types = new[] { typeof(Composer9), typeof(Composer2), typeof(Composer4) };
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
composers.Compose();
var builder = composition.WithCollectionBuilder<ComponentCollectionBuilder>();
ComponentCollectionBuilder builder = composition.WithCollectionBuilder<ComponentCollectionBuilder>();
builder.RegisterWith(register);
var components = builder.CreateCollection(factory);
ComponentCollection components = builder.CreateCollection(factory);
Assert.AreEqual(3, Composed.Count);
Assert.AreEqual(typeof(Composer4), Composed[0]);
Assert.AreEqual(typeof(Composer2), Composed[1]);
@@ -312,10 +345,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void WeakDependencies()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = new[] { typeof(Composer10) };
Type[] types = new[] { typeof(Composer10) };
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
composers.Compose();
@@ -328,7 +361,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
Assert.Throws<Exception>(() => composers.Compose());
Console.WriteLine("throws:");
composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
var requirements = composers.GetRequirements(false);
Dictionary<Type, List<Type>> requirements = composers.GetRequirements(false);
Console.WriteLine(Composers.GetComposersReport(requirements));
types = new[] { typeof(Composer2) };
@@ -351,10 +384,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void DisableMissing()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = new[] { typeof(Composer6), typeof(Composer8) }; // 8 disables 7 which is not in the list
Type[] types = new[] { typeof(Composer6), typeof(Composer8) }; // 8 disables 7 which is not in the list
var composers = new Composers(composition, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
Composed.Clear();
composers.Compose();
@@ -366,11 +399,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void AttributesPriorities()
{
var register = MockRegister();
IServiceCollection register = MockRegister();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var types = new[] { typeof(Composer26) };
var enableDisableAttributes = new[] { new DisableComposerAttribute(typeof(Composer26)) };
Type[] types = new[] { typeof(Composer26) };
DisableComposerAttribute[] enableDisableAttributes = new[] { new DisableComposerAttribute(typeof(Composer26)) };
var composers = new Composers(composition, types, enableDisableAttributes, Mock.Of<ILogger<Composers>>());
Composed.Clear();
composers.Compose();
@@ -388,47 +421,47 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
[Test]
public void AllComposers()
{
var typeFinder = TestHelper.GetTypeFinder();
ITypeFinder typeFinder = TestHelper.GetTypeFinder();
var typeLoader = new TypeLoader(typeFinder, AppCaches.Disabled.RuntimeCache, new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of<ILogger<TypeLoader>>(), Mock.Of<IProfilingLogger>());
var register = MockRegister();
IServiceCollection register = MockRegister();
var builder = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var allComposers = typeLoader.GetTypes<IComposer>().ToList();
var types = allComposers.Where(x => x.FullName.StartsWith("Umbraco.Core.") || x.FullName.StartsWith("Umbraco.Web")).ToList();
var composers = new Composers(builder, types, Enumerable.Empty<Attribute>(), Mock.Of<ILogger<Composers>>());
var requirements = composers.GetRequirements();
var report = Composers.GetComposersReport(requirements);
Dictionary<Type, List<Type>> requirements = composers.GetRequirements();
string report = Composers.GetComposersReport(requirements);
Console.WriteLine(report);
var composerTypes = composers.SortComposers(requirements);
IEnumerable<Type> composerTypes = composers.SortComposers(requirements);
foreach (var type in composerTypes)
Console.WriteLine(type);
}
#region Compothings
public class TestComposerBase : IComposer
{
public virtual void Compose(IUmbracoBuilder builder)
foreach (Type type in composerTypes)
{
Composed.Add(GetType());
Console.WriteLine(type);
}
}
public class TestComposerBase : IComposer
{
public virtual void Compose(IUmbracoBuilder builder) => Composed.Add(GetType());
}
public class Composer1 : TestComposerBase
{ }
{
}
[ComposeAfter(typeof(Composer4))]
public class Composer2 : TestComposerBase, ICoreComposer
{ }
{
}
public class Composer3 : TestComposerBase, IUserComposer
{ }
{
}
public class Composer4 : TestComposerBase
{ }
{
}
public class Composer5 : TestComposerBase
{
@@ -451,151 +484,135 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
public class TestComponentBase : IComponent
{
public virtual void Initialize()
{
Initialized.Add(GetType());
}
public virtual void Initialize() => Initialized.Add(GetType());
public virtual void Terminate()
{
Terminated.Add(GetType());
}
public virtual void Terminate() => Terminated.Add(GetType());
}
public class Component5 : TestComponentBase
{
private readonly ISomeResource _resource;
public Component5(ISomeResource resource)
{
_resource = resource;
}
public Component5(ISomeResource resource) => _resource = resource;
}
public class Component5a : TestComponentBase
{ }
{
}
[Disable]
public class Composer6 : TestComposerBase
{ }
{
}
public class Composer7 : TestComposerBase
{ }
{
}
[Disable(typeof(Composer7))]
[Enable(typeof(Composer6))]
public class Composer8 : TestComposerBase
{ }
{
}
public interface ITestComposer : IUserComposer
{ }
{
}
public class Composer9 : TestComposerBase, ITestComposer
{ }
{
}
[ComposeAfter(typeof(ITestComposer))]
public class Composer10 : TestComposerBase
{ }
{
}
[ComposeAfter(typeof(ITestComposer), false)]
public class Composer11 : TestComposerBase
{ }
{
}
[ComposeAfter(typeof(Composer4), true)]
public class Composer12 : TestComposerBase, ICoreComposer
{ }
{
}
[ComposeBefore(typeof(Composer1))]
public class Composer13 : TestComposerBase
{ }
{
}
public interface ISomeResource { }
public interface ISomeResource
{
}
public class SomeResource : ISomeResource { }
public class SomeResource : ISomeResource
{
}
public class Composer20 : TestComposerBase
{ }
{
}
[ComposeBefore(typeof(Composer20))]
public class Composer21 : TestComposerBase
{ }
{
}
public class Composer22 : TestComposerBase
{ }
{
}
[ComposeAfter(typeof(Composer22))]
public interface IComposer23 : IComposer
{ }
{
}
public class Composer24 : TestComposerBase, IComposer23
{ }
{
}
// should insert itself between 22 and anything i23
[ComposeBefore(typeof(IComposer23))]
//[RequireComponent(typeof(Component22))] - not needed, implement i23
////[RequireComponent(typeof(Component22))] - not needed, implement i23
public class Composer25 : TestComposerBase, IComposer23
{ }
{
}
public class Composer26 : TestComposerBase
{ }
{
}
[Enable(typeof(Composer26))]
public class Composer27 : TestComposerBase
{ }
#endregion
#region TypeArray
{
}
// FIXME: move to Testing
private static Type[] TypeArray<T1>() => new[] { typeof(T1) };
private static Type[] TypeArray<T1>()
{
return new[] { typeof(T1) };
}
private static Type[] TypeArray<T1, T2>() => new[] { typeof(T1), typeof(T2) };
private static Type[] TypeArray<T1, T2>()
{
return new[] { typeof(T1), typeof(T2) };
}
private static Type[] TypeArray<T1, T2, T3>() => new[] { typeof(T1), typeof(T2), typeof(T3) };
private static Type[] TypeArray<T1, T2, T3>()
{
return new[] { typeof(T1), typeof(T2), typeof(T3) };
}
private static Type[] TypeArray<T1, T2, T3, T4>() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) };
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>() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) };
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>() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) };
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>() => 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>()
{
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 Type[] TypeArray<T1, T2, T3, T4, T5, T6, T7, T8>() => 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++)
for (int i = 0; i < expected.Count; i++)
{
Assert.AreEqual(expected[i], test[i]);
}
}
#endregion
}
}

View File

@@ -1,3 +1,6 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
@@ -20,7 +23,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
[SetUp]
public void Setup()
{
var register = TestHelper.GetServiceCollection();
IServiceCollection register = TestHelper.GetServiceCollection();
_composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
}
@@ -32,24 +35,24 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
[Test]
public void ContainsTypes()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<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
//// Assert.IsFalse(col.ContainsType<Resolved4>()); // does not compile
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CanClearBuilderBeforeCollectionIsCreated()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
@@ -57,20 +60,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsFalse(builder.Has<Resolved1>());
Assert.IsFalse(builder.Has<Resolved2>());
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col);
}
[Test]
public void CannotClearBuilderOnceCollectionIsCreated()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() => builder.Clear());
}
@@ -78,7 +81,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
[Test]
public void CanAppendToBuilder()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
builder.Append<Resolved1>();
builder.Append<Resolved2>();
@@ -86,52 +89,48 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsFalse(builder.Has<Resolved3>());
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CannotAppendToBuilderOnceCollectionIsCreated()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() =>
builder.Append<Resolved1>()
);
Assert.Throws<InvalidOperationException>(() => builder.Append<Resolved1>());
}
[Test]
public void CanAppendDuplicateToBuilderAndDeDuplicate()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
builder.Append<Resolved1>();
builder.Append<Resolved1>();
var factory = _composition.CreateServiceProvider();
IServiceProvider factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1));
}
[Test]
public void CannotAppendInvalidTypeToBUilder()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
//builder.Append<Resolved4>(); // does not compile
Assert.Throws<InvalidOperationException>(() =>
builder.Append(new[] { typeof(Resolved4) }) // throws
);
////builder.Append<Resolved4>(); // does not compile
Assert.Throws<InvalidOperationException>(() => builder.Append(new[] { typeof(Resolved4) }));
}
[Test]
public void CanRemoveFromBuilder()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Remove<Resolved2>();
@@ -140,42 +139,40 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsFalse(builder.Has<Resolved2>());
Assert.IsFalse(builder.Has<Resolved3>());
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1));
}
[Test]
public void CanRemoveMissingFromBuilder()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Remove<Resolved3>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CannotRemoveFromBuilderOnceCollectionIsCreated()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() =>
builder.Remove<Resolved2>() // throws
);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() => builder.Remove<Resolved2>());
}
[Test]
public void CanInsertIntoBuilder()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Insert<Resolved3>();
@@ -184,69 +181,63 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved3), typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CannotInsertIntoBuilderOnceCollectionIsCreated()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() =>
builder.Insert<Resolved3>() // throws
);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() => builder.Insert<Resolved3>());
}
[Test]
public void CanInsertDuplicateIntoBuilderAndDeDuplicate()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Insert<Resolved2>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved2), typeof(Resolved1));
}
[Test]
public void CanInsertIntoEmptyBuilder()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
builder.Insert<Resolved2>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved2));
}
[Test]
public void CannotInsertIntoBuilderAtWrongIndex()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
Assert.Throws<ArgumentOutOfRangeException>(() =>
builder.Insert<Resolved3>(99) // throws
);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert<Resolved3>(99));
Assert.Throws<ArgumentOutOfRangeException>(() =>
builder.Insert<Resolved3>(-1) // throws
);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert<Resolved3>(-1));
}
[Test]
public void CanInsertIntoBuilderBefore()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertBefore<Resolved2, Resolved3>();
@@ -255,15 +246,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved3), typeof(Resolved2));
}
[Test]
public void CanInsertIntoBuilderAfter()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertAfter<Resolved1, Resolved3>();
@@ -272,15 +263,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved3), typeof(Resolved2));
}
[Test]
public void CanInsertIntoBuilderAfterLast()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertAfter<Resolved2, Resolved3>();
@@ -289,47 +280,45 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved2), typeof(Resolved3));
}
[Test]
public void CannotInsertIntoBuilderBeforeOnceCollectionIsCreated()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() =>
builder.InsertBefore<Resolved2, Resolved3>()
);
builder.InsertBefore<Resolved2, Resolved3>());
}
[Test]
public void CanInsertDuplicateIntoBuilderBeforeAndDeDuplicate()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertBefore<Resolved1, Resolved2>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved2), typeof(Resolved1));
}
[Test]
public void CannotInsertIntoBuilderBeforeMissing()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>();
Assert.Throws<InvalidOperationException>(() =>
builder.InsertBefore<Resolved2, Resolved3>()
);
builder.InsertBefore<Resolved2, Resolved3>());
}
[Test]
@@ -341,21 +330,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
// 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
// the collection must come from the container.
IServiceProvider factory = _composition.CreateServiceProvider();
var factory = _composition.CreateServiceProvider();
using (var scope = factory.CreateScope())
using (IServiceScope scope = factory.CreateScope())
{
var col1 = scope.ServiceProvider.GetRequiredService<TestCollection>();
TestCollection col1 = scope.ServiceProvider.GetRequiredService<TestCollection>();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2));
var col2 = scope.ServiceProvider.GetRequiredService<TestCollection>();
TestCollection col2 = scope.ServiceProvider.GetRequiredService<TestCollection>();
AssertCollection(col2, typeof(Resolved1), typeof(Resolved2));
AssertSameCollection(scope.ServiceProvider, col1, col2);
}
}
[Test]
@@ -367,14 +354,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
// 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
// the collection must come from the container.
IServiceProvider factory = _composition.CreateServiceProvider();
var factory = _composition.CreateServiceProvider();
var col1 = factory.GetRequiredService<TestCollection>();
TestCollection col1 = factory.GetRequiredService<TestCollection>();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2));
var col2 = factory.GetRequiredService<TestCollection>();
TestCollection col2 = factory.GetRequiredService<TestCollection>();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2));
AssertNotSameCollection(col1, col2);
@@ -383,13 +369,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
[Test]
public void BuilderRespectsTypesOrder()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilderTransient>()
TestCollectionBuilderTransient builder = _composition.WithCollectionBuilder<TestCollectionBuilderTransient>()
.Append<Resolved3>()
.Insert<Resolved1>()
.InsertBefore<Resolved3, Resolved2>();
var factory = _composition.CreateServiceProvider();
var col1 = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col1 = builder.CreateCollection(factory);
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2), typeof(Resolved3));
}
@@ -402,13 +388,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
// 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
// the collection must come from the container/
IServiceProvider serviceProvider = _composition.CreateServiceProvider();
TestCollection col1A, col1B;
var serviceProvider = _composition.CreateServiceProvider();
using (var scope = serviceProvider.CreateScope())
using (IServiceScope scope = serviceProvider.CreateScope())
{
col1A = scope.ServiceProvider.GetRequiredService<TestCollection>();
col1B = scope.ServiceProvider.GetRequiredService<TestCollection>();
@@ -420,7 +404,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
TestCollection col2;
using (var scope = serviceProvider.CreateScope())
using (IServiceScope scope = serviceProvider.CreateScope())
{
col2 = scope.ServiceProvider.GetRequiredService<TestCollection>();
}
@@ -432,43 +416,43 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
[Test]
public void WeightedBuilderCreatesWeightedCollection()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilderWeighted>()
TestCollectionBuilderWeighted builder = _composition.WithCollectionBuilder<TestCollectionBuilderWeighted>()
.Add<Resolved1>()
.Add<Resolved2>();
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved2), typeof(Resolved1));
}
#region Assertions
private static void AssertCollection(IEnumerable<Resolved> col, params Type[] expected)
{
var colA = col.ToArray();
Resolved[] colA = col.ToArray();
Assert.AreEqual(expected.Length, colA.Length);
for (var i = 0; i < expected.Length; i++)
for (int i = 0; i < expected.Length; i++)
{
Assert.IsInstanceOf(expected[i], colA[i]);
}
}
private static void AssertSameCollection(IServiceProvider factory, IEnumerable<Resolved> col1, IEnumerable<Resolved> col2)
{
Assert.AreSame(col1, col2);
var col1A = col1.ToArray();
var col2A = col2.ToArray();
Resolved[] col1A = col1.ToArray();
Resolved[] col2A = col2.ToArray();
Assert.AreEqual(col1A.Length, col2A.Length);
// Ensure each item in each collection is the same but also
// resolve each item from the factory to ensure it's also the same since
// it should have the same lifespan.
for (var i = 0; i < col1A.Length; i++)
for (int i = 0; i < col1A.Length; i++)
{
Assert.AreSame(col1A[i], col2A[i]);
var itemA = factory.GetRequiredService(col1A[i].GetType());
var itemB = factory.GetRequiredService(col2A[i].GetType());
object itemA = factory.GetRequiredService(col1A[i].GetType());
object itemB = factory.GetRequiredService(col2A[i].GetType());
Assert.AreSame(itemA, itemB);
}
@@ -478,36 +462,37 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
{
Assert.AreNotSame(col1, col2);
var col1A = col1.ToArray();
var col2A = col2.ToArray();
Resolved[] col1A = col1.ToArray();
Resolved[] col2A = col2.ToArray();
Assert.AreEqual(col1A.Length, col2A.Length);
for (var i = 0; i < col1A.Length; i++)
for (int 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(50)] // default is 100
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>
@@ -542,9 +527,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
{
public TestCollection(IEnumerable<Resolved> items)
: base(items)
{ }
{
}
}
#endregion
}
}

View File

@@ -1,3 +1,6 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Collections.Generic;
using System.IO;
using System.Reflection;

View File

@@ -1,10 +1,12 @@
using NUnit.Framework;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using NUnit.Framework;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
{
[TestFixture]
public class CompositionTests
{
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
@@ -6,118 +9,113 @@ using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Core.DependencyInjection;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.UnitTests.TestHelpers;
using Umbraco.Core.DependencyInjection;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
{
/// <summary>
/// Tests for lazy collection builder.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[TestFixture]
public class LazyCollectionBuilderTests
{
private IServiceCollection CreateRegister()
{
return TestHelper.GetServiceCollection();
}
// 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
private IServiceCollection CreateRegister() => TestHelper.GetServiceCollection();
[Test]
public void LazyCollectionBuilderHandlesTypes()
{
var container = CreateRegister();
IServiceCollection container = CreateRegister();
var composition = new UmbracoBuilder(container, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
composition.WithCollectionBuilder<TestCollectionBuilder>()
.Add<TransientObject3>()
.Add<TransientObject2>()
.Add<TransientObject3>()
.Add<TransientObject1>();
var factory = composition.CreateServiceProvider();
IServiceProvider factory = composition.CreateServiceProvider();
var values = factory.GetRequiredService<TestCollection>();
TestCollection values = factory.GetRequiredService<TestCollection>();
Assert.AreEqual(3, values.Count());
Assert.IsTrue(values.Select(x => x.GetType())
.ContainsAll(new[] { typeof(TransientObject1), typeof(TransientObject2), typeof(TransientObject3) }));
var other = factory.GetRequiredService<TestCollection>();
TestCollection other = factory.GetRequiredService<TestCollection>();
Assert.AreNotSame(values, other); // transient
var o1 = other.FirstOrDefault(x => x is TransientObject1);
ITestInterface o1 = other.FirstOrDefault(x => x is TransientObject1);
Assert.IsFalse(values.Contains(o1)); // transient
}
[Test]
public void LazyCollectionBuilderHandlesProducers()
{
var container = CreateRegister();
IServiceCollection container = CreateRegister();
var composition = new UmbracoBuilder(container, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
composition.WithCollectionBuilder<TestCollectionBuilder>()
.Add(() => new[] { typeof(TransientObject3), typeof(TransientObject2) })
.Add(() => new[] { typeof(TransientObject3), typeof(TransientObject2) })
.Add(() => new[] { typeof(TransientObject1) });
var factory = composition.CreateServiceProvider();
IServiceProvider factory = composition.CreateServiceProvider();
var values = factory.GetRequiredService<TestCollection>();
TestCollection values = factory.GetRequiredService<TestCollection>();
Assert.AreEqual(3, values.Count());
Assert.IsTrue(values.Select(x => x.GetType())
.ContainsAll(new[] { typeof(TransientObject1), typeof(TransientObject2), typeof(TransientObject3) }));
var other = factory.GetRequiredService<TestCollection>();
TestCollection other = factory.GetRequiredService<TestCollection>();
Assert.AreNotSame(values, other); // transient
var o1 = other.FirstOrDefault(x => x is TransientObject1);
ITestInterface o1 = other.FirstOrDefault(x => x is TransientObject1);
Assert.IsFalse(values.Contains(o1)); // transient
}
[Test]
public void LazyCollectionBuilderHandlesTypesAndProducers()
{
var container = CreateRegister();
IServiceCollection container = CreateRegister();
var composition = new UmbracoBuilder(container, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
composition.WithCollectionBuilder<TestCollectionBuilder>()
.Add<TransientObject3>()
.Add<TransientObject2>()
.Add<TransientObject3>()
.Add(() => new[] { typeof(TransientObject1) });
var factory = composition.CreateServiceProvider();
IServiceProvider factory = composition.CreateServiceProvider();
var values = factory.GetRequiredService<TestCollection>();
TestCollection values = factory.GetRequiredService<TestCollection>();
Assert.AreEqual(3, values.Count());
Assert.IsTrue(values.Select(x => x.GetType())
.ContainsAll(new[] { typeof(TransientObject1), typeof(TransientObject2), typeof(TransientObject3) }));
var other = factory.GetRequiredService<TestCollection>();
TestCollection other = factory.GetRequiredService<TestCollection>();
Assert.AreNotSame(values, other); // transient
var o1 = other.FirstOrDefault(x => x is TransientObject1);
ITestInterface o1 = other.FirstOrDefault(x => x is TransientObject1);
Assert.IsFalse(values.Contains(o1)); // transient
}
[Test]
public void LazyCollectionBuilderThrowsOnIllegalTypes()
{
var container = CreateRegister();
IServiceCollection container = CreateRegister();
var composition = new UmbracoBuilder(container, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
composition.WithCollectionBuilder<TestCollectionBuilder>()
.Add<TransientObject3>()
// illegal, does not implement the interface!
//.Add<TransientObject4>()
////.Add<TransientObject4>()
// legal so far...
.Add(() => new[] { typeof(TransientObject4) });
@@ -125,14 +123,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.Throws<InvalidOperationException>(() =>
{
// but throws here when trying to register the types, right before creating the factory
var factory = composition.CreateServiceProvider();
IServiceProvider factory = composition.CreateServiceProvider();
});
}
[Test]
public void LazyCollectionBuilderCanExcludeTypes()
{
var container = CreateRegister();
IServiceCollection container = CreateRegister();
var composition = new UmbracoBuilder(container, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
composition.WithCollectionBuilder<TestCollectionBuilder>()
@@ -140,9 +138,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
.Add(() => new[] { typeof(TransientObject3), typeof(TransientObject2), typeof(TransientObject1) })
.Exclude<TransientObject3>();
var factory = composition.CreateServiceProvider();
IServiceProvider factory = composition.CreateServiceProvider();
var values = factory.GetRequiredService<TestCollection>();
TestCollection values = factory.GetRequiredService<TestCollection>();
Assert.AreEqual(2, values.Count());
Assert.IsFalse(values.Select(x => x.GetType())
@@ -150,28 +148,31 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsTrue(values.Select(x => x.GetType())
.ContainsAll(new[] { typeof(TransientObject1), typeof(TransientObject2) }));
var other = factory.GetRequiredService<TestCollection>();
TestCollection other = factory.GetRequiredService<TestCollection>();
Assert.AreNotSame(values, other); // transient
var o1 = other.FirstOrDefault(x => x is TransientObject1);
ITestInterface 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>
@@ -186,9 +187,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
{
public TestCollection(IEnumerable<ITestInterface> items)
: base(items)
{ }
{
}
}
#endregion
}
}

View File

@@ -1,4 +1,8 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
@@ -7,13 +11,11 @@ using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Core.DependencyInjection;
using Umbraco.Core.PackageActions;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.UnitTests.TestHelpers;
using Umbraco.Core.DependencyInjection;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
{
@@ -23,76 +25,47 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
[Test]
public void PackageActionCollectionBuilderWorks()
{
var container = TestHelper.GetServiceCollection();
IServiceCollection container = TestHelper.GetServiceCollection();
var composition = new UmbracoBuilder(container, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
var expectedPackageActions = TypeLoader.GetPackageActions();
IEnumerable<Type> expectedPackageActions = TypeLoader.GetPackageActions();
composition.WithCollectionBuilder<PackageActionCollectionBuilder>()
.Add(() => expectedPackageActions);
var factory = composition.CreateServiceProvider();
IServiceProvider factory = composition.CreateServiceProvider();
var actions = factory.GetRequiredService<PackageActionCollection>();
PackageActionCollection actions = factory.GetRequiredService<PackageActionCollection>();
Assert.AreEqual(2, actions.Count());
// order is unspecified, but both must be there
var hasAction1 = actions.ElementAt(0) is PackageAction1 || actions.ElementAt(1) is PackageAction1;
var hasAction2 = actions.ElementAt(0) is PackageAction2 || actions.ElementAt(1) is PackageAction2;
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, XElement xmlData)
{
throw new NotImplementedException();
}
public bool Execute(string packageName, XElement xmlData) => throw new NotImplementedException();
public string Alias()
{
return "pa1";
}
public string Alias() => "pa1";
public bool Undo(string packageName, XElement xmlData)
{
throw new NotImplementedException();
}
public bool Undo(string packageName, XElement xmlData) => throw new NotImplementedException();
public XmlNode SampleXml()
{
throw new NotImplementedException();
}
public XmlNode SampleXml() => throw new NotImplementedException();
}
public class PackageAction2 : IPackageAction
{
public bool Execute(string packageName, XElement xmlData)
{
throw new NotImplementedException();
}
public bool Execute(string packageName, XElement xmlData) => throw new NotImplementedException();
public string Alias()
{
return "pa2";
}
public string Alias() => "pa2";
public bool Undo(string packageName, XElement xmlData)
{
throw new NotImplementedException();
}
public bool Undo(string packageName, XElement xmlData) => throw new NotImplementedException();
public XmlNode SampleXml()
{
throw new NotImplementedException();
}
public XmlNode SampleXml() => throw new NotImplementedException();
}
#endregion
}
}

View File

@@ -1,17 +1,18 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Tests.TestHelpers.Stubs;
using Umbraco.Web.BackOffice.Trees;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
{
/// <summary>
/// Tests for typefinder
/// </summary>
@@ -24,11 +25,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
private Assembly[] _assemblies;
[SetUp]
public void Initialize()
{
_assemblies = new[]
public void Initialize() => _assemblies = new[]
{
this.GetType().Assembly,
GetType().Assembly,
typeof(System.Guid).Assembly,
typeof(NUnit.Framework.Assert).Assembly,
typeof(System.Xml.NameTable).Assembly,
@@ -36,13 +35,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
typeof(TypeFinder).Assembly,
};
}
[Test]
public void Find_Class_Of_Type_With_Attribute()
{
var typeFinder = new TypeFinder(Mock.Of<ILogger<TypeFinder>>(), new DefaultUmbracoAssemblyProvider(GetType().Assembly), new VaryingRuntimeHash());
var typesFound = typeFinder.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies);
IEnumerable<Type> typesFound = typeFinder.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies);
Assert.AreEqual(2, typesFound.Count());
}
@@ -50,10 +47,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
public void Find_Classes_With_Attribute()
{
var typeFinder = new TypeFinder(Mock.Of<ILogger<TypeFinder>>(), new DefaultUmbracoAssemblyProvider(GetType().Assembly), new VaryingRuntimeHash());
var typesFound = typeFinder.FindClassesWithAttribute<TreeAttribute>(_assemblies);
IEnumerable<Type> typesFound = typeFinder.FindClassesWithAttribute<TreeAttribute>(_assemblies);
Assert.AreEqual(0, typesFound.Count()); // 0 classes in _assemblies are marked with [Tree]
typesFound = typeFinder.FindClassesWithAttribute<TreeAttribute>(new[] { typeof (TreeAttribute).Assembly });
typesFound = typeFinder.FindClassesWithAttribute<TreeAttribute>(new[] { typeof(TreeAttribute).Assembly });
Assert.AreEqual(22, typesFound.Count()); // + classes in Umbraco.Web are marked with [Tree]
typesFound = typeFinder.FindClassesWithAttribute<TreeAttribute>();
@@ -63,27 +60,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class MyTestAttribute : Attribute
{
}
public abstract class TestEditor
{
}
[MyTest]
public class BenchmarkTestEditor : TestEditor
{
}
[MyTest]
public class MyOtherTestEditor : TestEditor
{
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Odbc;
@@ -7,6 +10,7 @@ using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Composing;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
@@ -17,19 +21,29 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
[TestFixture]
public class TypeHelperTests
{
private class Base<T>
{
}
private interface IBase<T>
{
}
class Base<T> { }
private interface IDerived<T> : IBase<T>
{
}
interface IBase<T> { }
private class Derived<T> : Base<T>, IBase<T>
{
}
interface IDerived<T> : IBase<T> { }
private class Derived2<T> : Derived<T>
{
}
class Derived<T> : Base<T>, IBase<T> { }
class Derived2<T> : Derived<T> { }
class DerivedI<T> : IDerived<T> { }
private class DerivedI<T> : IDerived<T>
{
}
[Test]
public void Is_Static_Class()
@@ -41,44 +55,41 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
[Test]
public void Find_Common_Base_Class()
{
var t1 = TypeHelper.GetLowestBaseType(typeof (OleDbCommand),
typeof (OdbcCommand),
typeof (SqlCommand));
Attempt<Type> t1 = TypeHelper.GetLowestBaseType(
typeof(OleDbCommand),
typeof(OdbcCommand),
typeof(SqlCommand));
Assert.IsFalse(t1.Success);
var t2 = TypeHelper.GetLowestBaseType(typeof (OleDbCommand),
typeof (OdbcCommand),
typeof (SqlCommand),
typeof (Component));
Attempt<Type> t2 = TypeHelper.GetLowestBaseType(
typeof(OleDbCommand),
typeof(OdbcCommand),
typeof(SqlCommand),
typeof(Component));
Assert.IsTrue(t2.Success);
Assert.AreEqual(typeof(Component), t2.Result);
var t3 = TypeHelper.GetLowestBaseType(typeof (OleDbCommand),
typeof (OdbcCommand),
typeof (SqlCommand),
typeof (Component),
typeof (Component).BaseType);
Attempt<Type> t3 = TypeHelper.GetLowestBaseType(
typeof(OleDbCommand),
typeof(OdbcCommand),
typeof(SqlCommand),
typeof(Component),
typeof(Component).BaseType);
Assert.IsTrue(t3.Success);
Assert.AreEqual(typeof(MarshalByRefObject), t3.Result);
var t4 = TypeHelper.GetLowestBaseType(typeof(OleDbCommand),
typeof(OdbcCommand),
typeof(SqlCommand),
typeof(Component),
typeof(Component).BaseType,
typeof(int));
Attempt<Type> t4 = TypeHelper.GetLowestBaseType(
typeof(OleDbCommand),
typeof(OdbcCommand),
typeof(SqlCommand),
typeof(Component),
typeof(Component).BaseType,
typeof(int));
Assert.IsFalse(t4.Success);
var t5 = TypeHelper.GetLowestBaseType(typeof(PropertyAliasDto));
Attempt<Type> t5 = TypeHelper.GetLowestBaseType(typeof(PropertyAliasDto));
Assert.IsTrue(t5.Success);
Assert.AreEqual(typeof(PropertyAliasDto), t5.Result);
//var t6 = TypeHelper.GetLowestBaseType(typeof (IApplicationEventHandler),
// typeof (SchedulerComponent),
// typeof(CacheRefresherComponent));
//Assert.IsTrue(t6.Success);
//Assert.AreEqual(typeof(IApplicationEventHandler), t6.Result);
}
[Test]
@@ -96,10 +107,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsTrue(TypeHelper.MatchType(typeof(List<int>), typeof(System.Collections.IEnumerable), bindings));
Assert.AreEqual(0, bindings.Count);
var t1 = typeof(IList<>); // IList<>
var a1 = t1.GetGenericArguments()[0]; // <T>
Type t1 = typeof(IList<>); // IList<>
Type a1 = t1.GetGenericArguments()[0]; // <T>
t1 = t1.MakeGenericType(a1); // IList<T>
var t2 = a1;
Type t2 = a1;
bindings = new Dictionary<string, Type>();
Assert.IsTrue(TypeHelper.MatchType(typeof(int), t2, bindings));
@@ -145,12 +156,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
// both are OK
Assert.IsTrue(TypeHelper.MatchType(typeof(List<int>), typeof(IEnumerable<>)));
var t1 = typeof (IDictionary<,>); // IDictionary<,>
var a1 = t1.GetGenericArguments()[0];
Type t1 = typeof(IDictionary<,>); // IDictionary<,>
Type a1 = t1.GetGenericArguments()[0];
t1 = t1.MakeGenericType(a1, a1); // IDictionary<T,T>
// both are OK
Assert.IsTrue(TypeHelper.MatchType(typeof(Dictionary<int, int>), t1));
Assert.IsFalse(TypeHelper.MatchType(typeof(Dictionary<int, string>), t1));
@@ -164,7 +174,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsTrue(TypeHelper.MatchType(typeof(Derived2<int>), typeof(IBase<>)));
Assert.IsTrue(TypeHelper.MatchType(typeof(int?), typeof(Nullable<>)));
Assert.IsTrue(TypeHelper.MatchType(typeof(Derived<int>), typeof(object)));
Assert.IsFalse(TypeHelper.MatchType(typeof(Derived<int>), typeof(List<>)));
Assert.IsFalse(TypeHelper.MatchType(typeof(Derived<int>), typeof(IEnumerable<>)));
@@ -172,21 +181,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.IsTrue(TypeHelper.MatchType(typeof(List<int>), typeof(IEnumerable<int>)));
Assert.IsFalse(TypeHelper.MatchType(typeof(int), typeof(Nullable<>)));
//This get's the "Type" from the Count extension method on IEnumerable<T>, however the type IEnumerable<T> isn't
// This get's the "Type" from the Count extension method on IEnumerable<T>, however the type IEnumerable<T> isn't
// IEnumerable<> and it is not a generic definition, this attempts to explain that:
// http://blogs.msdn.com/b/haibo_luo/archive/2006/02/17/534480.aspx
var genericEnumerableNonGenericDefinition = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
Type genericEnumerableNonGenericDefinition = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
.Single(x => x.Name == "Count" && x.GetParameters().Count() == 1)
.GetParameters()
.Single()
.ParameterType;
Assert.IsTrue(TypeHelper.MatchType(typeof(List<int>), genericEnumerableNonGenericDefinition));
}
[Test]
public void CreateOpenGenericTypes()
{
@@ -198,7 +204,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
// assembly; or null if the current instance represents a generic type parameter, an array type, pointer
// type, or byref type based on a type parameter, or a generic type that is not a generic type definition
// but contains unresolved type parameters."
var t = Type.GetType("System.Collections.Generic.IList`1");
Assert.IsNotNull(t);
Assert.IsTrue(t.IsGenericTypeDefinition);
@@ -206,7 +211,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
Assert.AreEqual("System.Collections.Generic.IList`1", t.FullName);
Assert.AreEqual("System.Collections.Generic.IList`1[T]", t.ToString());
t = typeof (IList<>);
t = typeof(IList<>);
Assert.IsTrue(t.IsGenericTypeDefinition);
Assert.AreEqual("IList`1", t.Name);
Assert.AreEqual("System.Collections.Generic.IList`1", t.FullName);
@@ -241,7 +246,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
t = typeof(IList<int>);
Assert.AreEqual("System.Collections.Generic.IList`1[System.Int32]", t.ToString());
t = typeof (IDictionary<,>);
t = typeof(IDictionary<,>);
t = t.MakeGenericType(typeof(int), t.GetGenericArguments()[1]);
Assert.IsFalse(t.IsGenericTypeDefinition); // not anymore
Assert.AreEqual("IDictionary`2", t.Name);

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using Umbraco.Core.Composing;

View File

@@ -1,11 +1,14 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
@@ -26,28 +29,30 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
public void Initialize()
{
// this ensures it's reset
var typeFinder = TestHelper.GetTypeFinder();
_typeLoader = new TypeLoader(typeFinder, NoAppCache.Instance,
new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)),
Mock.Of<ILogger<TypeLoader>>(), new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>()), false,
ITypeFinder typeFinder = TestHelper.GetTypeFinder();
// 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
new[]
// 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
Assembly[] assemblies = new[]
{
this.GetType().Assembly,
typeof(System.Guid).Assembly,
typeof(NUnit.Framework.Assert).Assembly,
GetType().Assembly,
typeof(Guid).Assembly,
typeof(Assert).Assembly,
typeof(System.Xml.NameTable).Assembly,
typeof(System.Configuration.GenericEnumConverter).Assembly,
//typeof(TabPage).Assembly,
////typeof(TabPage).Assembly,
typeof(TypeFinder).Assembly,
typeof(UmbracoContext).Assembly,
typeof(CheckBoxListPropertyEditor).Assembly
});
};
_typeLoader = new TypeLoader(
typeFinder,
NoAppCache.Instance,
new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)),
Mock.Of<ILogger<TypeLoader>>(),
new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>()),
false,
assemblies);
}
[TearDown]
@@ -55,106 +60,108 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
{
_typeLoader = null;
// cleanup
var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
var tlDir = Path.Combine(assDir.FullName, "TypeLoader");
DirectoryInfo assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
string tlDir = Path.Combine(assDir.FullName, "TypeLoader");
if (!Directory.Exists(tlDir))
{
return;
}
Directory.Delete(tlDir, true);
}
private DirectoryInfo PrepareFolder()
{
var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
var tlDir = Path.Combine(assDir.FullName, "TypeLoader");
var dir = Directory.CreateDirectory(Path.Combine(tlDir, Guid.NewGuid().ToString("N")));
DirectoryInfo assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
string tlDir = Path.Combine(assDir.FullName, "TypeLoader");
DirectoryInfo dir = Directory.CreateDirectory(Path.Combine(tlDir, Guid.NewGuid().ToString("N")));
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);
//}
////[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);
//}
//////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);
string filePath = _typeLoader.GetTypesListFilePath();
string fileDir = Path.GetDirectoryName(filePath);
Directory.CreateDirectory(fileDir);
File.WriteAllText(filePath, @"<?xml version=""1.0"" encoding=""utf-8""?>
@@ -192,35 +199,41 @@ AnotherContentFinder
[Test]
public void Create_Cached_Plugin_File()
{
var types = new[] { typeof(TypeLoader), typeof(TypeLoaderTests), typeof(IUmbracoContext) };
Type[] types = new[] { typeof(TypeLoader), typeof(TypeLoaderTests), typeof(IUmbracoContext) };
var typeList1 = new TypeLoader.TypeList(typeof(object), null);
foreach (var type in types) typeList1.Add(type);
foreach (Type 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));
Attempt<IEnumerable<string>> plugins = _typeLoader.TryGetCached(typeof(object), null);
Attempt<IEnumerable<string>> 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
// 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
IEnumerable<string> shouldContain = types.Select(x => x.AssemblyQualifiedName);
// Ensure they are all found
Assert.IsTrue(plugins.Result.ContainsAll(shouldContain));
}
[Test]
public void Get_Plugins_Hash_With_Hash_Generator()
{
//Arrange
var dir = PrepareFolder();
var d1 = dir.CreateSubdirectory("1");
var d2 = dir.CreateSubdirectory("2");
var d3 = dir.CreateSubdirectory("3");
var d4 = dir.CreateSubdirectory("4");
// Arrange
DirectoryInfo dir = PrepareFolder();
DirectoryInfo d1 = dir.CreateSubdirectory("1");
DirectoryInfo d2 = dir.CreateSubdirectory("2");
DirectoryInfo d3 = dir.CreateSubdirectory("3");
DirectoryInfo 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"));
@@ -235,16 +248,16 @@ AnotherContentFinder
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 };
FileInfo[] list1 = new[] { f1, f2, f3, f4, f5, f6 };
FileInfo[] list2 = new[] { f1, f3, f5 };
FileInfo[] list3 = new[] { f1, f3, f5, f7 };
//Act
var hash1 = GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>()));
var hash2 = GetFileHash(list2, new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>()));
var hash3 = GetFileHash(list3, new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>()));
// Act
string hash1 = GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>()));
string hash2 = GetFileHash(list2, new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>()));
string hash3 = GetFileHash(list3, new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>()));
//Assert
// Assert
Assert.AreNotEqual(hash1, hash2);
Assert.AreNotEqual(hash1, hash3);
Assert.AreNotEqual(hash2, hash3);
@@ -263,14 +276,14 @@ AnotherContentFinder
[Test]
public void Resolves_Types()
{
var foundTypes1 = _typeLoader.ResolveFindMeTypes();
IEnumerable<Type> foundTypes1 = _typeLoader.ResolveFindMeTypes();
Assert.AreEqual(2, foundTypes1.Count());
}
[Test]
public void GetDataEditors()
{
var types = _typeLoader.GetDataEditors();
IEnumerable<Type> types = _typeLoader.GetDataEditors();
Assert.AreEqual(39, types.Count());
}
@@ -287,32 +300,28 @@ AnotherContentFinder
propEditors.Add(typeof(LabelPropertyEditor));
types.Add(propEditors);
var found = types.SingleOrDefault(x => x.BaseType == typeof(DataEditor) && x.AttributeType == null);
TypeLoader.TypeList 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);
// This should not find a type list of this type
TypeLoader.TypeList 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
{
}
/// <summary>
/// Returns a unique hash for a combination of FileInfo objects.
/// </summary>
@@ -324,19 +333,23 @@ AnotherContentFinder
{
using (logger.DebugDuration<TypeLoader>("Determining hash of code files on disk", "Hash determined"))
{
using (var generator = new HashGenerator())
{
// get the distinct file infos to hash
var uniqInfos = new HashSet<string>();
using var generator = new HashGenerator();
foreach (var fileOrFolder in filesAndFolders)
// Get the distinct file infos to hash.
var uniqInfos = new HashSet<string>();
foreach (FileSystemInfo fileOrFolder in filesAndFolders)
{
if (uniqInfos.Contains(fileOrFolder.FullName))
{
if (uniqInfos.Contains(fileOrFolder.FullName)) continue;
uniqInfos.Add(fileOrFolder.FullName);
generator.AddFileSystemItem(fileOrFolder);
continue;
}
return generator.GenerateHash();
uniqInfos.Add(fileOrFolder.FullName);
generator.AddFileSystemItem(fileOrFolder);
}
return generator.GenerateHash();
}
}
}

View File

@@ -1,4 +1,7 @@
using AutoFixture.NUnit3;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using AutoFixture.NUnit3;
using Microsoft.Extensions.Options;
using NUnit.Framework;
using Umbraco.Core.Configuration;
@@ -6,8 +9,7 @@ using Umbraco.Core.Configuration.Models;
using Umbraco.Tests.UnitTests.AutoFixture;
using Umbraco.Web.Common.AspNetCore;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Configurations
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Configuration.Models
{
[TestFixture]
public class GlobalSettingsTests

View File

@@ -9,7 +9,7 @@ using Umbraco.Core.Configuration.Models.Validation;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Configuration.Models.Validation
{
[TestFixture]
public class GlobalSettingsValidationTests
public class GlobalSettingsValidatorTests
{
[Test]
public void Returns_Success_ForValid_Configuration()

View File

@@ -11,7 +11,7 @@ using Umbraco.Core.Configuration.Models.Validation;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Configuration.Models.Validation
{
[TestFixture]
public class HealthChecksSettingsValidationTests
public class HealthChecksSettingsValidatorTests
{
[Test]
public void Returns_Success_ForValid_Configuration()

View File

@@ -1,7 +1,10 @@
using NUnit.Framework;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using NUnit.Framework;
using Umbraco.Core.Configuration;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Configurations
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Configuration
{
[TestFixture]
public class NCronTabParserTests

View File

@@ -1,5 +1,7 @@
using NUnit.Framework;
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Scoping;
@@ -8,39 +10,27 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[TestFixture]
public class CallContextTests
{
private static bool _first;
private static bool s_first;
static CallContextTests()
{
SafeCallContext.Register(() =>
{
CallContext<string>.SetData("test1", null);
CallContext<string>.SetData("test2", null);
return null;
}, o => { });
}
static CallContextTests() => SafeCallContext.Register(
() =>
{
CallContext<string>.SetData("test1", null);
CallContext<string>.SetData("test2", null);
return null;
}, o => { });
[OneTimeSetUp]
public void SetUpFixture()
{
_first = true;
}
public void SetUpFixture() => s_first = true;
// logical call context leaks between tests
// is is required to clear it before tests begin
// (don't trust other tests properly tearing down)
[SetUp]
public void Setup()
{
SafeCallContext.Clear();
}
public void Setup() => SafeCallContext.Clear();
[TearDown]
public void TearDown()
{
SafeCallContext.Clear();
}
public void TearDown() => SafeCallContext.Clear();
[Test]
public void Test1()
@@ -50,9 +40,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
CallContext<string>.SetData("test3b", "test3b");
if (_first)
if (s_first)
{
_first = false;
s_first = false;
}
else
{
@@ -72,9 +62,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
{
CallContext<string>.SetData("test3a", "test3a");
if (_first)
if (s_first)
{
_first = false;
s_first = false;
}
else
{

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
@@ -23,16 +26,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
}
[TearDown]
public void TestTearDown()
{
Thread.CurrentThread.CurrentCulture = _savedCulture;
}
public void TestTearDown() => Thread.CurrentThread.CurrentCulture = _savedCulture;
[Test]
public void Can_Convert_List_To_Enumerable()
{
var list = new List<string> {"hello", "world", "awesome"};
var result = list.TryConvertTo<IEnumerable<string>>();
var list = new List<string> { "hello", "world", "awesome" };
Attempt<IEnumerable<string>> result = list.TryConvertTo<IEnumerable<string>>();
Assert.IsTrue(result.Success);
Assert.AreEqual(3, result.Result.Count());
}
@@ -40,16 +40,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void ObjectExtensions_Object_To_Dictionary()
{
//Arrange
// Arrange
var obj = new { Key1 = "value1", Key2 = "value2", Key3 = "value3" };
//Act
var d = obj.ToDictionary<string>();
//Assert
// Act
IDictionary<string, string> d = obj.ToDictionary<string>();
// Assert
Assert.IsTrue(d.Keys.Contains("Key1"));
Assert.IsTrue(d.Keys.Contains("Key2"));
Assert.IsTrue(d.Keys.Contains("Key3"));
@@ -61,8 +58,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void CanConvertIntToNullableInt()
{
var i = 1;
var result = i.TryConvertTo<int?>();
int i = 1;
Attempt<int?> result = i.TryConvertTo<int?>();
Assert.That(result.Success, Is.True);
}
@@ -70,7 +67,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
public void CanConvertNullableIntToInt()
{
int? i = 1;
var result = i.TryConvertTo<int>();
Attempt<int> result = i.TryConvertTo<int>();
Assert.That(result.Success, Is.True);
}
@@ -79,20 +76,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
{
var testCases = new Dictionary<string, bool>
{
{"TRUE", true},
{"True", true},
{"true", true},
{"1", true},
{"FALSE", false},
{"False", false},
{"false", false},
{"0", false},
{"", false}
{ "TRUE", true },
{ "True", true },
{ "true", true },
{ "1", true },
{ "FALSE", false },
{ "False", false },
{ "false", false },
{ "0", false },
{ string.Empty, false }
};
foreach (var testCase in testCases)
foreach (KeyValuePair<string, bool> testCase in testCases)
{
var result = testCase.Key.TryConvertTo<bool>();
Attempt<bool> result = testCase.Key.TryConvertTo<bool>();
Assert.IsTrue(result.Success, testCase.Key);
Assert.AreEqual(testCase.Value, result.Result, testCase.Key);
@@ -113,7 +110,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
{
var dateTime = new DateTime(2012, 11, 10, 13, 14, 15);
var result = date.TryConvertTo<DateTime>();
Attempt<DateTime> result = date.TryConvertTo<DateTime>();
Assert.IsTrue(result.Success, date);
Assert.AreEqual(DateTime.Equals(dateTime.Date, result.Result.Date), outcome, date);
@@ -122,7 +119,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public virtual void CanConvertBlankStringToNullDateTime()
{
var result = "".TryConvertTo<DateTime?>();
Attempt<DateTime?> result = string.Empty.TryConvertTo<DateTime?>();
Assert.IsTrue(result.Success);
Assert.IsNull(result.Result);
}
@@ -130,7 +127,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public virtual void CanConvertBlankStringToNullBool()
{
var result = "".TryConvertTo<bool?>();
Attempt<bool?> result = string.Empty.TryConvertTo<bool?>();
Assert.IsTrue(result.Success);
Assert.IsNull(result.Result);
}
@@ -138,7 +135,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public virtual void CanConvertBlankStringToDateTime()
{
var result = "".TryConvertTo<DateTime>();
Attempt<DateTime> result = string.Empty.TryConvertTo<DateTime>();
Assert.IsTrue(result.Success);
Assert.AreEqual(DateTime.MinValue, result.Result);
}
@@ -146,7 +143,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public virtual void CanConvertObjectToString_Using_ToString_Overload()
{
var result = new MyTestObject().TryConvertTo<string>();
Attempt<string> result = new MyTestObject().TryConvertTo<string>();
Assert.IsTrue(result.Success);
Assert.AreEqual("Hello world", result.Result);
@@ -156,7 +153,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
public virtual void CanConvertObjectToSameObject()
{
var obj = new MyTestObject();
var result = obj.TryConvertTo<object>();
Attempt<object> result = obj.TryConvertTo<object>();
Assert.AreEqual(obj, result.Result);
}
@@ -164,7 +161,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void ConvertToIntegerTest()
{
var conv = "100".TryConvertTo<int>();
Attempt<int> conv = "100".TryConvertTo<int>();
Assert.IsTrue(conv);
Assert.AreEqual(100, conv.Result);
@@ -198,7 +195,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void ConvertToDecimalTest()
{
var conv = "100".TryConvertTo<decimal>();
Attempt<decimal> conv = "100".TryConvertTo<decimal>();
Assert.IsTrue(conv);
Assert.AreEqual(100m, conv.Result);
@@ -234,7 +231,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void ConvertToNullableDecimalTest()
{
var conv = "100".TryConvertTo<decimal?>();
Attempt<decimal?> conv = "100".TryConvertTo<decimal?>();
Assert.IsTrue(conv);
Assert.AreEqual(100m, conv.Result);
@@ -270,7 +267,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void ConvertToDateTimeTest()
{
var conv = "2016-06-07".TryConvertTo<DateTime>();
Attempt<DateTime> conv = "2016-06-07".TryConvertTo<DateTime>();
Assert.IsTrue(conv);
Assert.AreEqual(new DateTime(2016, 6, 7), conv.Result);
}
@@ -278,7 +275,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void ConvertToNullableDateTimeTest()
{
var conv = "2016-06-07".TryConvertTo<DateTime?>();
Attempt<DateTime?> conv = "2016-06-07".TryConvertTo<DateTime?>();
Assert.IsTrue(conv);
Assert.AreEqual(new DateTime(2016, 6, 7), conv.Result);
}
@@ -286,19 +283,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void Value_Editor_Can_Convert_Decimal_To_Decimal_Clr_Type()
{
var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal);
DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal);
var result = valueEditor.TryConvertValueToCrlType(12.34d);
Attempt<object> result = valueEditor.TryConvertValueToCrlType(12.34d);
Assert.IsTrue(result.Success);
Assert.AreEqual(12.34d, result.Result);
}
private class MyTestObject
{
public override string ToString()
{
return "Hello world";
}
public override string ToString() => "Hello world";
}
}
}

View File

@@ -1,11 +1,9 @@
using System;
using Microsoft.Extensions.Options;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Strings;
using Umbraco.Tests.Testing;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
{

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
@@ -14,10 +17,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
public class UdiTests
{
[SetUp]
public void SetUp()
{
UdiParser.ResetUdiTypes();
}
public void SetUp() => UdiParser.ResetUdiTypes();
[Test]
public void StringUdiCtorTest()
@@ -31,7 +31,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void StringUdiParseTest()
{
var udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/test-id");
Udi udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/test-id");
Assert.AreEqual(Constants.UdiEntityType.AnyString, udi.EntityType);
Assert.IsInstanceOf<StringUdi>(udi);
var stringEntityId = udi as StringUdi;
@@ -56,7 +56,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
Assert.AreEqual("%2Fthis%20is%20a%20test", Uri.EscapeDataString("/this is a test"));
Assert.AreEqual("/this%20is%20a%20test", Uri.EscapeUriString("/this is a test"));
var udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test");
Udi udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test");
Assert.AreEqual(Constants.UdiEntityType.AnyString, udi.EntityType);
Assert.IsInstanceOf<StringUdi>(udi);
var stringEntityId = udi as StringUdi;
@@ -76,13 +76,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
{
// reserved = : / ? # [ ] @ ! $ & ' ( ) * + , ; =
// unreserved = alpha digit - . _ ~
Assert.AreEqual("%3A%2F%3F%23%5B%5D%40%21%24%26%27%28%29%2B%2C%3B%3D.-_~%25", Uri.EscapeDataString(":/?#[]@!$&'()+,;=.-_~%"));
Assert.AreEqual(":/?#[]@!$&'()+,;=.-_~%25", Uri.EscapeUriString(":/?#[]@!$&'()+,;=.-_~%"));
// we cannot have reserved chars at random places
// we want to keep the / in string udis
var r = string.Join("/", "path/to/View[1].cshtml".Split('/').Select(Uri.EscapeDataString));
Assert.AreEqual("path/to/View%5B1%5D.cshtml", r);
Assert.IsTrue(Uri.IsWellFormedUriString("umb://partial-view-macro/" + r, UriKind.Absolute));
@@ -90,8 +88,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
// with the proper fix in StringUdi this should work:
var udi1 = new StringUdi("partial-view-macro", "path/to/View[1].cshtml");
Assert.AreEqual("umb://partial-view-macro/path/to/View%5B1%5D.cshtml", udi1.ToString());
var udi2 = UdiParser.Parse("umb://partial-view-macro/path/to/View%5B1%5D.cshtml");
Assert.AreEqual("path/to/View[1].cshtml", ((StringUdi) udi2).Id);
Udi udi2 = UdiParser.Parse("umb://partial-view-macro/path/to/View%5B1%5D.cshtml");
Assert.AreEqual("path/to/View[1].cshtml", ((StringUdi)udi2).Id);
}
[Test]
@@ -109,7 +107,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
{
var guid = Guid.NewGuid();
var s = "umb://" + Constants.UdiEntityType.AnyGuid + "/" + guid.ToString("N");
var udi = UdiParser.Parse(s);
Udi udi = UdiParser.Parse(s);
Assert.AreEqual(Constants.UdiEntityType.AnyGuid, udi.EntityType);
Assert.IsInstanceOf<GuidUdi>(udi);
var gudi = udi as GuidUdi;
@@ -127,8 +125,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
Assert.IsTrue(new GuidUdi("type", guid1).Equals(new GuidUdi("type", guid1)));
Assert.IsTrue(new GuidUdi("type", guid1) == new GuidUdi("type", guid1));
Assert.IsTrue(((Udi)new GuidUdi("type", guid1)).Equals((Udi)new GuidUdi("type", guid1)));
Assert.IsTrue((Udi)new GuidUdi("type", guid1) == (Udi)new GuidUdi("type", guid1));
Assert.IsTrue(new GuidUdi("type", guid1).Equals(new GuidUdi("type", guid1)));
Assert.IsTrue(new GuidUdi("type", guid1) == new GuidUdi("type", guid1));
Assert.IsFalse(new GuidUdi("type", guid1).Equals(new GuidUdi("typex", guid1)));
Assert.IsFalse(new GuidUdi("type", guid1) == new GuidUdi("typex", guid1));
@@ -143,7 +141,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
public void DistinctTest()
{
var guid1 = Guid.NewGuid();
var entities = new[]
GuidUdi[] entities = new[]
{
new GuidUdi(Constants.UdiEntityType.AnyGuid, guid1),
new GuidUdi(Constants.UdiEntityType.AnyGuid, guid1),
@@ -160,7 +158,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
Assert.AreEqual(Constants.UdiEntityType.AnyGuid, udi.EntityType);
Assert.AreEqual(guid, ((GuidUdi)udi).Guid);
// *not* testing whether Udi.Create(type, invalidValue) throws
// because we don't throw anymore - see U4-10409
}
@@ -176,7 +173,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
Assert.IsTrue(guidUdi.IsRoot);
Assert.AreEqual("umb://any-guid/00000000000000000000000000000000", guidUdi.ToString());
var udi = UdiParser.Parse("umb://any-string/");
Udi udi = UdiParser.Parse("umb://any-string/");
Assert.IsTrue(udi.IsRoot);
Assert.IsInstanceOf<StringUdi>(udi);
@@ -194,14 +191,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
{
// can parse open string udi
var stringUdiString = "umb://" + Constants.UdiEntityType.AnyString;
Udi stringUdi;
Assert.IsTrue(UdiParser.TryParse(stringUdiString, out stringUdi));
Assert.IsTrue(UdiParser.TryParse(stringUdiString, out Udi stringUdi));
Assert.AreEqual(string.Empty, ((StringUdi)stringUdi).Id);
// can parse open guid udi
var guidUdiString = "umb://" + Constants.UdiEntityType.AnyGuid;
Udi guidUdi;
Assert.IsTrue(UdiParser.TryParse(guidUdiString, out guidUdi));
Assert.IsTrue(UdiParser.TryParse(guidUdiString, out Udi guidUdi));
Assert.AreEqual(Guid.Empty, ((GuidUdi)guidUdi).Guid);
// can create a range
@@ -219,13 +214,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
Converters = new JsonConverter[] { new UdiJsonConverter(), new UdiRangeJsonConverter() }
};
var guid = Guid.NewGuid();
var udi = new GuidUdi(Constants.UdiEntityType.AnyGuid, guid);
var json = JsonConvert.SerializeObject(udi, settings);
Assert.AreEqual(string.Format("\"umb://any-guid/{0:N}\"", guid), json);
var dudi = JsonConvert.DeserializeObject<Udi>(json, settings);
Udi dudi = JsonConvert.DeserializeObject<Udi>(json, settings);
Assert.AreEqual(Constants.UdiEntityType.AnyGuid, dudi.EntityType);
Assert.AreEqual(guid, ((GuidUdi)dudi).Guid);
@@ -233,7 +227,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
json = JsonConvert.SerializeObject(range, settings);
Assert.AreEqual(string.Format("\"umb://any-guid/{0:N}?children\"", guid), json);
var drange = JsonConvert.DeserializeObject<UdiRange>(json, settings);
UdiRange drange = JsonConvert.DeserializeObject<UdiRange>(json, settings);
Assert.AreEqual(udi, drange.Udi);
Assert.AreEqual(string.Format("umb://any-guid/{0:N}", guid), drange.Udi.UriValue.ToString());
Assert.AreEqual(Constants.DeploySelector.ChildrenOfThis, drange.Selector);
@@ -242,9 +236,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void ValidateUdiEntityType()
{
var types = UdiParser.GetKnownUdiTypes();
Dictionary<string, UdiType> types = UdiParser.GetKnownUdiTypes();
foreach (var fi in typeof(Constants.UdiEntityType).GetFields(BindingFlags.Public | BindingFlags.Static))
foreach (FieldInfo fi in typeof(Constants.UdiEntityType).GetFields(BindingFlags.Public | BindingFlags.Static))
{
// IsLiteral determines if its value is written at
// compile time and not changeable
@@ -257,7 +251,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
var value = fi.GetValue(null).ToString();
if (types.ContainsKey(value) == false)
{
Assert.Fail("Error in class Constants.UdiEntityType, type \"{0}\" is not declared by GetTypes.", value);
}
types.Remove(value);
}
}
@@ -268,11 +265,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
[Test]
public void KnownTypes()
{
Udi udi;
// cannot parse an unknown type, udi is null
// this will scan
Assert.IsFalse(UdiParser.TryParse("umb://whatever/1234", out udi));
Assert.IsFalse(UdiParser.TryParse("umb://whatever/1234", out Udi udi));
Assert.IsNull(udi);
UdiParser.ResetUdiTypes();
@@ -299,52 +294,28 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings
Assert.IsInstanceOf<GuidUdi>(udi);
// can get method for Deploy compatibility
var method = typeof(UdiParser).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string), typeof(bool) }, null);
MethodInfo method = typeof(UdiParser).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string), typeof(bool) }, null);
Assert.IsNotNull(method);
}
[UdiDefinition("foo", UdiType.GuidUdi)]
public class FooConnector : IServiceConnector
{
public IArtifact GetArtifact(Udi udi)
{
throw new NotImplementedException();
}
public IArtifact GetArtifact(Udi udi) => throw new NotImplementedException();
public IArtifact GetArtifact(object entity)
{
throw new NotImplementedException();
}
public IArtifact GetArtifact(object entity) => throw new NotImplementedException();
public ArtifactDeployState ProcessInit(IArtifact art, IDeployContext context)
{
throw new NotImplementedException();
}
public ArtifactDeployState ProcessInit(IArtifact art, IDeployContext context) => throw new NotImplementedException();
public void Process(ArtifactDeployState dart, IDeployContext context, int pass)
{
throw new NotImplementedException();
}
public void Process(ArtifactDeployState dart, IDeployContext context, int pass) => throw new NotImplementedException();
public void Explode(UdiRange range, List<Udi> udis)
{
throw new NotImplementedException();
}
public void Explode(UdiRange range, List<Udi> udis) => throw new NotImplementedException();
public NamedUdiRange GetRange(Udi udi, string selector)
{
throw new NotImplementedException();
}
public NamedUdiRange GetRange(Udi udi, string selector) => throw new NotImplementedException();
public NamedUdiRange GetRange(string entityType, string sid, string selector)
{
throw new NotImplementedException();
}
public NamedUdiRange GetRange(string entityType, string sid, string selector) => throw new NotImplementedException();
public bool Compare(IArtifact art1, IArtifact art2, ICollection<Difference> differences = null)
{
throw new NotImplementedException();
}
public bool Compare(IArtifact art1, IArtifact art2, ICollection<Difference> differences = null) => throw new NotImplementedException();
}
}
}

View File

@@ -1,10 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Xml;
using System.Xml.XPath;
using NUnit.Framework;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
@@ -12,7 +10,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
[TestFixture]
public class FrameworkXmlTests
{
const string Xml1 = @"<root>
private const string Xml1 = @"<root>
<items>
<item1 />
<item2>
@@ -27,31 +25,29 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
</items>
</root>";
// Umbraco : the following test shows that when legacy imports the whole tree in a
// "contentAll" xslt macro parameter, the entire collection of nodes is cloned ie is
// duplicated.
//
// What is the impact on memory?
// What happens for non-xslt macros?
[Test]
public void ImportNodeClonesImportedNode()
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
var node1 = doc1.SelectSingleNode("//item2");
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
var doc2 = new XmlDocument();
doc2.LoadXml("<nodes />");
var node2 = doc2.ImportNode(node1, true);
var root2 = doc2.DocumentElement;
XmlNode node2 = doc2.ImportNode(node1, true);
XmlElement root2 = doc2.DocumentElement;
Assert.IsNotNull(root2);
root2.AppendChild(node2);
var node3 = doc2.SelectSingleNode("//item2");
XmlNode node3 = doc2.SelectSingleNode("//item2");
Assert.AreNotSame(node1, node2); // has been cloned
Assert.AreSame(node2, node3); // has been appended
@@ -59,19 +55,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
Assert.AreNotSame(node1.FirstChild, node2.FirstChild); // deep clone
}
// Umbraco: the CanRemove...NodeAndNavigate tests shows that if the underlying XmlDocument
// is modified while navigating, then strange situations can be created. For xslt macros,
// the result depends on what the xslt engine is doing at the moment = unpredictable.
//
// What happens for non-xslt macros?
[Test]
public void CanRemoveCurrentNodeAndNavigate()
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
var nav1 = doc1.CreateNavigator();
XPathNavigator nav1 = doc1.CreateNavigator();
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("root", nav1.Name);
@@ -82,15 +76,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
Assert.IsTrue(nav1.MoveToNext());
Assert.AreEqual("item2", nav1.Name);
var node1 = doc1.SelectSingleNode("//item2");
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
var parent1 = node1.ParentNode;
XmlNode parent1 = node1.ParentNode;
Assert.IsNotNull(parent1);
parent1.RemoveChild(node1);
// navigator now navigates on an isolated fragment
// that is rooted on the node that was removed
Assert.AreEqual("item2", nav1.Name);
Assert.IsFalse(nav1.MoveToPrevious());
Assert.IsFalse(nav1.MoveToNext());
@@ -110,7 +103,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
var nav1 = doc1.CreateNavigator();
XPathNavigator nav1 = doc1.CreateNavigator();
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("root", nav1.Name);
@@ -123,15 +116,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("item21", nav1.Name);
var node1 = doc1.SelectSingleNode("//item2");
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
var parent1 = node1.ParentNode;
XmlNode parent1 = node1.ParentNode;
Assert.IsNotNull(parent1);
parent1.RemoveChild(node1);
// navigator now navigates on an isolated fragment
// that is rooted on the node that was removed
Assert.AreEqual("item21", nav1.Name);
Assert.IsTrue(nav1.MoveToParent());
Assert.AreEqual("item2", nav1.Name);
@@ -148,7 +140,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
var nav1 = doc1.CreateNavigator();
XPathNavigator nav1 = doc1.CreateNavigator();
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("root", nav1.Name);
@@ -163,14 +155,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
Assert.IsTrue(nav1.MoveToNext());
Assert.AreEqual("item4", nav1.Name);
var node1 = doc1.SelectSingleNode("//item2");
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
var parent1 = node1.ParentNode;
XmlNode parent1 = node1.ParentNode;
Assert.IsNotNull(parent1);
parent1.RemoveChild(node1);
// navigator sees the change
Assert.AreEqual("item4", nav1.Name);
Assert.IsTrue(nav1.MoveToPrevious());
Assert.AreEqual("item3", nav1.Name);
@@ -183,33 +174,33 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
// on what the xslt engine is doing at the moment = unpredictable.
//
// What happens for non-xslt macros?
[Test]
public void CanRemoveNodeAndIterate()
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
var nav1 = doc1.CreateNavigator();
XPathNavigator nav1 = doc1.CreateNavigator();
var iter1 = nav1.Select("//items/*");
var iter2 = nav1.Select("//items/*");
XPathNodeIterator iter1 = nav1.Select("//items/*");
XPathNodeIterator iter2 = nav1.Select("//items/*");
Assert.AreEqual(6, iter1.Count);
var node1 = doc1.SelectSingleNode("//item2");
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
var parent1 = node1.ParentNode;
XmlNode parent1 = node1.ParentNode;
Assert.IsNotNull(parent1);
parent1.RemoveChild(node1);
// iterator partially sees the change
Assert.AreEqual(6, iter1.Count); // has been cached, not updated
Assert.AreEqual(5, iter2.Count); // not calculated yet, correct value
var count = 0;
int count = 0;
while (iter1.MoveNext())
{
count++;
}
Assert.AreEqual(5, count);
}
@@ -218,22 +209,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
public void OldFrameworkXPathBugIsFixed()
{
// see http://bytes.com/topic/net/answers/177129-reusing-xpathexpression-multiple-iterations
var doc = new XmlDocument();
doc.LoadXml("<root><a><a1/><a2/></a><b/></root>");
var nav = doc.CreateNavigator();
var expr = nav.Compile("*");
XPathNavigator nav = doc.CreateNavigator();
XPathExpression expr = nav.Compile("*");
nav.MoveToFirstChild(); //root
var iter1 = nav.Select(expr);
iter1.MoveNext(); //root/a
var iter2 = iter1.Current.Select(expr);
nav.MoveToFirstChild(); // root
XPathNodeIterator iter1 = nav.Select(expr);
iter1.MoveNext(); // root/a
XPathNodeIterator iter2 = iter1.Current.Select(expr);
iter2.MoveNext(); // /root/a/a1
iter2.MoveNext(); // /root/a/a2
// used to fail because iter1 and iter2 would conflict
Assert.IsTrue(iter1.MoveNext()); //root/b
Assert.IsTrue(iter1.MoveNext()); // root/b
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
@@ -7,9 +10,9 @@ using System.Net;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using NUnit.Framework;
using Umbraco.Core.Xml;
using Umbraco.Core.Xml.XPath;
using NUnit.Framework;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
{
@@ -20,8 +23,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
public void NewNavigatorIsAtRoot()
{
const string xml = @"<root><item1 /><item2 /></root>";
var doc = XmlHelper.CreateXPathDocument(xml);
var nav = doc.CreateNavigator();
XPathDocument doc = XmlHelper.CreateXPathDocument(xml);
XPathNavigator nav = doc.CreateNavigator();
Assert.AreEqual(XPathNodeType.Root, nav.NodeType);
Assert.AreEqual(string.Empty, nav.Name);
@@ -56,8 +59,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
]]></item5>
</wrap>
</root>";
var doc = XmlHelper.CreateXPathDocument(xml);
var nav = doc.CreateNavigator();
XPathDocument doc = XmlHelper.CreateXPathDocument(xml);
XPathNavigator nav = doc.CreateNavigator();
NavigatorValues(nav, true);
}
@@ -71,7 +74,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
NavigatorValues(nav, false);
}
static void NavigatorValues(XPathNavigator nav, bool native)
private static void NavigatorValues(XPathNavigator nav, bool native)
{
// in non-native we can't have Value dump everything, else
// we'd dump the entire database? Makes not much sense.
@@ -106,7 +109,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
// we have no way to tell the navigable that a value is CDATA
// so the rule is, if it's null it's not there, anything else is there
// and the filtering has to be done when building the content
Assert.IsTrue(nav.MoveToNext());
Assert.AreEqual("item2c", nav.Name);
Assert.AreEqual("\n ", nav.Value.Lf()); // ok since it's a property
@@ -166,7 +168,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var nav = new NavigableNavigator(source);
nav.MoveToRoot();
Assert.AreEqual("", nav.Name); // because we're at root
Assert.AreEqual(string.Empty, nav.Name); // because we're at root
nav.MoveToFirstChild();
Assert.AreEqual("root", nav.Name);
nav.MoveToFirstChild();
@@ -206,7 +208,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
nav.MoveToFirstChild();
// "<data><item1>poo</item1><item2 xx=\"33\" /><item2 xx=\"34\" /></data>"
Assert.AreEqual(XPathNodeType.Element, nav.NodeType);
Assert.AreEqual("data", nav.Name);
@@ -232,8 +233,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
{
const string xml = @"<root id=""-1"" />";
var doc = XmlHelper.CreateXPathDocument(xml);
var nnav = doc.CreateNavigator();
XPathDocument doc = XmlHelper.CreateXPathDocument(xml);
XPathNavigator nnav = doc.CreateNavigator();
Assert.AreEqual(xml, nnav.OuterXml);
var source = new TestSource0();
@@ -285,7 +286,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var source = new TestSource1();
var nav = new NavigableNavigator(source);
var iterator = nav.Select("//type1");
XPathNodeIterator iterator = nav.Select("//type1");
Assert.AreEqual(1, iterator.Count);
iterator.MoveNext();
Assert.AreEqual("type1", iterator.Current.Name);
@@ -302,17 +303,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var source = new TestSource2();
var nav = new NavigableNavigator(source);
var doc = XmlHelper.CreateXPathDocument("<data><item1>poo</item1><item2 xx=\"33\" /><item2 xx=\"34\" /></data>");
var docNav = doc.CreateNavigator();
var docIter = docNav.Select("//item2 [@xx=33]");
XPathDocument doc = XmlHelper.CreateXPathDocument("<data><item1>poo</item1><item2 xx=\"33\" /><item2 xx=\"34\" /></data>");
XPathNavigator docNav = doc.CreateNavigator();
XPathNodeIterator docIter = docNav.Select("//item2 [@xx=33]");
Assert.AreEqual(1, docIter.Count);
Assert.AreEqual("", docIter.Current.Name);
Assert.AreEqual(string.Empty, docIter.Current.Name);
docIter.MoveNext();
Assert.AreEqual("item2", docIter.Current.Name);
var iterator = nav.Select("//item2 [@xx=33]");
XPathNodeIterator iterator = nav.Select("//item2 [@xx=33]");
Assert.AreEqual(1, iterator.Count);
Assert.AreEqual("", iterator.Current.Name);
Assert.AreEqual(string.Empty, iterator.Current.Name);
iterator.MoveNext();
Assert.AreEqual("item2", iterator.Current.Name);
}
@@ -323,7 +324,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var source = new TestSource1();
var nav = new NavigableNavigator(source);
var iterator = nav.Select("//* [@prop1=$var]", new XPathVariable("var", "1:p1"));
XPathNodeIterator iterator = nav.Select("//* [@prop1=$var]", new XPathVariable("var", "1:p1"));
Assert.AreEqual(1, iterator.Count);
iterator.MoveNext();
Assert.AreEqual("type1", iterator.Current.Name);
@@ -335,7 +336,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var source = new TestSource2();
var nav = new NavigableNavigator(source);
var iterator = nav.Select("//item2 [@xx=$var]", new XPathVariable("var", "33"));
XPathNodeIterator iterator = nav.Select("//item2 [@xx=$var]", new XPathVariable("var", "33"));
Assert.AreEqual(1, iterator.Count);
iterator.MoveNext();
Assert.AreEqual("item2", iterator.Current.Name);
@@ -347,12 +348,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var source = new TestSource4();
var nav = new NavigableNavigator(source);
var doc = XmlHelper.CreateXPathDocument(@"<root id=""-1"">
XPathDocument doc = XmlHelper.CreateXPathDocument(@"<root id=""-1"">
<type1 id=""1""><prop1><data value=""value""/></prop1><prop2>dang</prop2></type1>
<type1 id=""2""><prop1 /><prop2></prop2></type1>
<type1 id=""3""><prop1 /><prop2 /></type1>
</root>");
var docNav = doc.CreateNavigator();
XPathNavigator docNav = doc.CreateNavigator();
docNav.MoveToRoot();
Assert.IsTrue(docNav.MoveToFirstChild());
@@ -366,7 +367,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
Assert.IsFalse(docNav.MoveToNext());
docNav.MoveToRoot();
var docOuter = docNav.OuterXml;
string docOuter = docNav.OuterXml;
nav.MoveToRoot();
Assert.IsTrue(nav.MoveToFirstChild());
@@ -380,7 +381,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
Assert.IsFalse(nav.MoveToNext());
nav.MoveToRoot();
var outer = nav.OuterXml;
string outer = nav.OuterXml;
Assert.AreEqual(docOuter, outer);
}
@@ -392,14 +393,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var source = new TestSource1();
var nav = new NavigableNavigator(source);
var iterator = nav.Select("/*");
XPathNodeIterator iterator = nav.Select("/*");
// but, that requires that the underlying navigator implements IHasXmlNode
// so it is possible to obtain nodes from the navigator - not possible yet
var nodes = XmlNodeListFactory.CreateNodeList(iterator);
XmlNodeList nodes = XmlNodeListFactory.CreateNodeList(iterator);
Assert.AreEqual(nodes.Count, 1);
var node = nodes[0];
XmlNode node = nodes[0];
Assert.AreEqual(3, node.Attributes.Count);
Assert.AreEqual("1", node.Attributes["id"].Value);
@@ -434,7 +435,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
Assert.AreEqual(3, (nav.UnderlyingObject as TestContent).Id);
// at that point nav is at /root/1/3
var clone = nav.Clone() as NavigableNavigator;
// move nav to /root/1/5 and ensure that clone stays at /root/1/3
@@ -475,7 +475,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var source = new TestSource5();
var nav = new NavigableNavigator(source);
var iter = nav.Select(string.Format("//* [@id={0}]", id));
XPathNodeIterator iter = nav.Select(string.Format("//* [@id={0}]", id));
Assert.IsTrue(iter.MoveNext());
var current = iter.Current as NavigableNavigator;
Assert.AreEqual(NavigableNavigator.StatePosition.Element, current.InternalState.Position);
@@ -493,7 +493,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var source = new TestSource5();
var nav = new NavigableNavigator(source);
var iter = nav.Select("//* [@id=$id]", new XPathVariable("id", id.ToString(CultureInfo.InvariantCulture)));
XPathNodeIterator iter = nav.Select("//* [@id=$id]", new XPathVariable("id", id.ToString(CultureInfo.InvariantCulture)));
Assert.IsTrue(iter.MoveNext());
var current = iter.Current as NavigableNavigator;
Assert.AreEqual(NavigableNavigator.StatePosition.Element, current.InternalState.Position);
@@ -578,8 +578,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
// go to (/root) /1/prop1
Assert.IsTrue(nav.MoveToFirstChild());
// go to (/root) /1/prop2
Assert.IsTrue(nav.MoveToNext());
// go to (/root) /1/3
Assert.IsTrue(nav.MoveToNext());
Assert.AreEqual(NavigableNavigator.StatePosition.Element, nav.InternalState.Position);
@@ -666,13 +668,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
// go to /root/1/prop1
Assert.IsTrue(nav.MoveToFirstChild());
// go to /root/1/prop2
Assert.IsTrue(nav.MoveToNext());
// can't go to /root/1/3
Assert.IsFalse(nav.MoveToNext());
Assert.IsFalse(nav.MoveToId("3"));
//Assert.AreEqual(NavigableNavigator.StatePosition.Element, nav.InternalState.Position);
//Assert.AreEqual(3, (nav.UnderlyingObject as TestContent).Id);
//// Assert.AreEqual(NavigableNavigator.StatePosition.Element, nav.InternalState.Position);
//// Assert.AreEqual(3, (nav.UnderlyingObject as TestContent).Id);
}
[TestCase(true, true)]
@@ -755,7 +760,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
// see http://www.onenaught.com/posts/352/xslt-performance-tip-dont-indent-output
// why aren't we using an XmlWriter here?
var transform = new XslCompiledTransform(debug);
var xmlReader = new XmlTextReader(new StringReader(xslt))
{
@@ -774,8 +778,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
if (!native)
{
var source = new TestSource7();
var nav = new NavigableNavigator(source);
//args.AddParam("currentPage", string.Empty, nav.Clone());
////var nav = new NavigableNavigator(source);
////args.AddParam("currentPage", string.Empty, nav.Clone());
var x = new XmlDocument();
x.LoadXml(xml);
@@ -784,14 +788,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
{
// it even fails like that => macro nav. issue?
new MacroNavigator.MacroParameter("nav", x.CreateNavigator()) // nav.Clone())
}
);
});
}
else
{
var doc = new XmlDocument();
doc.LoadXml("<macro />");
var nav = doc.CreateElement("nav");
XmlElement nav = doc.CreateElement("nav");
doc.DocumentElement.AppendChild(nav);
var x = new XmlDocument();
x.LoadXml(xml);
@@ -807,22 +810,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
// but was NOT working (changing the order of nodes) with macro nav, debug
// was due to an issue with macro nav IsSamePosition, fixed
//Debug.Print("--------");
//Debug.Print(writer.ToString());
////Debug.Print("--------");
////Debug.Print(writer.ToString());
Assert.AreEqual(expected.Lf(), writer.ToString().Lf());
}
[Test]
public void WhiteSpacesAndEmptyValues()
{
// "When Microsofts DOM builder receives a text node from the parser
// that contains only white space, it is thrown away." - so if it's ONLY
// spaces, it's nothing, but spaces are NOT trimmed.
// For attributes, spaces are preserved even when there's only spaces.
var doc = XmlHelper.CreateXPathDocument(@"<root>
XPathDocument doc = XmlHelper.CreateXPathDocument(@"<root>
<item><prop/></item>
<item><prop></prop></item>
<item><prop> </prop></item>
@@ -835,9 +836,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
<item x="" ""/>
</root>");
var docNav = doc.CreateNavigator();
XPathNavigator docNav = doc.CreateNavigator();
Assert.AreEqual(@"<root>
Assert.AreEqual(
@"<root>
<item>
<prop />
</item>
@@ -859,7 +861,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
</item>
<item x="""" />
<item x="" "" />
</root>".Lf(), docNav.OuterXml.Lf());
</root>".Lf(),
docNav.OuterXml.Lf());
docNav.MoveToRoot();
Assert.IsTrue(docNav.MoveToFirstChild());
@@ -870,18 +873,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
Assert.IsTrue(docNav.MoveToNext());
Assert.IsTrue(docNav.MoveToFirstChild()); // prop
Assert.IsFalse(docNav.IsEmptyElement);
Assert.AreEqual("", docNav.Value); // contains an empty text node
Assert.AreEqual(string.Empty, docNav.Value); // contains an empty text node
Assert.IsTrue(docNav.MoveToParent());
Assert.IsTrue(docNav.MoveToNext());
Assert.IsTrue(docNav.MoveToFirstChild()); // prop
Assert.IsFalse(docNav.IsEmptyElement);
Assert.AreEqual("", docNav.Value); // contains an empty text node
Assert.AreEqual(string.Empty, docNav.Value); // contains an empty text node
var source = new TestSource8();
var nav = new NavigableNavigator(source);
// shows how whitespaces are handled by NavigableNavigator
Assert.AreEqual(@"<root id=""-1"" attr="""">
Assert.AreEqual(
@"<root id=""-1"" attr="""">
<item id=""1"" attr="""">
<prop />
</item>
@@ -902,9 +906,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
}
}
#region Navigable implementation
class TestPropertyType : INavigableFieldType
internal class TestPropertyType : INavigableFieldType
{
public TestPropertyType(string name, bool isXmlContent = false, Func<object, string> xmlStringConverter = null)
{
@@ -914,11 +916,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
}
public string Name { get; private set; }
public bool IsXmlContent { get; private set; }
public Func<object, string> XmlStringConverter { get; private set; }
}
class TestContentType : INavigableContentType
internal class TestContentType : INavigableContentType
{
public TestContentType(TestSourceBase source, string name, params INavigableFieldType[] properties)
{
@@ -928,25 +932,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
}
public TestSourceBase Source { get; private set; }
public string Name { get; private set; }
public INavigableFieldType[] FieldTypes { get; protected set; }
}
class TestRootContentType : TestContentType
internal class TestRootContentType : TestContentType
{
public TestRootContentType(TestSourceBase source, params INavigableFieldType[] properties)
: base(source, "root")
{
FieldTypes = properties;
}
: base(source, "root") => FieldTypes = properties;
public TestContentType CreateType(string name, params INavigableFieldType[] properties)
{
return new TestContentType(Source, name, FieldTypes.Union(properties).ToArray());
}
public TestContentType CreateType(string name, params INavigableFieldType[] properties) => new TestContentType(Source, name, FieldTypes.Union(properties).ToArray());
}
class TestContent : INavigableContent
internal class TestContent : INavigableContent
{
public TestContent(TestContentType type, int id, int parentId)
{
@@ -956,39 +956,56 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
}
private readonly TestContentType _type;
public int Id { get; private set; }
public int ParentId { get; private set; }
public INavigableContentType Type { get { return _type; } }
public INavigableContentType Type => _type;
public IList<int> ChildIds { get; private set; }
public object Value(int id)
{
var fieldType = _type.FieldTypes[id] as TestPropertyType;
if (fieldType == null) throw new Exception("Oops");
if (!(_type.FieldTypes[id] is TestPropertyType fieldType))
{
throw new Exception("Oops");
}
var value = FieldValues[id];
var isAttr = id <= _type.Source.LastAttributeIndex;
object value = FieldValues[id];
bool isAttr = id <= _type.Source.LastAttributeIndex;
// null => return null
if (value == null) return null;
if (value == null)
{
return null;
}
// attribute => return string value
if (isAttr) return value.ToString();
if (isAttr)
{
return value.ToString();
}
// has a converter => use the converter
if (fieldType.XmlStringConverter != null)
{
return fieldType.XmlStringConverter(value);
}
// not a string => return value as a string
var s = value as string;
if (s == null) return value.ToString();
if (!(value is string s))
{
return value.ToString();
}
// xml content... try xml
if (fieldType.IsXmlContent)
{
XPathDocument doc;
if (XmlHelper.TryCreateXPathDocumentFromPropertyValue(s, out doc))
if (XmlHelper.TryCreateXPathDocumentFromPropertyValue(s, out XPathDocument doc))
{
return doc.CreateNavigator();
}
}
// return the string
@@ -1007,37 +1024,31 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
public TestContent WithValues(params object[] values)
{
FieldValues = values == null ? new object[] {null} : values;
FieldValues = values ?? (new object[] { null });
return this;
}
}
class TestRootContent : TestContent
internal class TestRootContent : TestContent
{
public TestRootContent(TestContentType type)
: base(type, -1, -1)
{ }
{
}
}
abstract class TestSourceBase : INavigableSource
internal abstract class TestSourceBase : INavigableSource
{
protected readonly Dictionary<int, TestContent> Content = new Dictionary<int, TestContent>();
public INavigableContent Get(int id)
{
return Content.ContainsKey(id) ? Content[id] : null;
}
public INavigableContent Get(int id) => Content.ContainsKey(id) ? Content[id] : null;
public int LastAttributeIndex { get; protected set; }
public INavigableContent Root { get; protected set; }
}
#endregion
#region Navigable sources
class TestSource0 : TestSourceBase
internal class TestSource0 : TestSourceBase
{
public TestSource0()
{
@@ -1047,7 +1058,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
}
}
class TestSource1 : TestSourceBase
internal class TestSource1 : TestSourceBase
{
public TestSource1()
{
@@ -1059,15 +1070,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var prop2 = new TestPropertyType("prop2");
var prop3 = new TestPropertyType("prop3");
var type = new TestRootContentType(this, prop1, prop2);
var type1 = type.CreateType("type1", prop3);
TestContentType type1 = type.CreateType("type1", prop3);
Content[1] = new TestContent(type1, 1, -1).WithValues("1:p1", "1:p2", "1:p3");
Root = new TestRootContent(type).WithValues("", "").WithChildren(1);
Root = new TestRootContent(type).WithValues(string.Empty, string.Empty).WithChildren(1);
}
}
class TestSource2 : TestSourceBase
internal class TestSource2 : TestSourceBase
{
public TestSource2()
{
@@ -1075,7 +1086,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var prop1 = new TestPropertyType("prop1", true);
var type = new TestRootContentType(this);
var type1 = type.CreateType("type1", prop1);
TestContentType type1 = type.CreateType("type1", prop1);
const string xml = "<data><item1>poo</item1><item2 xx=\"33\" /><item2 xx=\"34\" /></data>";
Content[1] = new TestContent(type1, 1, 1).WithValues(xml);
@@ -1084,7 +1095,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
}
}
class TestSource3 : TestSourceBase
internal class TestSource3 : TestSourceBase
{
public TestSource3()
{
@@ -1094,7 +1105,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var prop2 = new TestPropertyType("prop2");
var prop3 = new TestPropertyType("prop3");
var type = new TestRootContentType(this, prop1, prop2);
var type1 = type.CreateType("type1", prop3);
TestContentType type1 = type.CreateType("type1", prop3);
Content[1] = new TestContent(type1, 1, 1).WithValues("1:p1", "1:p2", "1:p3").WithChildren(2);
Content[2] = new TestContent(type1, 2, 1).WithValues("2:p1", "2:p2", "2:p3");
@@ -1103,7 +1114,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
}
}
class TestSource4 : TestSourceBase
internal class TestSource4 : TestSourceBase
{
public TestSource4()
{
@@ -1112,17 +1123,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var prop1 = new TestPropertyType("prop1", true);
var prop2 = new TestPropertyType("prop2");
var type = new TestRootContentType(this);
var type1 = type.CreateType("type1", prop1, prop2);
TestContentType type1 = type.CreateType("type1", prop1, prop2);
Content[1] = new TestContent(type1, 1, -1).WithValues("<data value=\"value\"/>", "dang");
Content[2] = new TestContent(type1, 2, -1).WithValues(null, "");
Content[2] = new TestContent(type1, 2, -1).WithValues(null, string.Empty);
Content[3] = new TestContent(type1, 3, -1).WithValues(null, null);
Root = new TestRootContent(type).WithChildren(1, 2, 3);
}
}
class TestSource5 : TestSourceBase
internal class TestSource5 : TestSourceBase
{
public TestSource5()
{
@@ -1131,7 +1142,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var prop1 = new TestPropertyType("prop1");
var prop2 = new TestPropertyType("prop2");
var type = new TestRootContentType(this);
var type1 = type.CreateType("type1", prop1, prop2);
TestContentType type1 = type.CreateType("type1", prop1, prop2);
Content[1] = new TestContent(type1, 1, -1).WithValues("p11", "p12").WithChildren(3, 5);
Content[2] = new TestContent(type1, 2, -1).WithValues("p21", "p22").WithChildren(4, 6);
@@ -1144,32 +1155,33 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
}
}
class TestSource6 : TestSourceBase
internal class TestSource6 : TestSourceBase
{
//<root>
// <wrap>
// <item1 />
// <item2></item2>
// <item2a> </item2a>
// <item2b>
// </item2b>
// <item2c><![CDATA[
// ]]></item2c>
// <item3>blah</item3>
// <item4>
// <subitem x=""1"">bam</subitem>
// </item4>
// <item5>
// </item5>
// </wrap>
//</root>
////<root>
//// <wrap>
//// <item1 />
//// <item2></item2>
//// <item2a> </item2a>
//// <item2b>
//// </item2b>
//// <item2c><![CDATA[
//// ]]></item2c>
//// <item3>blah</item3>
//// <item4>
//// <subitem x=""1"">bam</subitem>
//// </item4>
//// <item5>
//// </item5>
//// </wrap>
////</root>
public TestSource6()
{
LastAttributeIndex = -1;
var type = new TestRootContentType(this);
var type1 = type.CreateType("wrap",
TestContentType type1 = type.CreateType(
"wrap",
new TestPropertyType("item1"),
new TestPropertyType("item2"),
new TestPropertyType("item2a"),
@@ -1178,8 +1190,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
new TestPropertyType("item3"),
new TestPropertyType("item3a"),
new TestPropertyType("item4", true),
new TestPropertyType("item5", true)
);
new TestPropertyType("item5", true));
Content[1] = new TestContent(type1, 1, -1)
.WithValues(
@@ -1191,14 +1202,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
"blah",
"\n blah\n ",
"<subitem x=\"1\">bam</subitem>",
"\n "
);
"\n ");
Root = new TestRootContent(type).WithChildren(1);
}
}
class TestSource7 : TestSourceBase
internal class TestSource7 : TestSourceBase
{
public TestSource7()
{
@@ -1207,7 +1217,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var prop1 = new TestPropertyType("isDoc");
var prop2 = new TestPropertyType("title");
var type = new TestRootContentType(this, prop1);
var type1 = type.CreateType("node", prop1, prop2);
TestContentType type1 = type.CreateType("node", prop1, prop2);
Content[1] = new TestContent(type1, 1, -1).WithValues(1, "title-1").WithChildren(3, 5);
Content[2] = new TestContent(type1, 2, -1).WithValues(1, "title-2").WithChildren(4, 6);
@@ -1223,7 +1233,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
}
}
class TestSource8 : TestSourceBase
internal class TestSource8 : TestSourceBase
{
public TestSource8()
{
@@ -1232,15 +1242,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
var attr = new TestPropertyType("attr");
var prop = new TestPropertyType("prop");
var type = new TestRootContentType(this, attr);
var type1 = type.CreateType("item", attr, prop);
TestContentType type1 = type.CreateType("item", attr, prop);
Content[1] = new TestContent(type1, 1, -1).WithValues(null, null);
Content[2] = new TestContent(type1, 2, -1).WithValues("", "");
Content[2] = new TestContent(type1, 2, -1).WithValues(string.Empty, string.Empty);
Content[3] = new TestContent(type1, 3, -1).WithValues(" ", " ");
Content[4] = new TestContent(type1, 4, -1).WithValues("", "\n");
Content[4] = new TestContent(type1, 4, -1).WithValues(string.Empty, "\n");
Content[5] = new TestContent(type1, 5, -1).WithValues(" ooo ", " ooo ");
Root = new TestRootContent(type).WithValues(null).WithChildren(1, 2, 3, 4, 5);
}
}
#endregion
}

View File

@@ -1,4 +1,7 @@
using System.Runtime.InteropServices;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Runtime.InteropServices;
using System.Xml;
using System.Xml.XPath;
using NUnit.Framework;
@@ -19,7 +22,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
</root>");
var nav = doc.CreateNavigator();
var xml = nav.OuterXml;
Assert.AreEqual(EnsureNativeLineEndings(@"<root foo=""bar"">
Assert.AreEqual(
EnsureNativeLineEndings(@"<root foo=""bar"">
<a></a>
<b x=""1""></b>
</root>"), xml);
@@ -35,7 +39,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
</xx:root>");
var nav = doc.CreateNavigator();
var xml = nav.OuterXml;
Assert.AreEqual(EnsureNativeLineEndings(@"<xx:root foo=""bar"" xmlns:xx=""uri"">
Assert.AreEqual(
EnsureNativeLineEndings(@"<xx:root foo=""bar"" xmlns:xx=""uri"">
<a></a>
<b x=""1""></b>
</xx:root>"), xml);
@@ -51,7 +56,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
</root>");
var nav = new RenamedRootNavigator(doc.CreateNavigator(), "test");
var xml = nav.OuterXml;
Assert.AreEqual(EnsureNativeLineEndings(@"<test foo=""bar"">
Assert.AreEqual(
EnsureNativeLineEndings(@"<test foo=""bar"">
<a></a>
<b x=""1""></b>
</test>"), xml);
@@ -73,7 +79,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml
</xx:root>");
var nav = new RenamedRootNavigator(doc.CreateNavigator(), "test");
var xml = nav.OuterXml;
Assert.AreEqual(EnsureNativeLineEndings(@"<xx:test foo=""bar"" xmlns:xx=""uri"">
Assert.AreEqual(
EnsureNativeLineEndings(@"<xx:test foo=""bar"" xmlns:xx=""uri"">
<a></a>
<b x=""1""></b>
</xx:test>"), xml);

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Lucene.Net.Index;
using NUnit.Framework;
using Umbraco.Core;
@@ -13,11 +16,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
{
const int maxTries = 5;
var totalTries = 0;
DelegateExtensions.RetryUntilSuccessOrMaxAttempts((currentTry) =>
{
totalTries = currentTry;
return Attempt<IndexWriter>.Fail();
}, 5, TimeSpan.FromMilliseconds(10));
DelegateExtensions.RetryUntilSuccessOrMaxAttempts(
(currentTry) =>
{
totalTries = currentTry;
return Attempt<IndexWriter>.Fail();
},
5,
TimeSpan.FromMilliseconds(10));
Assert.AreEqual(maxTries, totalTries);
}
@@ -26,11 +32,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
public void Quits_On_Success_Count()
{
var totalTries = 0;
DelegateExtensions.RetryUntilSuccessOrMaxAttempts((currentTry) =>
{
totalTries = currentTry;
return totalTries == 2 ? Attempt<string>.Succeed() : Attempt<string>.Fail();
}, 5, TimeSpan.FromMilliseconds(10));
DelegateExtensions.RetryUntilSuccessOrMaxAttempts(
(currentTry) =>
{
totalTries = currentTry;
return totalTries == 2 ? Attempt<string>.Succeed() : Attempt<string>.Fail();
},
5,
TimeSpan.FromMilliseconds(10));
Assert.AreEqual(2, totalTries);
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Web.Trees;
@@ -14,13 +17,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
[TestCase(TreeUse.Dialog, TreeUse.Dialog | TreeUse.Main, false)]
public void HasFlagTest(TreeUse value, TreeUse test, bool expected)
{
// the built-in Enum.HasFlag() method determines whether
// all bits from <test> are set (other bits can be set too)
// The built-in Enum.HasFlag() method determines whether
// all bits from <test> are set (other bits can be set too).
if (expected)
{
Assert.IsTrue(value.HasFlag(test));
}
else
{
Assert.IsFalse(value.HasFlag(test));
}
}
[Obsolete]
@@ -30,13 +36,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
[TestCase(TreeUse.Dialog, TreeUse.Dialog | TreeUse.Main, false)]
public void HasFlagAllTest(TreeUse value, TreeUse test, bool expected)
{
// the HasFlagAll() extension method determines whether
// all bits from <test> are set (other bits can be set too)
// The HasFlagAll() extension method determines whether
// all bits from <test> are set (other bits can be set too).
if (expected)
{
Assert.IsTrue(value.HasFlagAll(test));
}
else
{
Assert.IsFalse(value.HasFlagAll(test));
}
}
[TestCase(TreeUse.Dialog, TreeUse.Dialog, true)]
@@ -45,13 +54,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
[TestCase(TreeUse.Dialog, TreeUse.Dialog | TreeUse.Main, true)]
public void HasFlagAnyTest(TreeUse value, TreeUse test, bool expected)
{
// the HasFlagAny() extension method determines whether
// at least one bit from <test> is set
// The HasFlagAny() extension method determines whether
// at least one bit from <test> is set.
if (expected)
{
Assert.IsTrue(value.HasFlagAny(test));
}
else
{
Assert.IsFalse(value.HasFlagAny(test));
}
}
}
}

View File

@@ -1,4 +1,8 @@
using System.Collections.Generic;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
@@ -27,9 +31,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
[Test]
public void Contains_All()
{
var list1 = new[] {1, 2, 3, 4, 5, 6};
var list2 = new[] {6, 5, 3, 2, 1, 4};
var list3 = new[] {6, 5, 4, 3};
var list1 = new[] { 1, 2, 3, 4, 5, 6 };
var list2 = new[] { 6, 5, 3, 2, 1, 4 };
var list3 = new[] { 6, 5, 4, 3 };
Assert.IsTrue(list1.ContainsAll(list2));
Assert.IsTrue(list2.ContainsAll(list1));
@@ -42,15 +46,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
{
var hierarchy = new TestItem("1")
{
Children = new List<TestItem>
{
new TestItem("1.1"),
new TestItem("1.2"),
new TestItem("1.3")
}
};
Children = new List<TestItem>
{
new TestItem("1.1"),
new TestItem("1.2"),
new TestItem("1.3")
}
};
var selectRecursive = hierarchy.Children.SelectRecursive(x => x.Children);
IEnumerable<TestItem> selectRecursive = hierarchy.Children.SelectRecursive(x => x.Children);
Assert.AreEqual(3, selectRecursive.Count());
}
@@ -111,7 +115,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
}
};
var selectRecursive = hierarchy.Children.SelectRecursive(x => x.Children);
IEnumerable<TestItem> selectRecursive = hierarchy.Children.SelectRecursive(x => x.Children);
Assert.AreEqual(10, selectRecursive.Count());
}
@@ -122,7 +126,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
Children = Enumerable.Empty<TestItem>();
Name = name;
}
public string Name { get; }
public IEnumerable<TestItem> Children { get; set; }
}
@@ -131,7 +137,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
{
var integers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
var groupsOfTwo = integers.InGroupsOf(2).ToArray();
IEnumerable<int>[] groupsOfTwo = integers.InGroupsOf(2).ToArray();
var flattened = groupsOfTwo.SelectMany(x => x).ToArray();
@@ -139,7 +145,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
Assert.That(flattened.Length, Is.EqualTo(integers.Length));
CollectionAssert.AreEquivalent(integers, flattened);
var groupsOfMassive = integers.InGroupsOf(100).ToArray();
IEnumerable<int>[] groupsOfMassive = integers.InGroupsOf(100).ToArray();
Assert.That(groupsOfMassive.Length, Is.EqualTo(1));
flattened = groupsOfMassive.SelectMany(x => x).ToArray();
Assert.That(flattened.Length, Is.EqualTo(integers.Length));
@@ -150,7 +156,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
public void InGroupsOf_CanRepeat()
{
var integers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
var inGroupsOf = integers.InGroupsOf(2);
IEnumerable<IEnumerable<int>> inGroupsOf = integers.InGroupsOf(2);
Assert.AreEqual(5, inGroupsOf.Count());
Assert.AreEqual(5, inGroupsOf.Count()); // again
}
@@ -172,7 +178,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
};
// Act
var iteratorSource = list.DistinctBy(x => x.Item2);
IEnumerable<Tuple<string, string>> iteratorSource = list.DistinctBy(x => x.Item2);
// Assert
// First check distinction

View File

@@ -1,11 +1,13 @@
using NUnit.Framework;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Umbraco.Extensions;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Security;
using Umbraco.Extensions;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Extensions
{
@@ -15,16 +17,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Extensions
[Test]
public void Get_Remaining_Ticket_Seconds()
{
var backOfficeIdentity = new UmbracoBackOfficeIdentity(Constants.Security.SuperUserIdAsString, "test", "test",
Enumerable.Empty<int>(), Enumerable.Empty<int>(), "en-US", Guid.NewGuid().ToString(),
Enumerable.Empty<string>(), Enumerable.Empty<string>());
var backOfficeIdentity = new UmbracoBackOfficeIdentity(
Constants.Security.SuperUserIdAsString,
"test",
"test",
Enumerable.Empty<int>(),
Enumerable.Empty<int>(),
"en-US",
Guid.NewGuid().ToString(),
Enumerable.Empty<string>(),
Enumerable.Empty<string>());
var principal = new ClaimsPrincipal(backOfficeIdentity);
var expireSeconds = 99;
var elapsedSeconds = 3;
var remainingSeconds = expireSeconds - elapsedSeconds;
var now = DateTimeOffset.Now;
var then = now.AddSeconds(elapsedSeconds);
DateTimeOffset now = DateTimeOffset.Now;
DateTimeOffset then = now.AddSeconds(elapsedSeconds);
var expires = now.AddSeconds(expireSeconds).ToString("o");
backOfficeIdentity.AddClaim(new Claim(

View File

@@ -1,12 +1,13 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration.Models;
using Umbraco.Tests.Common;
using Umbraco.Tests.Common.Builders;
using Umbraco.Web.Common.AspNetCore;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Extensions

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using NUnit.Framework;
using Umbraco.Core;

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
@@ -11,10 +14,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
{
private DirectoryInfo PrepareFolder()
{
var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
var dir = Directory.CreateDirectory(Path.Combine(assDir.FullName, "HashCombiner",
Guid.NewGuid().ToString("N")));
foreach (var f in dir.GetFiles())
DirectoryInfo assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
DirectoryInfo dir = Directory.CreateDirectory(
Path.Combine(assDir.FullName, "HashCombiner", Guid.NewGuid().ToString("N")));
foreach (FileInfo f in dir.GetFiles())
{
f.Delete();
}
@@ -57,7 +60,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
[Test]
public void HashCombiner_Test_DateTime()
{
var dt = DateTime.Now;
DateTime dt = DateTime.Now;
var combiner1 = new HashCodeCombiner();
combiner1.AddDateTime(dt);
@@ -74,19 +77,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
[Test]
public void HashCombiner_Test_File()
{
var dir = PrepareFolder();
DirectoryInfo dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (var file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
using (StreamWriter file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
file1.WriteLine("hello");
}
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (var file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
using (StreamWriter file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
//even though files are the same, the dates are different
// even though files are the same, the dates are different
file2.WriteLine("hello");
}
@@ -110,15 +113,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
[Test]
public void HashCombiner_Test_Folder()
{
var dir = PrepareFolder();
DirectoryInfo dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (var file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
using (StreamWriter file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
file1.WriteLine("hello");
}
//first test the whole folder
// first test the whole folder
var combiner1 = new HashCodeCombiner();
combiner1.AddFolder(dir);
@@ -127,13 +130,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
//now add a file to the folder
// now add a file to the folder
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (var file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
using (StreamWriter file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
//even though files are the same, the dates are different
// even though files are the same, the dates are different
file2.WriteLine("hello");
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
@@ -11,18 +14,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
{
private string Generate(bool isCaseSensitive, params string[] strs)
{
using (var generator = new HashGenerator())
using var generator = new HashGenerator();
foreach (var str in strs)
{
foreach (var str in strs)
if (isCaseSensitive)
{
if (isCaseSensitive)
generator.AddString(str);
else
generator.AddCaseInsensitiveString(str);
generator.AddString(str);
}
else
{
generator.AddCaseInsensitiveString(str);
}
return generator.GenerateHash();
}
return generator.GenerateHash();
}
[Test]
@@ -53,10 +58,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
private DirectoryInfo PrepareFolder()
{
var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
var dir = Directory.CreateDirectory(Path.Combine(assDir.FullName, "HashCombiner",
Guid.NewGuid().ToString("N")));
foreach (var f in dir.GetFiles())
DirectoryInfo assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
DirectoryInfo dir = Directory.CreateDirectory(
Path.Combine(assDir.FullName, "HashCombiner", Guid.NewGuid().ToString("N")));
foreach (FileInfo f in dir.GetFiles())
{
f.Delete();
}
@@ -95,92 +100,85 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
[Test]
public void HashCombiner_Test_DateTime()
{
using (var combiner1 = new HashGenerator())
using (var combiner2 = new HashGenerator())
{
var dt = DateTime.Now;
combiner1.AddDateTime(dt);
combiner2.AddDateTime(dt);
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
combiner2.AddDateTime(DateTime.Now);
Assert.AreNotEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
}
using var combiner1 = new HashGenerator();
using var combiner2 = new HashGenerator();
DateTime dt = DateTime.Now;
combiner1.AddDateTime(dt);
combiner2.AddDateTime(dt);
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
combiner2.AddDateTime(DateTime.Now);
Assert.AreNotEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
}
[Test]
public void HashCombiner_Test_File()
{
using (var combiner1 = new HashGenerator())
using (var combiner2 = new HashGenerator())
using (var combiner3 = new HashGenerator())
using var combiner1 = new HashGenerator();
using var combiner2 = new HashGenerator();
using var combiner3 = new HashGenerator();
DirectoryInfo dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (StreamWriter file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
var dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (var file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
file1.WriteLine("hello");
}
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (var file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
//even though files are the same, the dates are different
file2.WriteLine("hello");
}
combiner1.AddFile(new FileInfo(file1Path));
combiner2.AddFile(new FileInfo(file1Path));
combiner3.AddFile(new FileInfo(file2Path));
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
Assert.AreNotEqual(combiner1.GenerateHash(), combiner3.GenerateHash());
combiner2.AddFile(new FileInfo(file2Path));
Assert.AreNotEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
file1.WriteLine("hello");
}
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (StreamWriter file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
// even though files are the same, the dates are different
file2.WriteLine("hello");
}
combiner1.AddFile(new FileInfo(file1Path));
combiner2.AddFile(new FileInfo(file1Path));
combiner3.AddFile(new FileInfo(file2Path));
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
Assert.AreNotEqual(combiner1.GenerateHash(), combiner3.GenerateHash());
combiner2.AddFile(new FileInfo(file2Path));
Assert.AreNotEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
}
[Test]
public void HashCombiner_Test_Folder()
{
using (var combiner1 = new HashGenerator())
using (var combiner2 = new HashGenerator())
using (var combiner3 = new HashGenerator())
using var combiner1 = new HashGenerator();
using var combiner2 = new HashGenerator();
using var combiner3 = new HashGenerator();
DirectoryInfo dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (StreamWriter file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
var dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (var file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
file1.WriteLine("hello");
}
//first test the whole folder
combiner1.AddFolder(dir);
combiner2.AddFolder(dir);
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
//now add a file to the folder
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (var file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
//even though files are the same, the dates are different
file2.WriteLine("hello");
}
combiner3.AddFolder(dir);
Assert.AreNotEqual(combiner1.GenerateHash(), combiner3.GenerateHash());
file1.WriteLine("hello");
}
// first test the whole folder
combiner1.AddFolder(dir);
combiner2.AddFolder(dir);
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
// now add a file to the folder
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (StreamWriter file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
// even though files are the same, the dates are different
file2.WriteLine("hello");
}
combiner3.AddFolder(dir);
Assert.AreNotEqual(combiner1.GenerateHash(), combiner3.GenerateHash());
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Text;
using NUnit.Framework;
using Umbraco.Core;
@@ -39,7 +42,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
Assert.AreEqual(expected, actual);
}
private static readonly char[] _bytesToHexStringLookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static readonly char[] s_bytesToHexStringLookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
// Reference implementation taken from original extension method.
private static string ToHexString(byte[] bytes, char separator, int blockSize, int blockCount)
@@ -49,8 +52,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
for (var i = 0; i < bytesLength; i++)
{
var b = bytes[i];
chars[p++] = _bytesToHexStringLookup[b / 0x10];
chars[p++] = _bytesToHexStringLookup[b % 0x10];
chars[p++] = s_bytesToHexStringLookup[b / 0x10];
chars[p++] = s_bytesToHexStringLookup[b % 0x10];
if (count == blockCount)
{
continue;
@@ -65,6 +68,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core
size = 0;
count++;
}
return new string(chars, 0, chars.Length);
}
}

View File

@@ -1,4 +1,8 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
@@ -14,10 +18,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
{
protected IFileSystem _fileSystem;
protected AbstractFileSystemTests(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
protected AbstractFileSystemTests(IFileSystem fileSystem) => _fileSystem = fileSystem;
[Test]
public void Can_Create_And_Delete_Files()
@@ -28,7 +29,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
_fileSystem.DeleteFile("test.txt");
Assert.IsFalse(_fileSystem.FileExists("test.txt"));
Assert.IsFalse(_fileSystem.FileExists("test.txt"));
}
[Test]
@@ -37,7 +38,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
_fileSystem.AddFile("test/test.txt", CreateStream());
_fileSystem.AddFile("test/test.txt", CreateStream());
var files = _fileSystem.GetFiles("test");
IEnumerable<string> files = _fileSystem.GetFiles("test");
Assert.AreEqual(1, files.Count());
@@ -50,16 +51,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
}
[Test]
public void Cant_Overwrite_File()
{
public void Cant_Overwrite_File() =>
Assert.Throws<InvalidOperationException>(() =>
{
_fileSystem.AddFile("test.txt", CreateStream());
_fileSystem.AddFile("test.txt", CreateStream(), false);
{
_fileSystem.AddFile("test.txt", CreateStream());
_fileSystem.AddFile("test.txt", CreateStream(), false);
_fileSystem.DeleteFile("test.txt");
});
}
_fileSystem.DeleteFile("test.txt");
});
[Test]
public void Can_Get_Files()
@@ -69,7 +68,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
_fileSystem.AddFile("test/test3.txt", CreateStream());
_fileSystem.AddFile("test/test4.bak", CreateStream());
var files = _fileSystem.GetFiles("test");
IEnumerable<string> files = _fileSystem.GetFiles("test");
Assert.AreEqual(4, files.Count());
@@ -85,7 +84,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
{
_fileSystem.AddFile("test.txt", CreateStream("hello world"));
var stream = _fileSystem.OpenFile("test.txt");
Stream stream = _fileSystem.OpenFile("test.txt");
var reader = new StreamReader(stream);
var contents = reader.ReadToEnd();
reader.Close();
@@ -102,7 +101,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
_fileSystem.AddFile("test/sub2/test.txt", CreateStream());
_fileSystem.AddFile("test/sub3/test.txt", CreateStream());
var dirs = _fileSystem.GetDirectories("test");
IEnumerable<string> dirs = _fileSystem.GetDirectories("test");
Assert.AreEqual(3, dirs.Count());
Assert.IsTrue(_fileSystem.DirectoryExists("test/sub1"));
@@ -119,8 +118,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
_fileSystem.AddFile("test.txt", CreateStream());
var created = _fileSystem.GetCreated("test.txt");
var modified = _fileSystem.GetLastModified("test.txt");
DateTimeOffset created = _fileSystem.GetCreated("test.txt");
DateTimeOffset modified = _fileSystem.GetLastModified("test.txt");
Assert.AreEqual(DateTime.UtcNow.Year, created.Year);
Assert.AreEqual(DateTime.UtcNow.Month, created.Month);
@@ -142,7 +141,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
Assert.AreEqual(ConstructUrl("test.txt"), url);
_fileSystem.DeleteFile("test.txt");
_fileSystem.DeleteFile("test.txt");
}
[Test]
@@ -165,7 +164,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
[Test]
public void Can_Get_Size()
{
var stream = CreateStream();
Stream stream = CreateStream();
var streamLength = stream.Length;
_fileSystem.AddFile("test.txt", stream);
@@ -174,12 +173,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
_fileSystem.DeleteFile("test.txt");
}
#region Helper Methods
protected Stream CreateStream(string contents = null)
{
if (string.IsNullOrEmpty(contents))
{
contents = "test";
}
var bytes = Encoding.UTF8.GetBytes(contents);
var stream = new MemoryStream(bytes);
@@ -188,7 +187,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
}
protected abstract string ConstructUrl(string path);
#endregion
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.IO;
using System.Text;
using System.Threading;
@@ -16,19 +19,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
{
public PhysicalFileSystemTests()
: base(new PhysicalFileSystem(TestHelper.IOHelper, TestHelper.GetHostingEnvironment(), Mock.Of<ILogger<PhysicalFileSystem>>(), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FileSysTests"), "/Media/"))
{ }
{
}
[SetUp]
public void Setup()
{
}
[TearDown]
public void TearDown()
{
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FileSysTests");
if (Directory.Exists(path) == false) return;
if (Directory.Exists(path) == false)
{
return;
}
var files = Directory.GetFiles(path);
foreach (var f in files)
@@ -39,16 +45,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
Directory.Delete(path, true);
}
protected override string ConstructUrl(string path)
{
return "/Media/" + path;
}
protected override string ConstructUrl(string path) => "/Media/" + path;
private string Repeat(string pattern, int count)
{
var text = new StringBuilder();
for (var i = 0; i < count; i++)
{
text.Append(pattern);
}
return text.ToString();
}
@@ -58,7 +64,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FileSysTests");
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
{
_fileSystem.AddFile("sub/f3.txt", ms);
}
Assert.IsTrue(File.Exists(Path.Combine(basePath, "sub/f3.txt")));
@@ -80,14 +88,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.IO
// here we initialize the PhysicalFileSystem with
// rootPath = /path/to/FileSysTests
// rootUrl = /Media/
var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FileSysTests");
// ensure that GetFullPath
// - does return the proper full path
// - does properly normalize separators
// - does throw on invalid paths
// works
var path = _fileSystem.GetFullPath("foo.tmp");
Assert.AreEqual(Path.Combine(basePath, @"foo.tmp"), path);

View File

@@ -1,14 +1,16 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Linq;
using Moq;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.IO;
using Umbraco.Core.Manifest;
using Umbraco.Core.Models;
using Umbraco.Core.Models.ContentEditing;
using Umbraco.Core.Models.Membership;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.Composing;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Manifest
{
@@ -18,64 +20,68 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Manifest
[Test]
public void Test()
{
var contentType = Mock.Of<IContentType>();
IContentType contentType = Mock.Of<IContentType>();
Mock.Get(contentType).Setup(x => x.Alias).Returns("type1");
var content = Mock.Of<IContent>();
IContent content = Mock.Of<IContent>();
Mock.Get(content).Setup(x => x.ContentType).Returns(new SimpleContentType(contentType));
var group1 = Mock.Of<IReadOnlyUserGroup>();
IReadOnlyUserGroup group1 = Mock.Of<IReadOnlyUserGroup>();
Mock.Get(group1).Setup(x => x.Alias).Returns("group1");
var group2 = Mock.Of<IReadOnlyUserGroup>();
IReadOnlyUserGroup group2 = Mock.Of<IReadOnlyUserGroup>();
Mock.Get(group2).Setup(x => x.Alias).Returns("group2");
// no rule = ok
AssertDefinition(content, true, Array.Empty<string>(), new [] { group1, group2 });
AssertDefinition(content, true, Array.Empty<string>(), new[] { group1, group2 });
// wildcards = ok
AssertDefinition(content, true, new [] { "+content/*" }, new [] { group1, group2 });
AssertDefinition(content, false, new[] { "+media/*" }, new [] { group1, group2 });
AssertDefinition(content, true, new[] { "+content/*" }, new[] { group1, group2 });
AssertDefinition(content, false, new[] { "+media/*" }, new[] { group1, group2 });
// explicitly enabling / disabling
AssertDefinition(content, true, new[] { "+content/type1" }, new [] { group1, group2 });
AssertDefinition(content, false, new[] { "-content/type1" }, new [] { group1, group2 });
AssertDefinition(content, true, new[] { "+content/type1" }, new[] { group1, group2 });
AssertDefinition(content, false, new[] { "-content/type1" }, new[] { group1, group2 });
// when there are type rules, failing to approve the type = no app
AssertDefinition(content, false, new[] { "+content/type2" }, new [] { group1, group2 });
AssertDefinition(content, false, new[] { "+media/type1" }, new [] { group1, group2 });
AssertDefinition(content, false, new[] { "+content/type2" }, new[] { group1, group2 });
AssertDefinition(content, false, new[] { "+media/type1" }, new[] { group1, group2 });
// can have multiple rule, first one that matches = end
AssertDefinition(content, false, new[] { "-content/type1", "+content/*" }, new [] { group1, group2 });
AssertDefinition(content, true, new[] { "-content/type2", "+content/*" }, new [] { group1, group2 });
AssertDefinition(content, true, new[] { "+content/*", "-content/type1" }, new [] { group1, group2 });
AssertDefinition(content, false, new[] { "-content/type1", "+content/*" }, new[] { group1, group2 });
AssertDefinition(content, true, new[] { "-content/type2", "+content/*" }, new[] { group1, group2 });
AssertDefinition(content, true, new[] { "+content/*", "-content/type1" }, new[] { group1, group2 });
// when there are role rules, failing to approve a role = no app
AssertDefinition(content, false, new[] { "+role/group33" }, new [] { group1, group2 });
AssertDefinition(content, false, new[] { "+role/group33" }, new[] { group1, group2 });
// wildcards = ok
AssertDefinition(content, true, new[] { "+role/*" }, new [] { group1, group2 });
AssertDefinition(content, true, new[] { "+role/*" }, new[] { group1, group2 });
// explicitly enabling / disabling
AssertDefinition(content, true, new[] { "+role/group1" }, new [] { group1, group2 });
AssertDefinition(content, false, new[] { "-role/group1" }, new [] { group1, group2 });
AssertDefinition(content, true, new[] { "+role/group1" }, new[] { group1, group2 });
AssertDefinition(content, false, new[] { "-role/group1" }, new[] { group1, group2 });
// can have multiple rule, first one that matches = end
AssertDefinition(content, true, new[] { "+role/group1", "-role/group2" }, new [] { group1, group2 });
AssertDefinition(content, true, new[] { "+role/group1", "-role/group2" }, new[] { group1, group2 });
// mixed type and role rules, both are evaluated and need to match
AssertDefinition(content, true, new[] { "+role/group1", "+content/type1" }, new [] { group1, group2 });
AssertDefinition(content, false, new[] { "+role/group1", "+content/type2" }, new [] { group1, group2 });
AssertDefinition(content, false, new[] { "+role/group33", "+content/type1" }, new [] { group1, group2 });
AssertDefinition(content, true, new[] { "+role/group1", "+content/type1" }, new[] { group1, group2 });
AssertDefinition(content, false, new[] { "+role/group1", "+content/type2" }, new[] { group1, group2 });
AssertDefinition(content, false, new[] { "+role/group33", "+content/type1" }, new[] { group1, group2 });
}
private void AssertDefinition(object source, bool expected, string[] show, IReadOnlyUserGroup[] groups)
{
var definition = JsonConvert.DeserializeObject<ManifestContentAppDefinition>("{" + (show.Length == 0 ? "" : " \"show\": [" + string.Join(",", show.Select(x => "\"" + x + "\"")) + "] ") + "}");
ManifestContentAppDefinition definition = JsonConvert.DeserializeObject<ManifestContentAppDefinition>("{" + (show.Length == 0 ? string.Empty : " \"show\": [" + string.Join(",", show.Select(x => "\"" + x + "\"")) + "] ") + "}");
var factory = new ManifestContentAppFactory(definition, TestHelper.IOHelper);
var app = factory.GetContentAppFor(source, groups);
ContentApp app = factory.GetContentAppFor(source, groups);
if (expected)
{
Assert.IsNotNull(app);
}
else
{
Assert.IsNull(app);
}
}
}
}

View File

@@ -1,21 +1,24 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NUnit.Framework;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Dashboards;
using Umbraco.Core.IO;
using Umbraco.Core.Manifest;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.PropertyEditors.Validators;
using Umbraco.Core.Services;
using Umbraco.Core.Dashboards;
using Umbraco.Core.IO;
using Umbraco.Core.Serialization;
using Umbraco.Core.Services;
using Umbraco.Core.Strings;
using Umbraco.Tests.TestHelpers;
@@ -37,14 +40,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Manifest
new DelimitedValueValidator(),
};
_ioHelper = TestHelper.IOHelper;
var loggerFactory = NullLoggerFactory.Instance;
NullLoggerFactory loggerFactory = NullLoggerFactory.Instance;
_parser = new ManifestParser(AppCaches.Disabled, new ManifestValueValidatorCollection(validators), new ManifestFilterCollection(Array.Empty<IManifestFilter>()), loggerFactory.CreateLogger<ManifestParser>(), loggerFactory, _ioHelper, TestHelper.GetHostingEnvironment(), Mock.Of<IDataTypeService>(), Mock.Of<ILocalizationService>(), new JsonNetSerializer(), Mock.Of<ILocalizedTextService>(), Mock.Of<IShortStringHelper>());
}
[Test]
public void DelimitedValueValidator()
{
const string json = @"{'propertyEditors': [
{
alias: 'Test.Test2',
@@ -64,7 +66,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Manifest
}
]}";
var manifest = _parser.ParseManifest(json);
PackageManifest manifest = _parser.ParseManifest(json);
Assert.AreEqual(1, manifest.ParameterEditors.Length);
Assert.AreEqual(1, manifest.ParameterEditors[0].GetValueEditor().Validators.Count);
@@ -80,7 +82,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Manifest
[Test]
public void CanParseComments()
{
const string json1 = @"
// this is a single-line comment
{
@@ -92,7 +93,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Manifest
}
";
var jobject = (JObject) JsonConvert.DeserializeObject(json1);
var jobject = (JObject)JsonConvert.DeserializeObject(json1);
Assert.AreEqual("2", jobject.Property("x").Value.ToString());
Assert.AreEqual("3", jobject.Property("y").Value.ToString());
Assert.AreEqual("4", jobject.Property("z").Value.ToString());
@@ -115,8 +116,8 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
[Test]
public void CanParseManifest_ScriptsAndStylesheets()
{
var json = "{}";
var manifest = _parser.ParseManifest(json);
string json = "{}";
PackageManifest manifest = _parser.ParseManifest(json);
Assert.AreEqual(0, manifest.Scripts.Length);
json = "{javascript: []}";
@@ -139,7 +140,7 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
Assert.Throws<JsonReaderException>(() => _parser.ParseManifest(json));
json = "{}";
manifest = _parser.ParseManifest(json);
manifest = _parser.ParseManifest(json);
Assert.AreEqual(0, manifest.Stylesheets.Length);
json = "{css: []}";
@@ -154,8 +155,6 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
manifest = _parser.ParseManifest(json);
Assert.AreEqual(2, manifest.Stylesheets.Length);
json = "{propertyEditors: [], javascript: ['~/test.js', '~/test2.js'], css: ['~/stylesheet.css', '~/random-long-name.css']}";
manifest = _parser.ParseManifest(json);
Assert.AreEqual(2, manifest.Scripts.Length);
@@ -212,10 +211,10 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
}
]}";
var manifest = _parser.ParseManifest(json);
PackageManifest manifest = _parser.ParseManifest(json);
Assert.AreEqual(2, manifest.PropertyEditors.Length);
var editor = manifest.PropertyEditors[1];
IDataEditor editor = manifest.PropertyEditors[1];
Assert.IsTrue((editor.Type & EditorType.MacroParameter) > 0);
editor = manifest.PropertyEditors[0];
@@ -223,18 +222,18 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
Assert.AreEqual("Test 1", editor.Name);
Assert.IsFalse((editor.Type & EditorType.MacroParameter) > 0);
var valueEditor = editor.GetValueEditor();
IDataValueEditor valueEditor = editor.GetValueEditor();
Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/PropertyEditors/MyEditor.html"), valueEditor.View);
Assert.AreEqual("int", valueEditor.ValueType);
Assert.IsTrue(valueEditor.HideLabel);
// these two don't make much sense here
// valueEditor.RegexValidator;
// valueEditor.RequiredValidator;
//// valueEditor.RegexValidator;
//// valueEditor.RequiredValidator;
var validators = valueEditor.Validators;
List<IValueValidator> validators = valueEditor.Validators;
Assert.AreEqual(2, validators.Count);
var validator = validators[0];
IValueValidator validator = validators[0];
var v1 = validator as RequiredValidator;
Assert.IsNotNull(v1);
Assert.AreEqual("Required", v1.ValidationName);
@@ -245,19 +244,19 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
Assert.AreEqual("\\d*", v2.Configuration);
// this is not part of the manifest
var preValues = editor.GetConfigurationEditor().DefaultConfiguration;
IDictionary<string, object> preValues = editor.GetConfigurationEditor().DefaultConfiguration;
Assert.IsEmpty(preValues);
var preValueEditor = editor.GetConfigurationEditor();
IConfigurationEditor preValueEditor = editor.GetConfigurationEditor();
Assert.IsNotNull(preValueEditor);
Assert.IsNotNull(preValueEditor.Fields);
Assert.AreEqual(2, preValueEditor.Fields.Count);
var f = preValueEditor.Fields[0];
ConfigurationField f = preValueEditor.Fields[0];
Assert.AreEqual("key1", f.Key);
Assert.AreEqual("Some config 1", f.Name);
Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/PropertyEditors/Views/pre-val1.html"), f.View);
var fvalidators = f.Validators;
List<IValueValidator> fvalidators = f.Validators;
Assert.IsNotNull(fvalidators);
Assert.AreEqual(1, fvalidators.Count);
var fv = fvalidators[0] as RequiredValidator;
@@ -294,27 +293,27 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
}
]}";
var manifest = _parser.ParseManifest(json);
PackageManifest manifest = _parser.ParseManifest(json);
Assert.AreEqual(3, manifest.ParameterEditors.Length);
Assert.IsTrue(manifest.ParameterEditors.All(x => (x.Type & EditorType.MacroParameter) > 0));
var editor = manifest.ParameterEditors[1];
IDataEditor editor = manifest.ParameterEditors[1];
Assert.AreEqual("parameter2", editor.Alias);
Assert.AreEqual("Another parameter", editor.Name);
var config = editor.DefaultConfiguration;
IDictionary<string, object> config = editor.DefaultConfiguration;
Assert.AreEqual(1, config.Count);
Assert.IsTrue(config.ContainsKey("key1"));
Assert.AreEqual("some config val", config["key1"]);
var valueEditor = editor.GetValueEditor();
IDataValueEditor valueEditor = editor.GetValueEditor();
Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/PropertyEditors/CsvEditor.html"), valueEditor.View);
editor = manifest.ParameterEditors[2];
Assert.Throws<InvalidOperationException>(() =>
{
var _ = editor.GetValueEditor();
IDataValueEditor valueEditor = editor.GetValueEditor();
});
}
@@ -353,20 +352,20 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
}
]
}";
var manifest = _parser.ParseManifest(json);
PackageManifest manifest = _parser.ParseManifest(json);
Assert.AreEqual(2, manifest.GridEditors.Length);
var editor = manifest.GridEditors[0];
GridEditor editor = manifest.GridEditors[0];
Assert.AreEqual("small-hero", editor.Alias);
Assert.AreEqual("Small Hero", editor.Name);
Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPlugin/small-hero/editortemplate.html"), editor.View);
Assert.AreEqual(_ioHelper.ResolveUrl("/Views/Partials/Grid/Editors/SmallHero.cshtml"), editor.Render);
Assert.AreEqual("icon-presentation", editor.Icon);
var config = editor.Config;
IDictionary<string, object> config = editor.Config;
Assert.AreEqual(2, config.Count);
Assert.IsTrue(config.ContainsKey("image"));
var c = config["image"];
object c = config["image"];
Assert.IsInstanceOf<JObject>(c); // FIXME: is this what we want?
Assert.IsTrue(config.ContainsKey("link"));
c = config["link"];
@@ -394,11 +393,11 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
}
]}";
var manifest = _parser.ParseManifest(json);
PackageManifest manifest = _parser.ParseManifest(json);
Assert.AreEqual(2, manifest.ContentApps.Length);
Assert.IsInstanceOf<ManifestContentAppDefinition>(manifest.ContentApps[0]);
var app0 = (ManifestContentAppDefinition) manifest.ContentApps[0];
var app0 = (ManifestContentAppDefinition)manifest.ContentApps[0];
Assert.AreEqual("myPackageApp1", app0.Alias);
Assert.AreEqual("My App1", app0.Name);
Assert.AreEqual("icon-foo", app0.Icon);
@@ -431,11 +430,11 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
}
]}";
var manifest = _parser.ParseManifest(json);
PackageManifest manifest = _parser.ParseManifest(json);
Assert.AreEqual(2, manifest.Dashboards.Length);
Assert.IsInstanceOf<ManifestDashboard>(manifest.Dashboards[0]);
var db0 = manifest.Dashboards[0];
ManifestDashboard db0 = manifest.Dashboards[0];
Assert.AreEqual("something", db0.Alias);
Assert.AreEqual(100, db0.Weight);
Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/Dashboards/one.html"), db0.View);
@@ -448,7 +447,7 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
Assert.AreEqual("foo", db0.AccessRules[1].Value);
Assert.IsInstanceOf<ManifestDashboard>(manifest.Dashboards[1]);
var db1 = manifest.Dashboards[1];
ManifestDashboard db1 = manifest.Dashboards[1];
Assert.AreEqual("something.else", db1.Alias);
Assert.AreEqual(-1, db1.Weight);
Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/Dashboards/two.html"), db1.View);
@@ -464,7 +463,7 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2
{ ""alias"": ""hello"", ""name"": ""World"" }
]}";
var manifest = _parser.ParseManifest(json);
PackageManifest manifest = _parser.ParseManifest(json);
Assert.AreEqual(2, manifest.Sections.Length);
Assert.AreEqual("content", manifest.Sections[0].Alias);
Assert.AreEqual("hello", manifest.Sections[1].Alias);

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
@@ -16,13 +19,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
private int _id;
private Guid _key;
protected Item()
{
_propertyChangedInfo = new Dictionary<string, bool>();
}
protected Item() => _propertyChangedInfo = new Dictionary<string, bool>();
/// <summary>
/// Integer Id
/// Gets or sets the integer Id
/// </summary>
[DataMember]
public int Id
@@ -36,7 +36,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
}
/// <summary>
/// Guid based Id
/// Gets or sets the Guid based Id
/// </summary>
/// <remarks>The key is currectly used to store the Unique Id from the
/// umbracoNode table, which many of the entities are based on.</remarks>
@@ -66,8 +66,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
public DateTime? DeleteDate { get; set; }
/// <summary>
/// Gets or sets the WasCancelled flag, which is used to track
/// whether some action against an entity was cancelled through some event.
/// Gets or sets a value indicating whether some action against an entity was cancelled through some event.
/// This only exists so we have a way to check if an event was cancelled through
/// the new api, which also needs to take effect in the legacy api.
/// </summary>
@@ -86,7 +85,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
protected virtual void OnPropertyChanged(PropertyInfo propertyInfo)
{
if (_withChanges == false)
{
return;
}
_propertyChangedInfo[propertyInfo.Name] = true;
@@ -96,7 +97,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
public virtual void ResetIdentity()
{
_hasIdentity = false;
_id = default(int);
_id = default;
}
/// <summary>
@@ -111,15 +112,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
/// <summary>
/// Method to call on entity saved/updated
/// </summary>
internal virtual void UpdatingEntity()
{
UpdateDate = DateTime.Now;
}
internal virtual void UpdatingEntity() => UpdateDate = DateTime.Now;
/// <summary>
/// Tracks the properties that have changed
/// </summary>
//private readonly IDictionary<string, bool> _propertyChangedInfo = new Dictionary<string, bool>();
private readonly IDictionary<string, bool> _propertyChangedInfo;
/// <summary>
@@ -127,24 +124,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
/// </summary>
/// <param name="propertyName">Name of the property to check</param>
/// <returns>True if Property is dirty, otherwise False</returns>
public virtual bool IsPropertyDirty(string propertyName)
{
return _propertyChangedInfo.Any(x => x.Key == propertyName);
}
public virtual bool IsPropertyDirty(string propertyName) => _propertyChangedInfo.Any(x => x.Key == propertyName);
public virtual IEnumerable<string> GetDirtyProperties()
{
return _propertyChangedInfo.Keys;
}
public virtual IEnumerable<string> GetDirtyProperties() => _propertyChangedInfo.Keys;
/// <summary>
/// Indicates whether the current entity is dirty.
/// </summary>
/// <returns>True if entity is dirty, otherwise False</returns>
public virtual bool IsDirty()
{
return _propertyChangedInfo.Any();
}
public virtual bool IsDirty() => _propertyChangedInfo.Any();
/// <summary>
/// Resets dirty properties by clearing the dictionary used to track changes.
@@ -153,29 +141,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
/// Please note that resetting the dirty properties could potentially
/// obstruct the saving of a new or updated entity.
/// </remarks>
public virtual void ResetDirtyProperties()
{
_propertyChangedInfo.Clear();
}
public virtual void ResetDirtyProperties() => _propertyChangedInfo.Clear();
/// <summary>
/// Disables change tracking.
/// </summary>
public void DisableChangeTracking()
{
_withChanges = false;
}
public void DisableChangeTracking() => _withChanges = false;
/// <summary>
/// Enables change tracking.
/// </summary>
public void EnableChangeTracking()
{
_withChanges = true;
}
public void EnableChangeTracking() => _withChanges = true;
/// <summary>
/// Indicates whether the current entity has an identity, eg. Id.
/// Gets or sets a value indicating whether the current entity has an identity, eg. Id.
/// </summary>
public virtual bool HasIdentity
{
@@ -183,15 +162,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
protected set => _hasIdentity = value;
}
public static bool operator ==(Item left, Item right)
{
return ReferenceEquals(left, right);
}
public static bool operator ==(Item left, Item right) => ReferenceEquals(left, right);
public static bool operator !=(Item left, Item right)
{
return !(left == right);
}
public static bool operator !=(Item left, Item right) => !(left == right);
/*public virtual bool SameIdentityAs(IEntity other)
{
@@ -249,9 +222,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
return _hash.Value;
}*/
public object DeepClone()
{
return this.MemberwiseClone();
}
public object DeepClone() => this.MemberwiseClone();
}
}

View File

@@ -1,7 +1,10 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
{
{
public class OrderItem : Item
{
public readonly int PartNumber;
@@ -10,8 +13,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
private int _quantity = 0;
public OrderItem(int partNumber, string description,
int quantity, double unitPrice)
public OrderItem(int partNumber, string description, int quantity, double unitPrice)
{
PartNumber = partNumber;
Description = description;
@@ -21,22 +23,26 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
public int Quantity
{
get { return _quantity; }
get => _quantity;
set
{
if (value < 0)
{
throw new ArgumentException("Quantity cannot be negative.");
}
_quantity = value;
}
}
public override string ToString()
{
return string.Format(
public override string ToString() =>
string.Format(
"{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
PartNumber, _quantity, Description, UnitPrice,
PartNumber,
_quantity,
Description,
UnitPrice,
UnitPrice * _quantity);
}
}
}

View File

@@ -1,4 +1,7 @@
using System.Collections.Generic;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;

View File

@@ -1,4 +1,7 @@
using System.Collections.Generic;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
@@ -10,31 +13,32 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
// The parameterless constructor of the base class creates a
// KeyedCollection with an internal dictionary. For this code
// example, no other constructors are exposed.
//
public SimpleOrder() : base() { }
public SimpleOrder(IEnumerable<OrderItem> properties)
public SimpleOrder()
: base()
{
Reset(properties);
}
public SimpleOrder(IEnumerable<OrderItem> properties) => Reset(properties);
// This is the only method that absolutely must be overridden,
// because without it the KeyedCollection cannot extract the
// keys from the items. The input parameter type is the
// second generic type argument, in this case OrderItem, and
// the return value type is the first generic type argument,
// in this case int.
//
protected override int GetKeyForItem(OrderItem item)
{
protected override int GetKeyForItem(OrderItem item) =>
// In this example, the key is the part number.
return item.PartNumber;
}
item.PartNumber;
internal void Reset(IEnumerable<OrderItem> properties)
{
Clear();
foreach (var property in properties) Add(property);
foreach (OrderItem property in properties)
{
Add(property);
}
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
@@ -46,7 +50,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
protected override void RemoveItem(int index)
{
var removed = this[index];
OrderItem removed = this[index];
base.RemoveItem(index);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));
}
@@ -63,16 +67,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public new bool Contains(int partNumber)
{
return this.Any(x => x.PartNumber == partNumber);
}
public new bool Contains(int partNumber) => this.Any(x => x.PartNumber == partNumber);
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
{
CollectionChanged?.Invoke(this, args);
}
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args) => CollectionChanged?.Invoke(this, args);
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Linq;
using Moq;
using NUnit.Framework;
@@ -15,11 +18,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void DirtyProperty_Reset_Clears_SavedPublishedState()
{
var contentTypeService = Mock.Of<IContentTypeService>();
var contentType = ContentTypeBuilder.CreateTextPageContentType();
IContentTypeService contentTypeService = Mock.Of<IContentTypeService>();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
content.PublishedState = PublishedState.Publishing;
Assert.IsFalse(content.Published);
@@ -31,15 +34,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void DirtyProperty_OnlyIfActuallyChanged_Content()
{
var contentTypeService = Mock.Of<IContentTypeService>();
var contentType = ContentTypeBuilder.CreateTextPageContentType();
IContentTypeService contentTypeService = Mock.Of<IContentTypeService>();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// if you assign a content property with its value it is not dirty
// if you assign it with another value then back, it is dirty
content.ResetDirtyProperties(false);
Assert.IsFalse(content.IsPropertyDirty("Published"));
content.Published = true;
@@ -56,16 +58,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void DirtyProperty_OnlyIfActuallyChanged_User()
{
var contentTypeService = Mock.Of<IContentTypeService>();
var contentType = ContentTypeBuilder.CreateTextPageContentType();
IContentTypeService contentTypeService = Mock.Of<IContentTypeService>();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
var prop = content.Properties.First();
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
IProperty prop = content.Properties.First();
// if you assign a user property with its value it is not dirty
// if you assign it with another value then back, it is dirty
prop.SetValue("A");
content.ResetDirtyProperties(false);
Assert.IsFalse(prop.IsDirty());
@@ -83,15 +84,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void DirtyProperty_UpdateDate()
{
var contentTypeService = Mock.Of<IContentTypeService>();
var contentType = ContentTypeBuilder.CreateTextPageContentType();
IContentTypeService contentTypeService = Mock.Of<IContentTypeService>();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
var prop = content.Properties.First();
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
IProperty prop = content.Properties.First();
content.ResetDirtyProperties(false);
var d = content.UpdateDate;
DateTime d = content.UpdateDate;
prop.SetValue("A");
Assert.IsTrue(content.IsAnyUserPropertyDirty());
Assert.IsFalse(content.IsEntityDirty());
@@ -109,11 +110,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void DirtyProperty_WasDirty_ContentProperty()
{
var contentTypeService = Mock.Of<IContentTypeService>();
var contentType = ContentTypeBuilder.CreateTextPageContentType();
IContentTypeService contentTypeService = Mock.Of<IContentTypeService>();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
content.ResetDirtyProperties(false);
Assert.IsFalse(content.IsDirty());
Assert.IsFalse(content.WasDirty());
@@ -139,11 +140,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void DirtyProperty_WasDirty_ContentSortOrder()
{
var contentTypeService = Mock.Of<IContentTypeService>();
var contentType = ContentTypeBuilder.CreateTextPageContentType();
IContentTypeService contentTypeService = Mock.Of<IContentTypeService>();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
content.ResetDirtyProperties(false);
Assert.IsFalse(content.IsDirty());
Assert.IsFalse(content.WasDirty());
@@ -169,12 +170,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void DirtyProperty_WasDirty_UserProperty()
{
var contentTypeService = Mock.Of<IContentTypeService>();
var contentType = ContentTypeBuilder.CreateTextPageContentType();
IContentTypeService contentTypeService = Mock.Of<IContentTypeService>();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
var prop = content.Properties.First();
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
IProperty prop = content.Properties.First();
content.ResetDirtyProperties(false);
Assert.IsFalse(content.IsDirty());
Assert.IsFalse(content.WasDirty());
@@ -189,13 +190,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
prop.SetValue("b");
content.ResetDirtyProperties(true); // what PersistUpdatedItem does
Assert.IsFalse(content.IsDirty());
//Assert.IsFalse(content.WasDirty()); // not impacted by user properties
//// Assert.IsFalse(content.WasDirty()); // not impacted by user properties
Assert.IsTrue(content.WasDirty()); // now it is!
prop.SetValue("a");
prop.SetValue("b");
content.ResetDirtyProperties(); // what PersistUpdatedItem does
Assert.IsFalse(content.IsDirty());
//Assert.IsFalse(content.WasDirty()); // not impacted by user properties
//// Assert.IsFalse(content.WasDirty()); // not impacted by user properties
Assert.IsTrue(content.WasDirty()); // now it is!
}
}

View File

@@ -1,4 +1,8 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -11,7 +15,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Release_Date_Less_Than_Expire_Date()
{
var now = DateTime.Now;
DateTime now = DateTime.Now;
var schedule = new ContentScheduleCollection();
Assert.IsFalse(schedule.Add(now, now));
}
@@ -19,7 +23,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Cannot_Add_Duplicate_Dates_Invariant()
{
var now = DateTime.Now;
DateTime now = DateTime.Now;
var schedule = new ContentScheduleCollection();
schedule.Add(now, null);
Assert.Throws<ArgumentException>(() => schedule.Add(null, now));
@@ -28,7 +32,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Cannot_Add_Duplicate_Dates_Variant()
{
var now = DateTime.Now;
DateTime now = DateTime.Now;
var schedule = new ContentScheduleCollection();
schedule.Add(now, null);
schedule.Add("en-US", now, null);
@@ -39,10 +43,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Remove_Invariant()
{
var now = DateTime.Now;
DateTime now = DateTime.Now;
var schedule = new ContentScheduleCollection();
schedule.Add(now, null);
var invariantSched = schedule.GetSchedule(string.Empty);
IEnumerable<ContentSchedule> invariantSched = schedule.GetSchedule(string.Empty);
schedule.Remove(invariantSched.First());
Assert.AreEqual(0, schedule.FullSchedule.Count());
}
@@ -50,15 +54,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Remove_Variant()
{
var now = DateTime.Now;
DateTime now = DateTime.Now;
var schedule = new ContentScheduleCollection();
schedule.Add(now, null);
schedule.Add("en-US", now, null);
var invariantSched = schedule.GetSchedule(string.Empty);
IEnumerable<ContentSchedule> invariantSched = schedule.GetSchedule(string.Empty);
schedule.Remove(invariantSched.First());
Assert.AreEqual(0, schedule.GetSchedule(string.Empty).Count());
Assert.AreEqual(1, schedule.FullSchedule.Count());
var variantSched = schedule.GetSchedule("en-US");
IEnumerable<ContentSchedule> variantSched = schedule.GetSchedule("en-US");
schedule.Remove(variantSched.First());
Assert.AreEqual(0, schedule.GetSchedule("en-US").Count());
Assert.AreEqual(0, schedule.FullSchedule.Count());
@@ -67,7 +71,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Clear_Start_Invariant()
{
var now = DateTime.Now;
DateTime now = DateTime.Now;
var schedule = new ContentScheduleCollection();
schedule.Add(now, now.AddDays(1));
@@ -81,7 +85,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Clear_End_Variant()
{
var now = DateTime.Now;
DateTime now = DateTime.Now;
var schedule = new ContentScheduleCollection();
schedule.Add(now, now.AddDays(1));
schedule.Add("en-US", now, now.AddDays(1));
@@ -102,6 +106,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(1, schedule.GetSchedule("en-US", ContentScheduleAction.Release).Count());
Assert.AreEqual(2, schedule.FullSchedule.Count());
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
@@ -25,18 +28,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[TestFixture]
public class ContentTests
{
private IContentTypeService _contentTypeService = Mock.Of<IContentTypeService>();
private readonly IContentTypeService _contentTypeService = Mock.Of<IContentTypeService>();
[Test]
public void Variant_Culture_Names_Track_Dirty_Changes()
{
var contentType = new ContentTypeBuilder()
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.WithContentVariation(ContentVariation.Culture)
.Build();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = new ContentBuilder()
Content content = new ContentBuilder()
.WithId(1)
.WithVersionId(1)
.WithName("content")
@@ -45,33 +48,33 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
const string langFr = "fr-FR";
Assert.IsFalse(content.IsPropertyDirty("CultureInfos")); //hasn't been changed
Assert.IsFalse(content.IsPropertyDirty("CultureInfos")); // hasn't been changed
Thread.Sleep(500); //The "Date" wont be dirty if the test runs too fast since it will be the same date
Thread.Sleep(500); // The "Date" wont be dirty if the test runs too fast since it will be the same date
content.SetCultureName("name-fr", langFr);
Assert.IsTrue(content.IsPropertyDirty("CultureInfos")); //now it will be changed since the collection has changed
var frCultureName = content.CultureInfos[langFr];
Assert.IsTrue(content.IsPropertyDirty("CultureInfos")); // now it will be changed since the collection has changed
ContentCultureInfos frCultureName = content.CultureInfos[langFr];
Assert.IsTrue(frCultureName.IsPropertyDirty("Date"));
content.ResetDirtyProperties();
Assert.IsFalse(content.IsPropertyDirty("CultureInfos")); //it's been reset
Assert.IsFalse(content.IsPropertyDirty("CultureInfos")); // it's been reset
Assert.IsTrue(content.WasPropertyDirty("CultureInfos"));
Thread.Sleep(500); //The "Date" wont be dirty if the test runs too fast since it will be the same date
Thread.Sleep(500); // The "Date" wont be dirty if the test runs too fast since it will be the same date
content.SetCultureName("name-fr", langFr);
Assert.IsTrue(frCultureName.IsPropertyDirty("Date"));
Assert.IsTrue(content.IsPropertyDirty("CultureInfos")); //it's true now since we've updated a name
Assert.IsTrue(content.IsPropertyDirty("CultureInfos")); // it's true now since we've updated a name
}
[Test]
public void Variant_Published_Culture_Names_Track_Dirty_Changes()
{
var contentType = new ContentTypeBuilder()
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.WithContentVariation(ContentVariation.Culture)
.Build();
var content = new ContentBuilder()
Content content = new ContentBuilder()
.WithId(1)
.WithVersionId(1)
.WithName("content")
@@ -82,38 +85,38 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
content.ChangeContentType(contentType);
Assert.IsFalse(content.IsPropertyDirty("PublishCultureInfos")); //hasn't been changed
Assert.IsFalse(content.IsPropertyDirty("PublishCultureInfos")); // hasn't been changed
Thread.Sleep(500); //The "Date" wont be dirty if the test runs too fast since it will be the same date
Thread.Sleep(500); // The "Date" wont be dirty if the test runs too fast since it will be the same date
content.SetCultureName("name-fr", langFr);
content.PublishCulture(CultureImpact.Explicit(langFr, false)); //we've set the name, now we're publishing it
Assert.IsTrue(content.IsPropertyDirty("PublishCultureInfos")); //now it will be changed since the collection has changed
var frCultureName = content.PublishCultureInfos[langFr];
content.PublishCulture(CultureImpact.Explicit(langFr, false)); // we've set the name, now we're publishing it
Assert.IsTrue(content.IsPropertyDirty("PublishCultureInfos")); // now it will be changed since the collection has changed
ContentCultureInfos frCultureName = content.PublishCultureInfos[langFr];
Assert.IsTrue(frCultureName.IsPropertyDirty("Date"));
content.ResetDirtyProperties();
Assert.IsFalse(content.IsPropertyDirty("PublishCultureInfos")); //it's been reset
Assert.IsFalse(content.IsPropertyDirty("PublishCultureInfos")); // it's been reset
Assert.IsTrue(content.WasPropertyDirty("PublishCultureInfos"));
Thread.Sleep(500); //The "Date" wont be dirty if the test runs too fast since it will be the same date
Thread.Sleep(500); // The "Date" wont be dirty if the test runs too fast since it will be the same date
content.SetCultureName("name-fr", langFr);
content.PublishCulture(CultureImpact.Explicit(langFr, false)); //we've set the name, now we're publishing it
content.PublishCulture(CultureImpact.Explicit(langFr, false)); // we've set the name, now we're publishing it
Assert.IsTrue(frCultureName.IsPropertyDirty("Date"));
Assert.IsTrue(content.IsPropertyDirty("PublishCultureInfos")); //it's true now since we've updated a name
Assert.IsTrue(content.IsPropertyDirty("PublishCultureInfos")); // it's true now since we've updated a name
}
[Test]
public void Get_Non_Grouped_Properties()
{
var contentType = ContentTypeBuilder.CreateSimpleContentType();
ContentType contentType = ContentTypeBuilder.CreateSimpleContentType();
// Add non-grouped properties
var pt1 = new PropertyTypeBuilder()
PropertyType pt1 = new PropertyTypeBuilder()
.WithAlias("nonGrouped1")
.WithName("Non Grouped 1")
.Build();
var pt2 = new PropertyTypeBuilder()
PropertyType pt2 = new PropertyTypeBuilder()
.WithAlias("nonGrouped2")
.WithName("Non Grouped 2")
.Build();
@@ -124,9 +127,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
contentType.ResetDirtyProperties(false);
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateSimpleContent(contentType);
Content content = ContentBuilder.CreateSimpleContent(contentType);
var nonGrouped = content.GetNonGroupedProperties();
IEnumerable<IProperty> nonGrouped = content.GetNonGroupedProperties();
Assert.AreEqual(2, nonGrouped.Count());
Assert.AreEqual(5, content.Properties.Count());
@@ -135,15 +138,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void All_Dirty_Properties_Get_Reset()
{
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
content.ResetDirtyProperties(false);
Assert.IsFalse(content.IsDirty());
foreach (var prop in content.Properties)
foreach (IProperty prop in content.Properties)
{
Assert.IsFalse(prop.IsDirty());
}
@@ -153,10 +156,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Verify_Mocked_Content()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
@@ -168,10 +171,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Change_Property_Value()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
content.Properties["title"].SetValue("This is the new title");
@@ -186,10 +189,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Set_Property_Value_As_String()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
content.SetValue("title", "This is the new title");
@@ -204,15 +207,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Clone_Content_With_Reset_Identity()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
content.Id = 10;
content.Key = new Guid("29181B97-CB8F-403F-86DE-5FEB497F4800");
// Act
var clone = content.DeepCloneWithResetIdentities();
IContent clone = content.DeepCloneWithResetIdentities();
// Assert
Assert.AreNotSame(clone, content);
@@ -225,7 +228,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private static IProfilingLogger GetTestProfilingLogger()
{
var logger = NullLoggerFactory.Instance.CreateLogger<ProfilingLogger>();
ILogger<ProfilingLogger> logger = NullLoggerFactory.Instance.CreateLogger<ProfilingLogger>();
var profiler = new TestProfiler();
return new ProfilingLogger(logger, profiler);
}
@@ -235,14 +238,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Deep_Clone_Perf_Test()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.Id = 99;
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
var i = 200;
foreach (var property in content.Properties)
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
int i = 200;
foreach (IProperty property in content.Properties)
{
property.Id = ++i;
}
content.Id = 10;
content.CreateDate = DateTime.Now;
content.CreatorId = 22;
@@ -250,7 +254,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
content.Level = 3;
content.Path = "-1,4,10";
content.ContentSchedule.Add(DateTime.Now, DateTime.Now.AddDays(1));
//content.ChangePublishedState(PublishedState.Published);
//// content.ChangePublishedState(PublishedState.Published);
content.SortOrder = 5;
content.TemplateId = 88;
content.Trashed = false;
@@ -260,13 +264,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
var runtimeCache = new ObjectCacheAppCache();
runtimeCache.Insert(content.Id.ToString(CultureInfo.InvariantCulture), () => content);
var proflog = GetTestProfilingLogger();
IProfilingLogger proflog = GetTestProfilingLogger();
using (proflog.DebugDuration<ContentTests>("STARTING PERF TEST WITH RUNTIME CACHE"))
{
for (int j = 0; j < 1000; j++)
{
var clone = runtimeCache.Get(content.Id.ToString(CultureInfo.InvariantCulture));
object clone = runtimeCache.Get(content.Id.ToString(CultureInfo.InvariantCulture));
}
}
@@ -283,12 +287,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Deep_Clone()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.Id = 99;
contentType.Variations = ContentVariation.Culture;
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
content.SetCultureName("Hello", "en-US");
content.SetCultureName("World", "es-ES");
@@ -297,11 +301,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
// should not try to clone something that's not Published or Unpublished
// (and in fact it will not work)
// but we cannot directly set the state to Published - hence this trick
//content.ChangePublishedState(PublishedState.Publishing);
// content.ChangePublishedState(PublishedState.Publishing);
content.ResetDirtyProperties(false); // => .Published
var i = 200;
foreach (var property in content.Properties)
int i = 200;
foreach (IProperty property in content.Properties)
{
property.Id = ++i;
}
@@ -347,7 +351,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.WriterId, content.WriterId);
Assert.AreNotSame(clone.Properties, content.Properties);
Assert.AreEqual(clone.Properties.Count(), content.Properties.Count());
for (var index = 0; index < content.Properties.Count; index++)
for (int index = 0; index < content.Properties.Count; index++)
{
Assert.AreNotSame(clone.Properties[index], content.Properties[index]);
Assert.AreEqual(clone.Properties[index], content.Properties[index]);
@@ -355,7 +359,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreNotSame(clone.PublishCultureInfos, content.PublishCultureInfos);
Assert.AreEqual(clone.PublishCultureInfos.Count, content.PublishCultureInfos.Count);
foreach (var key in content.PublishCultureInfos.Keys)
foreach (string key in content.PublishCultureInfos.Keys)
{
Assert.AreNotSame(clone.PublishCultureInfos[key], content.PublishCultureInfos[key]);
Assert.AreEqual(clone.PublishCultureInfos[key], content.PublishCultureInfos[key]);
@@ -363,28 +367,27 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreNotSame(clone.CultureInfos, content.CultureInfos);
Assert.AreEqual(clone.CultureInfos.Count, content.CultureInfos.Count);
foreach (var key in content.CultureInfos.Keys)
foreach (string key in content.CultureInfos.Keys)
{
Assert.AreNotSame(clone.CultureInfos[key], content.CultureInfos[key]);
Assert.AreEqual(clone.CultureInfos[key], content.CultureInfos[key]);
}
// This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
System.Reflection.PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(content, null));
}
// Need to ensure the event handlers are wired
var asDirty = (ICanBeDirty)clone;
Assert.IsFalse(asDirty.IsPropertyDirty("Properties"));
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("blah")
.Build();
var newProperty = new PropertyBuilder()
IProperty newProperty = new PropertyBuilder()
.WithId(1)
.WithPropertyType(propertyType)
.Build();
@@ -398,19 +401,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Remember_Dirty_Properties()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.Id = 99;
contentType.Variations = ContentVariation.Culture;
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
content.SetCultureName("Hello", "en-US");
content.SetCultureName("World", "es-ES");
content.PublishCulture(CultureImpact.All);
var i = 200;
foreach (var property in content.Properties)
int i = 200;
foreach (IProperty property in content.Properties)
{
property.Id = ++i;
}
@@ -445,14 +448,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.IsTrue(content.WasPropertyDirty(nameof(Content.Trashed)));
Assert.IsTrue(content.WasPropertyDirty(nameof(Content.UpdateDate)));
Assert.IsTrue(content.WasPropertyDirty(nameof(Content.WriterId)));
foreach (var prop in content.Properties)
foreach (IProperty prop in content.Properties)
{
Assert.IsTrue(prop.WasDirty());
Assert.IsTrue(prop.WasPropertyDirty("Id"));
}
Assert.IsTrue(content.WasPropertyDirty("CultureInfos"));
foreach (var culture in content.CultureInfos)
foreach (ContentCultureInfos culture in content.CultureInfos)
{
Assert.IsTrue(culture.WasDirty());
Assert.IsTrue(culture.WasPropertyDirty("Name"));
@@ -460,7 +463,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
}
Assert.IsTrue(content.WasPropertyDirty("PublishCultureInfos"));
foreach (var culture in content.PublishCultureInfos)
foreach (ContentCultureInfos culture in content.PublishCultureInfos)
{
Assert.IsTrue(culture.WasDirty());
Assert.IsTrue(culture.WasPropertyDirty("Name"));
@@ -472,13 +475,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Serialize_Without_Error()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.Id = 99;
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
var i = 200;
foreach (var property in content.Properties)
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
int i = 200;
foreach (IProperty property in content.Properties)
{
property.Id = ++i;
}
@@ -490,14 +493,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
content.Level = 3;
content.Path = "-1,4,10";
content.ContentSchedule.Add(DateTime.Now, DateTime.Now.AddDays(1));
//content.ChangePublishedState(PublishedState.Publishing);
//// content.ChangePublishedState(PublishedState.Publishing);
content.SortOrder = 5;
content.TemplateId = 88;
content.Trashed = false;
content.UpdateDate = DateTime.Now;
content.WriterId = 23;
var json = JsonConvert.SerializeObject(content);
string json = JsonConvert.SerializeObject(content);
Debug.Print(json);
}
@@ -526,10 +529,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Change_Property_Value_Through_Anonymous_Object()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
content.PropertyValues(new { title = "This is the new title" });
@@ -546,10 +549,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Verify_Dirty_Property_On_Content()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
content.ResetDirtyProperties();
@@ -564,7 +567,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Add_PropertyGroup_On_ContentType()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
// Act
contentType.PropertyGroups.Add(new PropertyGroup(true) { Name = "Test Group", SortOrder = 3 });
@@ -577,7 +580,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Remove_PropertyGroup_From_ContentType()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.ResetDirtyProperties();
// Act
@@ -585,17 +588,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
// Assert
Assert.That(contentType.PropertyGroups.Count, Is.EqualTo(1));
//Assert.That(contentType.IsPropertyDirty("PropertyGroups"), Is.True);
//// Assert.That(contentType.IsPropertyDirty("PropertyGroups"), Is.True);
}
[Test]
public void Can_Add_PropertyType_To_Group_On_ContentType()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
// Act
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("subtitle")
.WithName("Subtitle")
.Build();
@@ -609,13 +612,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Add_New_Property_To_New_PropertyType()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("subtitle")
.WithName("Subtitle")
.Build();
@@ -633,13 +636,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Add_New_Property_To_New_PropertyType_In_New_PropertyGroup()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("subtitle")
.WithName("Subtitle")
.Build();
@@ -660,13 +663,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Update_PropertyType_Through_Content_Properties()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act - note that the PropertyType's properties like SortOrder is not updated through the Content object
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("title")
.WithName("Title")
.Build();
@@ -682,18 +685,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Change_ContentType_On_Content()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
var simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
content.ChangeContentType(simpleContentType);
// Assert
Assert.That(content.Properties.Contains("author"), Is.True);
//Note: There was 4 properties, after changing ContentType 1 has been added (no properties are deleted)
// Note: There were 4 properties, after changing ContentType 1 has been added (no properties are deleted).
Assert.That(content.Properties.Count, Is.EqualTo(5));
}
@@ -701,11 +705,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Change_ContentType_On_Content_And_Set_Property_Value()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
var simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
content.ChangeContentType(simpleContentType);
@@ -720,11 +724,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Change_ContentType_On_Content_And_Still_Get_Old_Properties()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
var simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
// Act
content.ChangeContentType(simpleContentType);
@@ -742,29 +746,30 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Change_ContentType_On_Content_And_Clear_Old_PropertyTypes()
{
throw new NotImplementedException();
//Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
//// Arrange
//var contentType = ContentTypeBuilder.CreateTextPageContentType();
//var simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
//var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
//// Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
//// Act
//content.ChangeContentType(simpleContentType, true);
////// Arrange
//// var contentType = ContentTypeBuilder.CreateTextPageContentType();
//// var simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
//// var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
//// Assert
//Assert.That(content.Properties.Contains("author"), Is.True);
//Assert.That(content.Properties.Contains("keywords"), Is.False);
//Assert.That(content.Properties.Contains("description"), Is.False);
////// Act
//// content.ChangeContentType(simpleContentType, true);
////// Assert
//// Assert.That(content.Properties.Contains("author"), Is.True);
//// Assert.That(content.Properties.Contains("keywords"), Is.False);
//// Assert.That(content.Properties.Contains("description"), Is.False);
}
[Test]
public void Can_Verify_Content_Is_Published()
{
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
content.ResetDirtyProperties();
content.PublishedState = PublishedState.Publishing;
@@ -797,7 +802,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Adding_PropertyGroup_To_ContentType_Results_In_Dirty_Entity()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.ResetDirtyProperties();
// Act
@@ -807,19 +812,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
// Assert
Assert.That(contentType.IsDirty(), Is.True);
Assert.That(contentType.PropertyGroups.Any(x => x.Name == "Test Group"), Is.True);
//Assert.That(contentType.IsPropertyDirty("PropertyGroups"), Is.True);
//// Assert.That(contentType.IsPropertyDirty("PropertyGroups"), Is.True);
}
[Test]
public void After_Committing_Changes_Was_Dirty_Is_True()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.ResetDirtyProperties(); //reset
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.ResetDirtyProperties(); // reset
// Act
contentType.Alias = "newAlias";
contentType.ResetDirtyProperties(); //this would be like committing the entity
contentType.ResetDirtyProperties(); // this would be like committing the entity
// Assert
Assert.That(contentType.IsDirty(), Is.False);
@@ -831,11 +836,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void After_Committing_Changes_Was_Dirty_Is_True_On_Changed_Property()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.ResetDirtyProperties(); //reset
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.ResetDirtyProperties(); // reset
Mock.Get(_contentTypeService).As<IContentTypeBaseService>().Setup(x => x.Get(It.IsAny<int>())).Returns(contentType);
var content = ContentBuilder.CreateTextpageContent(contentType, "test", -1);
Content content = ContentBuilder.CreateTextpageContent(contentType, "test", -1);
content.ResetDirtyProperties();
// Act
@@ -848,13 +853,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.That(content.Properties[0].IsDirty(), Is.True);
Assert.That(content.Properties["title"].IsDirty(), Is.True);
content.ResetDirtyProperties(); //this would be like committing the entity
content.ResetDirtyProperties(); // this would be like committing the entity
// Assert
Assert.That(content.WasDirty(), Is.True);
Assert.That(content.Properties[0].WasDirty(), Is.True);
Assert.That(content.WasPropertyDirty("title"), Is.True);
Assert.That(content.Properties["title"].IsDirty(), Is.False);
Assert.That(content.Properties["title"].WasDirty(), Is.True);
@@ -864,7 +868,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void If_Not_Committed_Was_Dirty_Is_False()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
// Act
contentType.Alias = "newAlias";
@@ -878,7 +882,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Detect_That_A_Property_Is_Removed()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
Assert.That(contentType.WasPropertyDirty("HasPropertyTypeBeenRemoved"), Is.False);
// Act
@@ -892,11 +896,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Adding_PropertyType_To_PropertyGroup_On_ContentType_Results_In_Dirty_Entity()
{
// Arrange
var contentType = ContentTypeBuilder.CreateTextPageContentType();
ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();
contentType.ResetDirtyProperties();
// Act
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("subtitle")
.WithName("Subtitle")
.Build();
@@ -912,18 +916,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Compose_Composite_ContentType_Collection()
{
// Arrange
var simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
var propertyType = new PropertyTypeBuilder()
ContentType simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("coauthor")
.WithName("Co-author")
.Build();
var simple2ContentType = ContentTypeBuilder.CreateSimpleContentType("anotherSimple", "Another Simple Page",
ContentType simple2ContentType = ContentTypeBuilder.CreateSimpleContentType(
"anotherSimple",
"Another Simple Page",
propertyTypeCollection: new PropertyTypeCollection(true, new List<PropertyType> { propertyType }));
// Act
var added = simpleContentType.AddContentType(simple2ContentType);
var compositionPropertyGroups = simpleContentType.CompositionPropertyGroups;
var compositionPropertyTypes = simpleContentType.CompositionPropertyTypes;
bool added = simpleContentType.AddContentType(simple2ContentType);
IEnumerable<PropertyGroup> compositionPropertyGroups = simpleContentType.CompositionPropertyGroups;
IEnumerable<IPropertyType> compositionPropertyTypes = simpleContentType.CompositionPropertyTypes;
// Assert
Assert.That(added, Is.True);
@@ -935,20 +941,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Compose_Nested_Composite_ContentType_Collection()
{
// Arrange
var metaContentType = ContentTypeBuilder.CreateMetaContentType();
var simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
var propertyType = new PropertyTypeBuilder()
ContentType metaContentType = ContentTypeBuilder.CreateMetaContentType();
ContentType simpleContentType = ContentTypeBuilder.CreateSimpleContentType();
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("coauthor")
.WithName("Co-author")
.Build();
var simple2ContentType = ContentTypeBuilder.CreateSimpleContentType("anotherSimple", "Another Simple Page",
ContentType simple2ContentType = ContentTypeBuilder.CreateSimpleContentType(
"anotherSimple",
"Another Simple Page",
propertyTypeCollection: new PropertyTypeCollection(true, new List<PropertyType> { propertyType }));
// Act
var addedMeta = simple2ContentType.AddContentType(metaContentType);
var added = simpleContentType.AddContentType(simple2ContentType);
var compositionPropertyGroups = simpleContentType.CompositionPropertyGroups;
var compositionPropertyTypes = simpleContentType.CompositionPropertyTypes;
bool addedMeta = simple2ContentType.AddContentType(metaContentType);
bool added = simpleContentType.AddContentType(simple2ContentType);
IEnumerable<PropertyGroup> compositionPropertyGroups = simpleContentType.CompositionPropertyGroups;
IEnumerable<IPropertyType> compositionPropertyTypes = simpleContentType.CompositionPropertyTypes;
// Assert
Assert.That(addedMeta, Is.True);
@@ -961,35 +969,39 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Avoid_Circular_Dependencies_In_Composition()
{
var textPage = ContentTypeBuilder.CreateTextPageContentType();
var parent = ContentTypeBuilder.CreateSimpleContentType("parent", "Parent", null, randomizeAliases: true);
var meta = ContentTypeBuilder.CreateMetaContentType();
var propertyType1 = new PropertyTypeBuilder()
ContentType textPage = ContentTypeBuilder.CreateTextPageContentType();
ContentType parent = ContentTypeBuilder.CreateSimpleContentType("parent", "Parent", null, randomizeAliases: true);
ContentType meta = ContentTypeBuilder.CreateMetaContentType();
PropertyType propertyType1 = new PropertyTypeBuilder()
.WithAlias("coauthor")
.WithName("Co-author")
.Build();
var mixin1 = ContentTypeBuilder.CreateSimpleContentType("mixin1", "Mixin1",
ContentType mixin1 = ContentTypeBuilder.CreateSimpleContentType(
"mixin1",
"Mixin1",
propertyTypeCollection: new PropertyTypeCollection(true, new List<PropertyType> { propertyType1 }));
var propertyType2 = new PropertyTypeBuilder()
PropertyType propertyType2 = new PropertyTypeBuilder()
.WithAlias("author")
.WithName("Author")
.Build();
var mixin2 = ContentTypeBuilder.CreateSimpleContentType("mixin2", "Mixin2",
ContentType mixin2 = ContentTypeBuilder.CreateSimpleContentType(
"mixin2",
"Mixin2",
propertyTypeCollection: new PropertyTypeCollection(true, new List<PropertyType> { propertyType2 }));
// Act
var addedMetaMixin2 = mixin2.AddContentType(meta);
var addedMixin2 = mixin1.AddContentType(mixin2);
var addedMeta = parent.AddContentType(meta);
bool addedMetaMixin2 = mixin2.AddContentType(meta);
bool addedMixin2 = mixin1.AddContentType(mixin2);
bool addedMeta = parent.AddContentType(meta);
var addedMixin1 = parent.AddContentType(mixin1);
bool addedMixin1 = parent.AddContentType(mixin1);
var addedMixin1Textpage = textPage.AddContentType(mixin1);
var addedTextpageParent = parent.AddContentType(textPage);
bool addedMixin1Textpage = textPage.AddContentType(mixin1);
bool addedTextpageParent = parent.AddContentType(textPage);
var aliases = textPage.CompositionAliases();
var propertyTypes = textPage.CompositionPropertyTypes;
var propertyGroups = textPage.CompositionPropertyGroups;
IEnumerable<string> aliases = textPage.CompositionAliases();
IEnumerable<IPropertyType> propertyTypes = textPage.CompositionPropertyTypes;
IEnumerable<PropertyGroup> propertyGroups = textPage.CompositionPropertyGroups;
// Assert
Assert.That(mixin2.ContentTypeCompositionExists("meta"), Is.True);

View File

@@ -1,6 +1,10 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -17,10 +21,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Ignore("Ignoring this test until we actually enforce this, see comments in ContentTypeBase.PropertyTypesChanged")]
public void Cannot_Add_Duplicate_Property_Aliases()
{
var contentType = BuildContentType();
ContentType contentType = BuildContentType();
var propertyTypeBuilder = new PropertyTypeBuilder();
var additionalPropertyType = propertyTypeBuilder
PropertyType additionalPropertyType = propertyTypeBuilder
.WithAlias("title")
.Build();
@@ -32,16 +36,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Ignore("Ignoring this test until we actually enforce this, see comments in ContentTypeBase.PropertyTypesChanged")]
public void Cannot_Update_Duplicate_Property_Aliases()
{
var contentType = BuildContentType();
ContentType contentType = BuildContentType();
var propertyTypeBuilder = new PropertyTypeBuilder();
var additionalPropertyType = propertyTypeBuilder
PropertyType additionalPropertyType = propertyTypeBuilder
.WithAlias("title")
.Build();
contentType.PropertyTypeCollection.Add(additionalPropertyType);
var toUpdate = contentType.PropertyTypeCollection["myPropertyType2"];
IPropertyType toUpdate = contentType.PropertyTypeCollection["myPropertyType2"];
Assert.Throws<InvalidOperationException>(() => toUpdate.Alias = "myPropertyType");
}
@@ -49,7 +53,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Deep_Clone_Content_Type_Sort()
{
var contentType = BuildContentTypeSort();
ContentTypeSort contentType = BuildContentTypeSort();
var clone = (ContentTypeSort)contentType.DeepClone();
Assert.AreNotSame(clone, contentType);
Assert.AreEqual(clone, contentType);
@@ -71,7 +75,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Deep_Clone_Content_Type_With_Reset_Identities()
{
var contentType = BuildContentType();
ContentType contentType = BuildContentType();
var clone = (ContentType)contentType.DeepCloneWithResetIdentities("newAlias");
@@ -79,22 +83,26 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreNotEqual("newAlias", contentType.Alias);
Assert.IsFalse(clone.HasIdentity);
foreach (var propertyGroup in clone.PropertyGroups)
foreach (PropertyGroup propertyGroup in clone.PropertyGroups)
{
Assert.IsFalse(propertyGroup.HasIdentity);
foreach (var propertyType in propertyGroup.PropertyTypes)
foreach (IPropertyType propertyType in propertyGroup.PropertyTypes)
{
Assert.IsFalse(propertyType.HasIdentity);
}
}
foreach (var propertyType in clone.PropertyTypes.Where(x => x.HasIdentity))
foreach (IPropertyType propertyType in clone.PropertyTypes.Where(x => x.HasIdentity))
{
Assert.IsFalse(propertyType.HasIdentity);
}
}
}
[Test]
public void Can_Deep_Clone_Content_Type()
{
// Arrange
var contentType = BuildContentType();
ContentType contentType = BuildContentType();
// Act
var clone = (ContentType)contentType.DeepClone();
@@ -109,6 +117,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreNotSame(clone.AllowedTemplates.ElementAt(index), contentType.AllowedTemplates.ElementAt(index));
Assert.AreEqual(clone.AllowedTemplates.ElementAt(index), contentType.AllowedTemplates.ElementAt(index));
}
Assert.AreNotSame(clone.PropertyGroups, contentType.PropertyGroups);
Assert.AreEqual(clone.PropertyGroups.Count, contentType.PropertyGroups.Count);
for (var index = 0; index < contentType.PropertyGroups.Count; index++)
@@ -116,6 +125,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreNotSame(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
Assert.AreEqual(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
}
Assert.AreNotSame(clone.PropertyTypes, contentType.PropertyTypes);
Assert.AreEqual(clone.PropertyTypes.Count(), contentType.PropertyTypes.Count());
Assert.AreEqual(0, clone.NoGroupPropertyTypes.Count());
@@ -140,19 +150,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.Icon, contentType.Icon);
Assert.AreEqual(clone.IsContainer, contentType.IsContainer);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(contentType, null));
}
//need to ensure the event handlers are wired
// Need to ensure the event handlers are wired
var asDirty = (ICanBeDirty)clone;
Assert.IsFalse(asDirty.IsPropertyDirty("PropertyTypes"));
var propertyTypeBuilder = new PropertyTypeBuilder();
var additionalPropertyType = propertyTypeBuilder
PropertyType additionalPropertyType = propertyTypeBuilder
.WithAlias("blah")
.Build();
@@ -167,7 +178,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Serialize_Content_Type_Without_Error()
{
// Arrange
var contentType = BuildContentType();
ContentType contentType = BuildContentType();
var json = JsonConvert.SerializeObject(contentType);
Debug.Print(json);
@@ -183,7 +194,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Deep_Clone_Media_Type()
{
// Arrange
var contentType = BuildMediaType();
MediaType contentType = BuildMediaType();
// Act
var clone = (MediaType)contentType.DeepClone();
@@ -198,12 +209,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreNotSame(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
Assert.AreEqual(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
}
Assert.AreEqual(clone.PropertyTypes.Count(), contentType.PropertyTypes.Count());
for (var index = 0; index < contentType.PropertyTypes.Count(); index++)
{
Assert.AreNotSame(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
Assert.AreEqual(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
}
Assert.AreEqual(clone.CreateDate, contentType.CreateDate);
Assert.AreEqual(clone.CreatorId, contentType.CreatorId);
Assert.AreEqual(clone.Key, contentType.Key);
@@ -216,17 +229,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.Icon, contentType.Icon);
Assert.AreEqual(clone.IsContainer, contentType.IsContainer);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(contentType, null));
}
}
[Test]
public void Can_Serialize_Media_Type_Without_Error()
{
// Arrange
var contentType = BuildMediaType();
MediaType contentType = BuildMediaType();
var json = JsonConvert.SerializeObject(contentType);
Debug.Print(json);
@@ -242,7 +257,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Deep_Clone_Member_Type()
{
// Arrange
var contentType = BuildMemberType();
MemberType contentType = BuildMemberType();
// Act
var clone = (MemberType)contentType.DeepClone();
@@ -257,12 +272,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreNotSame(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
Assert.AreEqual(clone.PropertyGroups[index], contentType.PropertyGroups[index]);
}
Assert.AreEqual(clone.PropertyTypes.Count(), contentType.PropertyTypes.Count());
for (var index = 0; index < contentType.PropertyTypes.Count(); index++)
{
Assert.AreNotSame(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
Assert.AreEqual(clone.PropertyTypes.ElementAt(index), contentType.PropertyTypes.ElementAt(index));
}
Assert.AreEqual(clone.CreateDate, contentType.CreateDate);
Assert.AreEqual(clone.CreatorId, contentType.CreatorId);
Assert.AreEqual(clone.Key, contentType.Key);
@@ -276,16 +293,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.IsContainer, contentType.IsContainer);
// This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(contentType, null));
}
}
[Test]
public void Can_Serialize_Member_Type_Without_Error()
{
// Arrange
var contentType = BuildMemberType();
MemberType contentType = BuildMemberType();
var json = JsonConvert.SerializeObject(contentType);
Debug.Print(json);

View File

@@ -1,4 +1,7 @@
using Moq;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using Moq;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -14,26 +17,25 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Mock.Of<IContent>(x => x.Published == true),
new[] { "en-US", "fr-FR" },
"en-US");
Assert.AreEqual("en-US", result); //default culture is being saved so use it
Assert.AreEqual("en-US", result); // default culture is being saved so use it
result = CultureImpact.GetCultureForInvariantErrors(
Mock.Of<IContent>(x => x.Published == false),
new[] { "fr-FR" },
"en-US");
Assert.AreEqual("fr-FR", result); //default culture not being saved with not published version, use the first culture being saved
Assert.AreEqual("fr-FR", result); // default culture not being saved with not published version, use the first culture being saved
result = CultureImpact.GetCultureForInvariantErrors(
Mock.Of<IContent>(x => x.Published == true),
new[] { "fr-FR" },
"en-US");
Assert.AreEqual(null, result); //default culture not being saved with published version, use null
Assert.AreEqual(null, result); // default culture not being saved with published version, use null
}
[Test]
public void All_Cultures()
{
var impact = CultureImpact.All;
CultureImpact impact = CultureImpact.All;
Assert.AreEqual(impact.Culture, "*");
@@ -48,7 +50,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Invariant_Culture()
{
var impact = CultureImpact.Invariant;
CultureImpact impact = CultureImpact.Invariant;
Assert.AreEqual(impact.Culture, null);
@@ -93,7 +95,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void TryCreate_Explicit_Default_Culture()
{
var success = CultureImpact.TryCreate("en-US", true, ContentVariation.Culture, false, out var impact);
var success = CultureImpact.TryCreate("en-US", true, ContentVariation.Culture, false, out CultureImpact impact);
Assert.IsTrue(success);
Assert.AreEqual(impact.Culture, "en-US");
@@ -109,7 +111,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void TryCreate_Explicit_NonDefault_Culture()
{
var success = CultureImpact.TryCreate("en-US", false, ContentVariation.Culture, false, out var impact);
var success = CultureImpact.TryCreate("en-US", false, ContentVariation.Culture, false, out CultureImpact impact);
Assert.IsTrue(success);
Assert.AreEqual(impact.Culture, "en-US");
@@ -125,7 +127,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void TryCreate_AllCultures_For_Invariant()
{
var success = CultureImpact.TryCreate("*", false, ContentVariation.Nothing, false, out var impact);
var success = CultureImpact.TryCreate("*", false, ContentVariation.Nothing, false, out CultureImpact impact);
Assert.IsTrue(success);
Assert.AreEqual(impact.Culture, null);
@@ -136,7 +138,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void TryCreate_AllCultures_For_Variant()
{
var success = CultureImpact.TryCreate("*", false, ContentVariation.Culture, false, out var impact);
var success = CultureImpact.TryCreate("*", false, ContentVariation.Culture, false, out CultureImpact impact);
Assert.IsTrue(success);
Assert.AreEqual(impact.Culture, "*");
@@ -147,14 +149,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void TryCreate_Invariant_For_Variant()
{
var success = CultureImpact.TryCreate(null, false, ContentVariation.Culture, false, out var impact);
var success = CultureImpact.TryCreate(null, false, ContentVariation.Culture, false, out CultureImpact impact);
Assert.IsFalse(success);
}
[Test]
public void TryCreate_Invariant_For_Invariant()
{
var success = CultureImpact.TryCreate(null, false, ContentVariation.Nothing, false, out var impact);
var success = CultureImpact.TryCreate(null, false, ContentVariation.Nothing, false, out CultureImpact impact);
Assert.IsTrue(success);
Assert.AreSame(CultureImpact.Invariant, impact);

View File

@@ -1,4 +1,6 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
@@ -149,74 +151,76 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
MyTest1 = new object[]
{
new Test1(), "hello",
//not cloneable so this property will get skipped
// Not cloneable so this property will get skipped.
new Test2()
}
};
var clone = (Test3)test1.DeepClone();
//it skipped this property so these will now be the same
// It skipped this property so these will now be the same.
Assert.AreSame(clone.MyTest1, test1.MyTest1);
}
public class Test1 : BaseCloneable
{
public string Name { get; set; }
public int Age { get; set; }
public Test1 MyTest1 { get; set; }
public Test2 MyTest2 { get; set; }
public Test2 MyTest2 { get; set; }
}
public class Test2
{
public string Name { get; set; }
public Test1 MyTest1 { get; set; }
}
public class Test3 : BaseCloneable
{
public string Name { get; set; }
public object[] MyTest1 { get; set; }
public object[] MyTest1 { get; set; }
}
public class Test4 : BaseCloneable
{
public string Name { get; set; }
public Test1[] MyTest1 { get; set; }
public Test1[] MyTest1 { get; set; }
}
public class Test5 : BaseCloneable
{
public string Name { get; set; }
public IEnumerable MyTest1 { get; set; }
public IEnumerable MyTest1 { get; set; }
}
public class Test6 : BaseCloneable
{
public string Name { get; set; }
public IEnumerable<Test1> MyTest1 { get; set; }
public IEnumerable<Test1> MyTest1 { get; set; }
}
public class Test7 : BaseCloneable
{
public string Name { get; set; }
public List<Test1> MyTest1 { get; set; }
public List<Test1> MyTest1 { get; set; }
}
public class Test8 : BaseCloneable
{
public string Name { get; set; }
public ICollection<Test1> MyTest1 { get; set; }
public ICollection<Test1> MyTest1 { get; set; }
}
public abstract class BaseCloneable : IDeepCloneable

View File

@@ -1,4 +1,8 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -12,15 +16,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private DictionaryItemBuilder _builder = new DictionaryItemBuilder();
[SetUp]
public void SetUp()
{
_builder = new DictionaryItemBuilder();
}
public void SetUp() => _builder = new DictionaryItemBuilder();
[Test]
public void Can_Deep_Clone()
{
var item = _builder
DictionaryItem item = _builder
.WithRandomTranslations(2)
.Build();
@@ -41,19 +42,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.Translations.ElementAt(i), item.Translations.ElementAt(i));
}
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(item, null));
}
}
[Test]
public void Can_Serialize_Without_Error()
{
var item = _builder
DictionaryItem item = _builder
.WithRandomTranslations(2)
.Build();

View File

@@ -1,5 +1,9 @@
using System.Diagnostics;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -14,15 +18,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private DictionaryTranslationBuilder _builder = new DictionaryTranslationBuilder();
[SetUp]
public void SetUp()
{
_builder = new DictionaryTranslationBuilder();
}
public void SetUp() => _builder = new DictionaryTranslationBuilder();
[Test]
public void Can_Deep_Clone()
{
var item = BuildDictionaryTranslation();
IDictionaryTranslation item = BuildDictionaryTranslation();
var clone = (DictionaryTranslation)item.DeepClone();
@@ -33,35 +34,36 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.Key, item.Key);
Assert.AreEqual(clone.UpdateDate, item.UpdateDate);
Assert.AreNotSame(clone.Language, item.Language);
//This is null because we are ignoring it from cloning due to caching/cloning issues - we don't really want
// This is null because we are ignoring it from cloning due to caching/cloning issues - we don't really want
// this entity attached to this item but we're stuck with it for now
Assert.IsNull(clone.Language);
Assert.AreEqual(clone.LanguageId, item.LanguageId);
Assert.AreEqual(clone.Value, item.Value);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps.Where(x => x.Name != "Language"))
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps.Where(x => x.Name != "Language"))
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(item, null));
}
}
[Test]
public void Can_Serialize_Without_Error()
{
var item = BuildDictionaryTranslation();
IDictionaryTranslation item = BuildDictionaryTranslation();
var json = JsonConvert.SerializeObject(item);
Debug.Print(json);
}
private IDictionaryTranslation BuildDictionaryTranslation()
{
return _builder
private IDictionaryTranslation BuildDictionaryTranslation() =>
_builder
.AddLanguage()
.WithCultureInfo("en-AU")
.Done()
.WithValue("colour")
.Build();
}
.Build();
}
}

View File

@@ -1,6 +1,10 @@
using System.Diagnostics;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Diagnostics;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models.Entities;
using Umbraco.Tests.Common.Builders;
using Umbraco.Tests.Common.Builders.Extensions;
@@ -12,15 +16,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private DocumentEntitySlimBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new DocumentEntitySlimBuilder();
}
public void SetUp() => _builder = new DocumentEntitySlimBuilder();
[Test]
public void Can_Serialize_Without_Error()
{
var item = _builder
DocumentEntitySlim item = _builder
.WithId(3)
.WithCreatorId(4)
.WithName("Test")

View File

@@ -1,4 +1,8 @@
using Newtonsoft.Json;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Tests.Common.Builders;
@@ -12,19 +16,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private LanguageBuilder _builder = new LanguageBuilder();
[SetUp]
public void SetUp()
{
_builder = new LanguageBuilder();
}
public void SetUp() => _builder = new LanguageBuilder();
[Test]
public void Can_Deep_Clone()
{
var item = _builder
ILanguage item = _builder
.WithId(1)
.Build();
var clone = (Language) item.DeepClone();
var clone = (Language)item.DeepClone();
Assert.AreNotSame(clone, item);
Assert.AreEqual(clone, item);
Assert.AreEqual(clone.CreateDate, item.CreateDate);
@@ -34,9 +35,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.Key, item.Key);
Assert.AreEqual(clone.UpdateDate, item.UpdateDate);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(item, null));
}
@@ -45,7 +46,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Serialize_Without_Error()
{
var item = _builder.Build();
ILanguage item = _builder.Build();
Assert.DoesNotThrow(() => JsonConvert.SerializeObject(item));
}

View File

@@ -1,5 +1,9 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Entities;
@@ -14,15 +18,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private MacroBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new MacroBuilder();
}
public void SetUp() => _builder = new MacroBuilder();
[Test]
public void Can_Deep_Clone()
{
var macro = _builder
Macro macro = _builder
.WithId(1)
.WithUseInEditor(true)
.WithCacheDuration(3)
@@ -58,13 +59,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreNotSame(clone.AddedProperties, macro.AddedProperties);
Assert.AreNotSame(clone.RemovedProperties, macro.RemovedProperties);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(macro, null));
}
//need to ensure the event handlers are wired
// Need to ensure the event handlers are wired.
var asDirty = (ICanBeDirty)clone;
Assert.IsFalse(asDirty.IsPropertyDirty("Properties"));

View File

@@ -1,5 +1,9 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Diagnostics;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -14,16 +18,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private MemberGroupBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new MemberGroupBuilder();
}
public void SetUp() => _builder = new MemberGroupBuilder();
[Test]
public void Can_Deep_Clone()
{
// Arrange
var group = BuildMemberGroup();
MemberGroup group = BuildMemberGroup();
// Act
var clone = (MemberGroup)group.DeepClone();
@@ -40,24 +41,25 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.UpdateDate, group.UpdateDate);
Assert.AreEqual(clone.Name, group.Name);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(group, null));
}
}
[Test]
public void Can_Serialize_Without_Error()
{
var group = BuildMemberGroup();
MemberGroup group = BuildMemberGroup();
var json = JsonConvert.SerializeObject(group);
Debug.Print(json);
}
private MemberGroup BuildMemberGroup()
{
return _builder
private MemberGroup BuildMemberGroup() =>
_builder
.WithId(6)
.WithKey(Guid.NewGuid())
.WithName("Test Group")
@@ -69,6 +71,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
.WithKeyValue("test2", "hello")
.Done()
.Build();
}
}
}

View File

@@ -1,5 +1,9 @@
using System.Diagnostics;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -14,16 +18,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private MemberBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new MemberBuilder();
}
public void SetUp() => _builder = new MemberBuilder();
[Test]
public void Can_Deep_Clone()
{
// Arrange
var member = BuildMember();
Member member = BuildMember();
// Act
var clone = (Member)member.DeepClone();
@@ -66,24 +67,25 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
// this can be the same, it is immutable
Assert.AreSame(clone.ContentType, member.ContentType);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(member, null));
}
}
[Test]
public void Can_Serialize_Without_Error()
{
var member = BuildMember();
Member member = BuildMember();
var json = JsonConvert.SerializeObject(member);
Debug.Print(json);
}
private Member BuildMember()
{
return _builder
private Member BuildMember() =>
_builder
.AddMemberType()
.WithId(99)
.WithAlias("memberType")
@@ -117,7 +119,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
.WithEmail("email@email.com")
.WithFailedPasswordAttempts(22)
.WithIsApproved(true)
.WithIsLockedOut(true)
.WithIsLockedOut(true)
.WithTrashed(false)
.AddMemberGroups()
.WithValue("Group 1")
@@ -134,6 +136,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
.WithKeyValue("author", "John Doe")
.Done()
.Build();
}
}
}

View File

@@ -1,5 +1,8 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Diagnostics;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -14,15 +17,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private PropertyGroupBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new PropertyGroupBuilder();
}
public void SetUp() => _builder = new PropertyGroupBuilder();
[Test]
public void Can_Deep_Clone()
{
var pg = BuildPropertyGroup();
PropertyGroup pg = BuildPropertyGroup();
var clone = (PropertyGroup)pg.DeepClone();
@@ -43,9 +43,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.PropertyTypes[i], pg.PropertyTypes[i]);
}
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(pg, null));
}
@@ -54,15 +54,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Serialize_Without_Error()
{
var pg = BuildPropertyGroup();
PropertyGroup pg = BuildPropertyGroup();
var json = JsonConvert.SerializeObject(pg);
Debug.Print(json);
}
private PropertyGroup BuildPropertyGroup()
{
return _builder
private PropertyGroup BuildPropertyGroup() =>
_builder
.WithId(77)
.WithName("Group1")
.AddPropertyType()
@@ -71,15 +70,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
.WithName("Test")
.WithDescription("testing")
.WithPropertyGroupId(11)
.WithMandatory(true)
.WithMandatory(true)
.WithValidationRegExp("xxxx")
.Done()
.AddPropertyType()
.WithId(4)
.WithAlias("test2")
.WithName("Test2")
.WithName("Test2")
.Done()
.Build();
}
}
}

View File

@@ -1,27 +1,27 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Tests.Common.Builders;
using Umbraco.Tests.Common.Builders.Extensions;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
{
{
[TestFixture]
public class PropertyTests
{
private PropertyBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new PropertyBuilder();
}
public void SetUp() => _builder = new PropertyBuilder();
[Test]
public void Can_Deep_Clone()
{
var property = BuildProperty();
IProperty property = BuildProperty();
property.SetValue("hello");
property.PublishValues();
@@ -37,16 +37,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
}
// This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(property, null));
}
}
private IProperty BuildProperty()
{
return _builder
private IProperty BuildProperty() =>
_builder
.WithId(4)
.AddPropertyType()
.WithId(3)
@@ -61,6 +60,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
.WithValidationRegExp("xxxx")
.Done()
.Build();
}
}
}

View File

@@ -1,8 +1,11 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Diagnostics;
using Newtonsoft.Json;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Tests.Common.Builders;
@@ -16,15 +19,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private PropertyTypeBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new PropertyTypeBuilder();
}
public void SetUp() => _builder = new PropertyTypeBuilder();
[Test]
public void Can_Deep_Clone()
{
var pt = BuildPropertyType();
PropertyType pt = BuildPropertyType();
var clone = (PropertyType)pt.DeepClone();
@@ -45,9 +45,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.ValidationRegExp, pt.ValidationRegExp);
Assert.AreEqual(clone.ValueStorageType, pt.ValueStorageType);
//This double verifies by reflection (don't test properties marked with [DoNotClone]
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps.Where(p => p.GetCustomAttribute<DoNotCloneAttribute>(false) == null))
// This double verifies by reflection (don't test properties marked with [DoNotClone]
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps.Where(p => p.GetCustomAttribute<DoNotCloneAttribute>(false) == null))
{
var expected = propertyInfo.GetValue(pt, null);
var actual = propertyInfo.GetValue(clone, null);
@@ -64,15 +64,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Serialize_Without_Error()
{
var pt = BuildPropertyType();
PropertyType pt = BuildPropertyType();
var json = JsonConvert.SerializeObject(pt);
Debug.Print(json);
}
private PropertyType BuildPropertyType()
{
return _builder
private PropertyType BuildPropertyType() =>
_builder
.WithId(3)
.WithPropertyEditorAlias("TestPropertyEditor")
.WithAlias("test")
@@ -84,6 +83,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
.WithMandatory(true)
.WithValidationRegExp("xxxx")
.Build();
}
}
}

View File

@@ -1,5 +1,9 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Diagnostics;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -14,17 +18,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private RelationBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new RelationBuilder();
}
public void SetUp() => _builder = new RelationBuilder();
[Test]
public void Can_Deep_Clone()
{
var relation = BuildRelation();
Relation relation = BuildRelation();
var clone = (Relation) relation.DeepClone();
var clone = (Relation)relation.DeepClone();
Assert.AreNotSame(clone, relation);
Assert.AreEqual(clone, relation);
@@ -39,9 +40,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.RelationTypeId, relation.RelationTypeId);
Assert.AreEqual(clone.UpdateDate, relation.UpdateDate);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(relation, null));
}
@@ -50,15 +51,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Serialize_Without_Error()
{
var relation = BuildRelation();
Relation relation = BuildRelation();
var json = JsonConvert.SerializeObject(relation);
Debug.Print(json);
}
private Relation BuildRelation()
{
return _builder
private Relation BuildRelation() =>
_builder
.BetweenIds(9, 8)
.WithId(4)
.WithComment("test comment")
@@ -74,6 +74,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
.WithChildObjectType(Guid.NewGuid())
.Done()
.Build();
}
}
}

View File

@@ -1,4 +1,8 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models;
@@ -13,21 +17,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private RelationTypeBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new RelationTypeBuilder();
}
public void SetUp() => _builder = new RelationTypeBuilder();
[Test]
public void Can_Deep_Clone()
{
var item = _builder
IRelationType item = _builder
.WithId(1)
.WithParentObjectType(Guid.NewGuid())
.WithChildObjectType(Guid.NewGuid())
.Build();
var clone = (RelationType) item.DeepClone();
var clone = (RelationType)item.DeepClone();
Assert.AreNotSame(clone, item);
Assert.AreEqual(clone, item);
@@ -41,9 +42,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.CreateDate, item.CreateDate);
Assert.AreEqual(clone.UpdateDate, item.UpdateDate);
//This double verifies by reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// This double verifies by reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(item, null));
}
@@ -52,7 +53,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Serialize_Without_Error()
{
var item = _builder.Build();
IRelationType item = _builder.Build();
Assert.DoesNotThrow(() => JsonConvert.SerializeObject(item));
}

View File

@@ -1,4 +1,8 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Newtonsoft.Json;
@@ -14,17 +18,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private StylesheetBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new StylesheetBuilder();
}
public void SetUp() => _builder = new StylesheetBuilder();
[Test]
public void Can_Create_Stylesheet()
{
// Arrange
// Act
var stylesheet = _builder
Stylesheet stylesheet = _builder
.WithPath("/css/styles.css")
.WithContent(@"body { color:#000; } .bold {font-weight:bold;}")
.Build();
@@ -38,7 +39,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Add_Property()
{
// Arrange
var stylesheet = _builder
Stylesheet stylesheet = _builder
.WithPath("/css/styles.css")
.WithContent(@"body { color:#000; } .bold {font-weight:bold;}")
.Build();
@@ -50,14 +51,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(1, stylesheet.Properties.Count());
Assert.AreEqual("Test", stylesheet.Properties.Single().Name);
Assert.AreEqual("p", stylesheet.Properties.Single().Alias);
Assert.AreEqual("font-weight:bold;"+Environment.NewLine+"font-family:Arial;", stylesheet.Properties.Single().Value);
Assert.AreEqual("font-weight:bold;" + Environment.NewLine + "font-family:Arial;", stylesheet.Properties.Single().Value);
}
[Test]
public void Can_Remove_Property()
{
// Arrange
var stylesheet = _builder
Stylesheet stylesheet = _builder
.WithPath("/css/styles.css")
.WithContent(@"body { color:#000; } /**umb_name:Hello*/p{font-size:2em;} .bold {font-weight:bold;}")
.Build();
@@ -75,13 +76,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Can_Update_Property()
{
// Arrange
var stylesheet = _builder
Stylesheet stylesheet = _builder
.WithPath("/css/styles.css")
.WithContent(@"body { color:#000; } /**umb_name:Hello*/p{font-size:2em;} .bold {font-weight:bold;}")
.Build();
// Act
var prop = stylesheet.Properties.Single();
IStylesheetProperty prop = stylesheet.Properties.Single();
prop.Alias = "li";
prop.Value = "font-size:5em;";
@@ -91,20 +92,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
// Assert
Assert.AreEqual("li", prop.Alias);
Assert.AreEqual("font-size:5em;", prop.Value);
Assert.AreEqual("body { color:#000; } /**umb_name:Hello*/" +Environment.NewLine+ "li {" +Environment.NewLine+ "\tfont-size:5em;" +Environment.NewLine+ "} .bold {font-weight:bold;}", stylesheet.Content);
Assert.AreEqual("body { color:#000; } /**umb_name:Hello*/" + Environment.NewLine + "li {" + Environment.NewLine + "\tfont-size:5em;" + Environment.NewLine + "} .bold {font-weight:bold;}", stylesheet.Content);
}
[Test]
public void Can_Get_Properties_From_Css()
{
// Arrange
var stylesheet = _builder
Stylesheet stylesheet = _builder
.WithPath("/css/styles.css")
.WithContent(@"body { color:#000; } .bold {font-weight:bold;} /**umb_name:Hello */ p { font-size: 1em; } /**umb_name:testing123*/ li:first-child {padding:0px;}")
.Build();
// Act
var properties = stylesheet.Properties;
IEnumerable<IStylesheetProperty> properties = stylesheet.Properties;
// Assert
Assert.AreEqual(2, properties.Count());
@@ -116,12 +117,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual("li:first-child", properties.Last().Alias);
}
[Test]
public void Can_Serialize_Without_Error()
{
// Arrange
var stylesheet = _builder
Stylesheet stylesheet = _builder
.WithPath("/css/styles.css")
.WithContent(@"@media screen and (min-width: 600px) and (min-width: 900px) {
.class {

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
@@ -16,15 +19,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private TemplateBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new TemplateBuilder();
}
public void SetUp() => _builder = new TemplateBuilder();
[Test]
public void Can_Deep_Clone()
{
var template = BuildTemplate();
ITemplate template = BuildTemplate();
var clone = (Template)template.DeepClone();
@@ -42,15 +42,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.UpdateDate, template.UpdateDate);
// clone.Content should be null but getting it would lazy-load
var type = clone.GetType();
var contentField = type.BaseType.GetField("_content", BindingFlags.Instance | BindingFlags.NonPublic);
Type type = clone.GetType();
FieldInfo contentField = type.BaseType.GetField("_content", BindingFlags.Instance | BindingFlags.NonPublic);
var value = contentField.GetValue(clone);
Assert.IsNull(value);
// this double verifies by reflection
// need to exclude content else it would lazy-load
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps.Where(x => x.Name != "Content"))
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps.Where(x => x.Name != "Content"))
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(template, null));
}
@@ -59,15 +59,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void Can_Serialize_Without_Error()
{
var template = BuildTemplate();
ITemplate template = BuildTemplate();
var json = JsonConvert.SerializeObject(template);
Debug.Print(json);
}
private ITemplate BuildTemplate()
{
return _builder
private ITemplate BuildTemplate() =>
_builder
.WithId(3)
.WithAlias("test")
.WithName("Test")
@@ -77,6 +76,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
.WithContent("blah")
.AsMasterTemplate("master", 88)
.Build();
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
@@ -7,6 +10,7 @@ using Umbraco.Core.Models;
using Umbraco.Core.Models.Entities;
using Umbraco.Core.Services;
using Umbraco.Tests.Common.Builders;
using User = Umbraco.Core.Models.Membership.User;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
{
@@ -16,10 +20,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private UserBuilder _userBuilder;
[SetUp]
public void SetUp()
{
_userBuilder = new UserBuilder();
}
public void SetUp() => _userBuilder = new UserBuilder();
[TestCase(-1, "-1", "-1,1,2,3,4,5", true)] // below root start node
[TestCase(2, "-1,1,2", "-1,1,2,3,4,5", true)] // below start node
@@ -32,11 +33,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
public void Determines_Path_Based_Access_To_Content(int startNodeId, string startNodePath, string contentPath, bool outcome)
{
var user = _userBuilder
User user = _userBuilder
.WithStartContentIds(new[] { startNodeId })
.Build();
var content = Mock.Of<IContent>(c => c.Path == contentPath && c.Id == 5);
IContent content = Mock.Of<IContent>(c => c.Path == contentPath && c.Id == 5);
var esmock = new Mock<IEntityService>();
esmock
@@ -80,7 +81,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
// 6
// 7
// 8
var paths = new Dictionary<int, string>
{
{ 1, "-1,1" },
@@ -106,10 +106,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
var expectedA = expected.Split(comma, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).OrderBy(x => x).ToArray();
var ok = combinedA.Length == expectedA.Length;
if (ok) ok = expectedA.Where((t, i) => t != combinedA[i]).Any() == false;
if (ok)
{
ok = expectedA.Where((t, i) => t != combinedA[i]).Any() == false;
}
if (ok == false)
{
Assert.Fail("Expected \"" + string.Join(",", expectedA) + "\" but got \"" + string.Join(",", combinedA) + "\".");
}
}
}
}

View File

@@ -1,5 +1,9 @@
using System.Diagnostics;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core.Models.Membership;
@@ -14,15 +18,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
private UserBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new UserBuilder();
}
public void SetUp() => _builder = new UserBuilder();
[Test]
public void Can_Deep_Clone()
{
var item = BuildUser();
User item = BuildUser();
var clone = (User)item.DeepClone();
@@ -31,24 +32,25 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.AreEqual(clone.AllowedSections.Count(), item.AllowedSections.Count());
//Verify normal properties with reflection
var allProps = clone.GetType().GetProperties();
foreach (var propertyInfo in allProps)
// Verify normal properties with reflection
PropertyInfo[] allProps = clone.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in allProps)
{
Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(item, null));
}
}
[Test]
public void Can_Serialize_Without_Error()
{
var item = BuildUser();
User item = BuildUser();
var json = JsonConvert.SerializeObject(item);
Debug.Print(json);
}
private User BuildUser()
{
return _builder
private User BuildUser() =>
_builder
.WithId(3)
.WithLogin("username", "test pass")
.WithName("Test")
@@ -61,6 +63,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
.WithStartContentIds(new[] { 3 })
.WithStartMediaIds(new[] { 8 })
.Build();
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using NUnit.Framework;
@@ -22,110 +25,112 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void ValidateVariationTests()
{
// All tests:
// 1. if exact is set to true: culture cannot be null when the ContentVariation.Culture flag is set
// 2. if wildcards is set to false: fail when "*" is passed in as either culture or segment.
// 3. ContentVariation flag is ignored when wildcards are used.
// 4. Empty string is considered the same as null
AssertForNovariation();
AssertForCultureVariation();
AssertForSegmentVariation();
AssertForCultureAndSegmentVariation();
}
#region Nothing
private static void AssertForNovariation()
{
Assert4A(ContentVariation.Nothing, null, null, true);
Assert4A(ContentVariation.Nothing, null, "", true);
Assert4A(ContentVariation.Nothing, null, string.Empty, true);
Assert4B(ContentVariation.Nothing, null, "*", true, false, false, true);
Assert4A(ContentVariation.Nothing, null, "segment", false);
Assert4A(ContentVariation.Nothing, "", null, true);
Assert4A(ContentVariation.Nothing, "", "", true);
Assert4B(ContentVariation.Nothing, "", "*", true, false, false, true);
Assert4A(ContentVariation.Nothing, "", "segment", false);
Assert4A(ContentVariation.Nothing, string.Empty, null, true);
Assert4A(ContentVariation.Nothing, string.Empty, string.Empty, true);
Assert4B(ContentVariation.Nothing, string.Empty, "*", true, false, false, true);
Assert4A(ContentVariation.Nothing, string.Empty, "segment", false);
Assert4B(ContentVariation.Nothing, "*", null, true, false, false, true);
Assert4B(ContentVariation.Nothing, "*", "", true, false, false, true);
Assert4B(ContentVariation.Nothing, "*", string.Empty, true, false, false, true);
Assert4B(ContentVariation.Nothing, "*", "*", true, false, false, true);
Assert4A(ContentVariation.Nothing, "*", "segment", false);
Assert4A(ContentVariation.Nothing, "culture", null, false);
Assert4A(ContentVariation.Nothing, "culture", "", false);
Assert4A(ContentVariation.Nothing, "culture", string.Empty, false);
Assert4A(ContentVariation.Nothing, "culture", "*", false);
Assert4A(ContentVariation.Nothing, "culture", "segment", false);
}
#endregion
#region Culture
private static void AssertForCultureVariation()
{
Assert4B(ContentVariation.Culture, null, null, false, true, false, true);
Assert4B(ContentVariation.Culture, null, "", false, true, false, true);
Assert4B(ContentVariation.Culture, null, string.Empty, false, true, false, true);
Assert4B(ContentVariation.Culture, null, "*", false, false, false, true);
Assert4A(ContentVariation.Culture, null, "segment", false);
Assert4B(ContentVariation.Culture, "", null, false, true, false, true);
Assert4B(ContentVariation.Culture, "", "", false, true, false, true);
Assert4B(ContentVariation.Culture, "", "*", false, false, false, true);
Assert4A(ContentVariation.Culture, "", "segment", false);
Assert4B(ContentVariation.Culture, string.Empty, null, false, true, false, true);
Assert4B(ContentVariation.Culture, string.Empty, string.Empty, false, true, false, true);
Assert4B(ContentVariation.Culture, string.Empty, "*", false, false, false, true);
Assert4A(ContentVariation.Culture, string.Empty, "segment", false);
Assert4B(ContentVariation.Culture, "*", null, true, false, false, true);
Assert4B(ContentVariation.Culture, "*", "", true, false, false, true);
Assert4B(ContentVariation.Culture, "*", string.Empty, true, false, false, true);
Assert4B(ContentVariation.Culture, "*", "*", true, false, false, true);
Assert4A(ContentVariation.Culture, "*", "segment", false);
Assert4A(ContentVariation.Culture, "culture", null, true);
Assert4A(ContentVariation.Culture, "culture", "", true);
Assert4A(ContentVariation.Culture, "culture", string.Empty, true);
Assert4B(ContentVariation.Culture, "culture", "*", true, false, false, true);
Assert4A(ContentVariation.Culture, "culture", "segment", false);
}
#endregion
#region Segment
private static void AssertForSegmentVariation()
{
Assert4B(ContentVariation.Segment, null, null, true, true, true, true);
Assert4B(ContentVariation.Segment, null, "", true, true, true, true);
Assert4B(ContentVariation.Segment, null, string.Empty, true, true, true, true);
Assert4B(ContentVariation.Segment, null, "*", true, false, false, true);
Assert4A(ContentVariation.Segment, null, "segment", true);
Assert4B(ContentVariation.Segment, "", null, true, true, true, true);
Assert4B(ContentVariation.Segment, "", "", true, true, true, true);
Assert4B(ContentVariation.Segment, "", "*", true, false, false, true);
Assert4A(ContentVariation.Segment, "", "segment", true);
Assert4B(ContentVariation.Segment, string.Empty, null, true, true, true, true);
Assert4B(ContentVariation.Segment, string.Empty, string.Empty, true, true, true, true);
Assert4B(ContentVariation.Segment, string.Empty, "*", true, false, false, true);
Assert4A(ContentVariation.Segment, string.Empty, "segment", true);
Assert4B(ContentVariation.Segment, "*", null, true, false, false, true);
Assert4B(ContentVariation.Segment, "*", "", true, false, false, true);
Assert4B(ContentVariation.Segment, "*", string.Empty, true, false, false, true);
Assert4B(ContentVariation.Segment, "*", "*", true, false, false, true);
Assert4B(ContentVariation.Segment, "*", "segment", true, false, false, true);
Assert4A(ContentVariation.Segment, "culture", null, false);
Assert4A(ContentVariation.Segment, "culture", "", false);
Assert4A(ContentVariation.Segment, "culture", string.Empty, false);
Assert4A(ContentVariation.Segment, "culture", "*", false);
Assert4A(ContentVariation.Segment, "culture", "segment", false);
}
#endregion
#region CultureAndSegment
private static void AssertForCultureAndSegmentVariation()
{
Assert4B(ContentVariation.CultureAndSegment, null, null, false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, null, "", false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, null, string.Empty, false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, null, "*", false, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, null, "segment", false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, "", null, false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, "", "", false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, "", "*", false, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "", "segment", false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, string.Empty, null, false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, string.Empty, string.Empty, false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, string.Empty, "*", false, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, string.Empty, "segment", false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, "*", null, true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "*", "", true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "*", string.Empty, true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "*", "*", true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "*", "segment", true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "culture", null, true, true, true, true);
Assert4B(ContentVariation.CultureAndSegment, "culture", "", true, true, true, true);
Assert4B(ContentVariation.CultureAndSegment, "culture", string.Empty, true, true, true, true);
Assert4B(ContentVariation.CultureAndSegment, "culture", "*", true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "culture", "segment", true, true, true, true);
#endregion
}
/// <summary>
/// Asserts the result of <see cref="ContentVariationExtensions.ValidateVariation(ContentVariation, string, string, bool, bool, bool)"/>
/// </summary>
/// <param name="variation"></param>
/// <param name="culture"></param>
/// <param name="segment"></param>
/// <param name="exactAndWildcards">Validate using Exact + Wildcards flags</param>
/// <param name="nonExactAndNoWildcards">Validate using non Exact + no Wildcard flags</param>
/// <param name="exactAndNoWildcards">Validate using Exact + no Wildcard flags</param>
/// <param name="nonExactAndWildcards">Validate using non Exact + Wildcard flags</param>
private static void Assert4B(ContentVariation variation, string culture, string segment,
bool exactAndWildcards, bool nonExactAndNoWildcards, bool exactAndNoWildcards, bool nonExactAndWildcards)
private static void Assert4B(
ContentVariation variation,
string culture,
string segment,
bool exactAndWildcards,
bool nonExactAndNoWildcards,
bool exactAndNoWildcards,
bool nonExactAndWildcards)
{
Assert.AreEqual(exactAndWildcards, variation.ValidateVariation(culture, segment, true, true, false));
Assert.AreEqual(nonExactAndNoWildcards, variation.ValidateVariation(culture, segment, false, false, false));
@@ -137,14 +142,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
/// Asserts the result of <see cref="ContentVariationExtensions.ValidateVariation(ContentVariation, string, string, bool, bool, bool)"/>
/// where expectedResult matches all combinations of Exact + Wildcard
/// </summary>
/// <param name="variation"></param>
/// <param name="culture"></param>
/// <param name="segment"></param>
/// <param name="expectedResult"></param>
private static void Assert4A(ContentVariation variation, string culture, string segment, bool expectedResult)
{
private static void Assert4A(ContentVariation variation, string culture, string segment, bool expectedResult) =>
Assert4B(variation, culture, segment, expectedResult, expectedResult, expectedResult, expectedResult);
}
[Test]
public void PropertyTests()
@@ -245,10 +244,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void ContentNames()
{
var contentType = new ContentTypeBuilder()
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
var content = CreateContent(contentType);
Content content = CreateContent(contentType);
const string langFr = "fr-FR";
const string langUk = "en-UK";
@@ -288,15 +287,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
{
const string langFr = "fr-FR";
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("prop")
.Build();
var contentType = new ContentTypeBuilder()
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
contentType.AddPropertyType(propertyType);
var content = CreateContent(contentType);
Content content = CreateContent(contentType);
// can set value
// and get edited value, published is null
@@ -378,7 +377,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.IsNull(content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
var other = CreateContent(contentType, 2, "other");
Content other = CreateContent(contentType, 2, "other");
Assert.Throws<NotSupportedException>(() => other.SetValue("prop", "o")); // don't even try
other.SetValue("prop", "o1", langFr);
@@ -401,24 +400,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void ContentPublishValuesWithMixedPropertyTypeVariations()
{
var propertyValidationService = GetPropertyValidationService();
PropertyValidationService propertyValidationService = GetPropertyValidationService();
const string langFr = "fr-FR";
// content type varies by Culture
// prop1 varies by Culture
// prop2 is invariant
var contentType = new ContentTypeBuilder()
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
contentType.Variations |= ContentVariation.Culture;
var variantPropType = new PropertyTypeBuilder()
PropertyType variantPropType = new PropertyTypeBuilder()
.WithAlias("prop1")
.WithVariations(ContentVariation.Culture)
.WithMandatory(true)
.Build();
var invariantPropType = new PropertyTypeBuilder()
PropertyType invariantPropType = new PropertyTypeBuilder()
.WithAlias("prop2")
.WithVariations(ContentVariation.Nothing)
.WithMandatory(true)
@@ -426,24 +424,25 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
contentType.AddPropertyType(variantPropType);
contentType.AddPropertyType(invariantPropType);
var content = CreateContent(contentType);
Content content = CreateContent(contentType);
content.SetCultureName("hello", langFr);
//for this test we'll make the french culture the default one - this is needed for publishing invariant property values
// for this test we'll make the french culture the default one - this is needed for publishing invariant property values
var langFrImpact = CultureImpact.Explicit(langFr, true);
Assert.IsTrue(content.PublishCulture(langFrImpact)); // succeeds because names are ok (not validating properties here)
Assert.IsFalse(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact));// fails because prop1 is mandatory
Assert.IsFalse(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact)); // fails because prop1 is mandatory
content.SetValue("prop1", "a", langFr);
Assert.IsTrue(content.PublishCulture(langFrImpact)); // succeeds because names are ok (not validating properties here)
// fails because prop2 is mandatory and invariant and the item isn't published.
// Fails because prop2 is mandatory and invariant and the item isn't published.
// Invariant is validated against the default language except when there isn't a published version, in that case it's always validated.
Assert.IsFalse(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact));
content.SetValue("prop2", "x");
Assert.IsTrue(content.PublishCulture(langFrImpact)); // still ok...
Assert.IsTrue(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact));// now it's ok
Assert.IsTrue(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact)); // now it's ok
Assert.AreEqual("a", content.GetValue("prop1", langFr, published: true));
Assert.AreEqual("x", content.GetValue("prop2", published: true));
@@ -456,15 +455,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
const string langUk = "en-UK";
const string langEs = "es-ES";
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("prop")
.Build();
var contentType = new ContentTypeBuilder()
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
contentType.AddPropertyType(propertyType);
var content = CreateContent(contentType);
Content content = CreateContent(contentType);
// change - now we vary by culture
contentType.Variations |= ContentVariation.Culture;
@@ -515,16 +514,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
[Test]
public void IsDirtyTests()
{
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("prop")
.Build();
var prop = new Property(propertyType);
var contentType = new ContentTypeBuilder()
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
contentType.AddPropertyType(propertyType);
var content = CreateContent(contentType);
Content content = CreateContent(contentType);
prop.SetValue("a");
Assert.AreEqual("a", prop.GetValue());
@@ -538,13 +537,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
Assert.IsTrue(content.IsDirty());
Assert.IsTrue(content.IsAnyUserPropertyDirty());
// how can we tell which variation was dirty?
//// how can we tell which variation was dirty?
}
[Test]
public void ValidationTests()
{
var propertyType = new PropertyTypeBuilder()
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("prop")
.WithSupportsPublishing(true)
.Build();
@@ -554,7 +553,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
prop.SetValue("a");
Assert.AreEqual("a", prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
var propertyValidationService = GetPropertyValidationService();
PropertyValidationService propertyValidationService = GetPropertyValidationService();
Assert.IsTrue(propertyValidationService.IsPropertyValid(prop));
@@ -568,24 +567,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
prop.PublishValues();
}
private static Content CreateContent(IContentType contentType, int id = 1, string name = "content")
{
return new ContentBuilder()
private static Content CreateContent(IContentType contentType, int id = 1, string name = "content") =>
new ContentBuilder()
.WithId(id)
.WithVersionId(1)
.WithName(name)
.WithContentType(contentType)
.Build();
}
private static PropertyValidationService GetPropertyValidationService()
{
var ioHelper = Mock.Of<IIOHelper>();
var dataTypeService = Mock.Of<IDataTypeService>();
var localizedTextService = Mock.Of<ILocalizedTextService>();
var localizationService = Mock.Of<ILocalizationService>();
var shortStringHelper = Mock.Of<IShortStringHelper>();
var jsonSerializer = Mock.Of<IJsonSerializer>();
IIOHelper ioHelper = Mock.Of<IIOHelper>();
IDataTypeService dataTypeService = Mock.Of<IDataTypeService>();
ILocalizedTextService localizedTextService = Mock.Of<ILocalizedTextService>();
ILocalizationService localizationService = Mock.Of<ILocalizationService>();
IShortStringHelper shortStringHelper = Mock.Of<IShortStringHelper>();
IJsonSerializer jsonSerializer = Mock.Of<IJsonSerializer>();
var textBoxEditor = new TextboxPropertyEditor(
NullLoggerFactory.Instance,
@@ -594,8 +591,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models
ioHelper,
shortStringHelper,
localizedTextService,
jsonSerializer
);
jsonSerializer);
var serializer = new ConfigurationEditorJsonSerializer();

View File

@@ -1,8 +1,10 @@
using System.IO;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Hosting;
using Umbraco.Core.Packaging;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Packaging
@@ -14,7 +16,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Packaging
private static FileInfo GetTestPackagePath(string packageName)
{
var testPackagesDirName = Path.Combine("Umbraco.Core","Packaging","Packages");
var testPackagesDirName = Path.Combine("Umbraco.Core", "Packaging", "Packages");
var testDir = TestContext.CurrentContext.TestDirectory.Split("bin")[0];
var path = Path.Combine(testDir, testPackagesDirName, packageName);
return new FileInfo(path);
@@ -27,7 +29,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Packaging
var sut = new PackageExtraction();
// Act
var result = sut.ReadFilesFromArchive(GetTestPackagePath(PackageFileName), new[] { "Package.xml" });
IEnumerable<byte[]> result = sut.ReadFilesFromArchive(GetTestPackagePath(PackageFileName), new[] { "Package.xml" });
// Assert
Assert.AreEqual(1, result.Count());
@@ -40,7 +42,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Packaging
var sut = new PackageExtraction();
// Act
var result = sut.FindMissingFiles(GetTestPackagePath(PackageFileName), new[] { "DoesNotExists.XYZ" });
IEnumerable<string> result = sut.FindMissingFiles(GetTestPackagePath(PackageFileName), new[] { "DoesNotExists.XYZ" });
// Assert
Assert.AreEqual(1, result.Count());

View File

@@ -1,8 +1,11 @@
using Newtonsoft.Json;
using NUnit.Framework;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Web.Compose;
@@ -15,15 +18,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
Formatting = Formatting.None,
NullValueHandling = NullValueHandling.Ignore,
};
private const string _contentGuid1 = "036ce82586a64dfba2d523a99ed80f58";
private const string _contentGuid2 = "48288c21a38a40ef82deb3eda90a58f6";
private const string _settingsGuid1 = "ffd35c4e2eea4900abfa5611b67b2492";
private const string _subContentGuid1 = "4c44ce6b3a5c4f5f8f15e3dc24819a9e";
private const string _subContentGuid2 = "a062c06d6b0b44ac892b35d90309c7f8";
private const string _subSettingsGuid1 = "4d998d980ffa4eee8afdc23c4abd6d29";
private const string ContentGuid1 = "036ce82586a64dfba2d523a99ed80f58";
private const string ContentGuid2 = "48288c21a38a40ef82deb3eda90a58f6";
private const string SettingsGuid1 = "ffd35c4e2eea4900abfa5611b67b2492";
private const string SubContentGuid1 = "4c44ce6b3a5c4f5f8f15e3dc24819a9e";
private const string SubContentGuid2 = "a062c06d6b0b44ac892b35d90309c7f8";
private const string SubSettingsGuid1 = "4d998d980ffa4eee8afdc23c4abd6d29";
[Test]
public void Cannot_Have_Null_Udi()
@@ -38,14 +40,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
var guids = Enumerable.Range(0, 3).Select(x => Guid.NewGuid()).ToList();
var guidCounter = 0;
Func<Guid> guidFactory = () => guids[guidCounter++];
Guid GuidFactory() => guids[guidCounter++];
var json = GetBlockListJson(null);
var expected = ReplaceGuids(json, guids, _contentGuid1, _contentGuid2, _settingsGuid1);
var expected = ReplaceGuids(json, guids, ContentGuid1, ContentGuid2, SettingsGuid1);
var component = new BlockEditorComponent();
var result = component.ReplaceBlockListUdis(json, guidFactory);
var result = component.ReplaceBlockListUdis(json, GuidFactory);
var expectedJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(expected, _serializerSettings), _serializerSettings);
var resultJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(result, _serializerSettings), _serializerSettings);
@@ -60,9 +62,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
var guids = Enumerable.Range(0, 6).Select(x => Guid.NewGuid()).ToList();
var guidCounter = 0;
Func<Guid> guidFactory = () => guids[guidCounter++];
Guid GuidFactory() => guids[guidCounter++];
var innerJson = GetBlockListJson(null, _subContentGuid1, _subContentGuid2, _subSettingsGuid1);
var innerJson = GetBlockListJson(null, SubContentGuid1, SubContentGuid2, SubSettingsGuid1);
// we need to ensure the escaped json is consistent with how it will be re-escaped after parsing
// and this is how to do that, the result will also include quotes around it.
@@ -72,12 +74,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
var json = GetBlockListJson(innerJsonEscaped);
var component = new BlockEditorComponent();
var result = component.ReplaceBlockListUdis(json, guidFactory);
var result = component.ReplaceBlockListUdis(json, GuidFactory);
// the expected result is that the subFeatures data is no longer escaped
var expected = ReplaceGuids(GetBlockListJson(innerJson), guids,
_contentGuid1, _contentGuid2, _settingsGuid1,
_subContentGuid1, _subContentGuid2, _subSettingsGuid1);
var expected = ReplaceGuids(
GetBlockListJson(innerJson),
guids,
ContentGuid1,
ContentGuid2,
SettingsGuid1,
SubContentGuid1,
SubContentGuid2,
SubSettingsGuid1);
var expectedJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(expected, _serializerSettings), _serializerSettings);
var resultJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(result, _serializerSettings), _serializerSettings);
@@ -91,20 +99,26 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
var guids = Enumerable.Range(0, 6).Select(x => Guid.NewGuid()).ToList();
var guidCounter = 0;
Func<Guid> guidFactory = () => guids[guidCounter++];
Guid GuidFactory() => guids[guidCounter++];
// nested blocks without property value escaping used in the conversion
var innerJson = GetBlockListJson(null, _subContentGuid1, _subContentGuid2, _subSettingsGuid1);
var innerJson = GetBlockListJson(null, SubContentGuid1, SubContentGuid2, SubSettingsGuid1);
// get the json with the subFeatures as unescaped
var json = GetBlockListJson(innerJson);
var expected = ReplaceGuids(GetBlockListJson(innerJson), guids,
_contentGuid1, _contentGuid2, _settingsGuid1,
_subContentGuid1, _subContentGuid2, _subSettingsGuid1);
var expected = ReplaceGuids(
GetBlockListJson(innerJson),
guids,
ContentGuid1,
ContentGuid2,
SettingsGuid1,
SubContentGuid1,
SubContentGuid2,
SubSettingsGuid1);
var component = new BlockEditorComponent();
var result = component.ReplaceBlockListUdis(json, guidFactory);
var result = component.ReplaceBlockListUdis(json, GuidFactory);
var expectedJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(expected, _serializerSettings), _serializerSettings);
var resultJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(result, _serializerSettings), _serializerSettings);
@@ -118,9 +132,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
var guids = Enumerable.Range(0, 6).Select(x => Guid.NewGuid()).ToList();
var guidCounter = 0;
Func<Guid> guidFactory = () => guids[guidCounter++];
Guid GuidFactory() => guids[guidCounter++];
var innerJson = GetBlockListJson(null, _subContentGuid1, _subContentGuid2, _subSettingsGuid1);
var innerJson = GetBlockListJson(null, SubContentGuid1, SubContentGuid2, SubSettingsGuid1);
// we need to ensure the escaped json is consistent with how it will be re-escaped after parsing
// and this is how to do that, the result will also include quotes around it.
@@ -132,12 +146,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
var json = GetBlockListJson(complexEditorJsonEscaped);
var component = new BlockEditorComponent();
var result = component.ReplaceBlockListUdis(json, guidFactory);
var result = component.ReplaceBlockListUdis(json, GuidFactory);
// the expected result is that the subFeatures data is no longer escaped
var expected = ReplaceGuids(GetBlockListJson(GetGridJson(innerJson)), guids,
_contentGuid1, _contentGuid2, _settingsGuid1,
_subContentGuid1, _subContentGuid2, _subSettingsGuid1);
var expected = ReplaceGuids(
GetBlockListJson(GetGridJson(innerJson)),
guids,
ContentGuid1,
ContentGuid2,
SettingsGuid1,
SubContentGuid1,
SubContentGuid2,
SubSettingsGuid1);
var expectedJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(expected, _serializerSettings), _serializerSettings);
var resultJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(result, _serializerSettings), _serializerSettings);
@@ -146,10 +166,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
Assert.AreEqual(expectedJson, resultJson);
}
private string GetBlockListJson(string subFeatures,
string contentGuid1 = _contentGuid1,
string contentGuid2 = _contentGuid2,
string settingsGuid1 = _settingsGuid1)
private string GetBlockListJson(
string subFeatures,
string contentGuid1 = ContentGuid1,
string contentGuid2 = ContentGuid2,
string settingsGuid1 = SettingsGuid1)
{
return @"{
""layout"":
@@ -254,8 +275,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
var old = oldGuids[i];
json = json.Replace(old, newGuids[i].ToString("N"));
}
return json;
}
}
}

View File

@@ -1,9 +1,9 @@
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Blocks;
@@ -18,50 +18,49 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
[TestFixture]
public class BlockListPropertyValueConverterTests
{
private readonly Guid ContentKey1 = Guid.NewGuid();
private readonly Guid ContentKey2 = Guid.NewGuid();
private readonly Guid _contentKey1 = Guid.NewGuid();
private readonly Guid _contentKey2 = Guid.NewGuid();
private const string ContentAlias1 = "Test1";
private const string ContentAlias2 = "Test2";
private readonly Guid SettingKey1 = Guid.NewGuid();
private readonly Guid SettingKey2 = Guid.NewGuid();
private readonly Guid _settingKey1 = Guid.NewGuid();
private readonly Guid _settingKey2 = Guid.NewGuid();
private const string SettingAlias1 = "Setting1";
private const string SettingAlias2 = "Setting2";
/// <summary>
/// Setup mocks for IPublishedSnapshotAccessor
/// </summary>
/// <returns></returns>
private IPublishedSnapshotAccessor GetPublishedSnapshotAccessor()
{
var test1ContentType = Mock.Of<IPublishedContentType>(x =>
IPublishedContentType test1ContentType = Mock.Of<IPublishedContentType>(x =>
x.IsElement == true
&& x.Key == ContentKey1
&& x.Key == _contentKey1
&& x.Alias == ContentAlias1);
var test2ContentType = Mock.Of<IPublishedContentType>(x =>
IPublishedContentType test2ContentType = Mock.Of<IPublishedContentType>(x =>
x.IsElement == true
&& x.Key == ContentKey2
&& x.Key == _contentKey2
&& x.Alias == ContentAlias2);
var test3ContentType = Mock.Of<IPublishedContentType>(x =>
IPublishedContentType test3ContentType = Mock.Of<IPublishedContentType>(x =>
x.IsElement == true
&& x.Key == SettingKey1
&& x.Key == _settingKey1
&& x.Alias == SettingAlias1);
var test4ContentType = Mock.Of<IPublishedContentType>(x =>
IPublishedContentType test4ContentType = Mock.Of<IPublishedContentType>(x =>
x.IsElement == true
&& x.Key == SettingKey2
&& x.Key == _settingKey2
&& x.Alias == SettingAlias2);
var contentCache = new Mock<IPublishedContentCache>();
contentCache.Setup(x => x.GetContentType(ContentKey1)).Returns(test1ContentType);
contentCache.Setup(x => x.GetContentType(ContentKey2)).Returns(test2ContentType);
contentCache.Setup(x => x.GetContentType(SettingKey1)).Returns(test3ContentType);
contentCache.Setup(x => x.GetContentType(SettingKey2)).Returns(test4ContentType);
var publishedSnapshot = Mock.Of<IPublishedSnapshot>(x => x.Content == contentCache.Object);
var publishedSnapshotAccessor = Mock.Of<IPublishedSnapshotAccessor>(x => x.PublishedSnapshot == publishedSnapshot);
contentCache.Setup(x => x.GetContentType(_contentKey1)).Returns(test1ContentType);
contentCache.Setup(x => x.GetContentType(_contentKey2)).Returns(test2ContentType);
contentCache.Setup(x => x.GetContentType(_settingKey1)).Returns(test3ContentType);
contentCache.Setup(x => x.GetContentType(_settingKey2)).Returns(test4ContentType);
IPublishedSnapshot publishedSnapshot = Mock.Of<IPublishedSnapshot>(x => x.Content == contentCache.Object);
IPublishedSnapshotAccessor publishedSnapshotAccessor = Mock.Of<IPublishedSnapshotAccessor>(x => x.PublishedSnapshot == publishedSnapshot);
return publishedSnapshotAccessor;
}
private BlockListPropertyValueConverter CreateConverter()
{
var publishedSnapshotAccessor = GetPublishedSnapshotAccessor();
IPublishedSnapshotAccessor publishedSnapshotAccessor = GetPublishedSnapshotAccessor();
var publishedModelFactory = new NoopPublishedModelFactory();
var editor = new BlockListPropertyValueConverter(
Mock.Of<IProfilingLogger>(),
@@ -71,34 +70,36 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
private BlockListConfiguration ConfigForMany() => new BlockListConfiguration
{
Blocks = new[] {
new BlockListConfiguration.BlockConfiguration
{
ContentElementTypeKey = ContentKey1,
SettingsElementTypeKey = SettingKey2
},
new BlockListConfiguration.BlockConfiguration
{
ContentElementTypeKey = ContentKey2,
SettingsElementTypeKey = SettingKey1
}
Blocks = new[]
{
new BlockListConfiguration.BlockConfiguration
{
ContentElementTypeKey = _contentKey1,
SettingsElementTypeKey = _settingKey2
},
new BlockListConfiguration.BlockConfiguration
{
ContentElementTypeKey = _contentKey2,
SettingsElementTypeKey = _settingKey1
}
}
};
private BlockListConfiguration ConfigForSingle() => new BlockListConfiguration
{
Blocks = new[] {
new BlockListConfiguration.BlockConfiguration
{
ContentElementTypeKey = ContentKey1
}
Blocks = new[]
{
new BlockListConfiguration.BlockConfiguration
{
ContentElementTypeKey = _contentKey1
}
}
};
private IPublishedPropertyType GetPropertyType(BlockListConfiguration config)
{
var dataType = new PublishedDataType(1, "test", new Lazy<object>(() => config));
var propertyType = Mock.Of<IPublishedPropertyType>(x =>
IPublishedPropertyType propertyType = Mock.Of<IPublishedPropertyType>(x =>
x.EditorAlias == Constants.PropertyEditors.Aliases.BlockList
&& x.DataType == dataType);
return propertyType;
@@ -107,7 +108,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
[Test]
public void Is_Converter_For()
{
var editor = CreateConverter();
BlockListPropertyValueConverter editor = CreateConverter();
Assert.IsTrue(editor.IsConverter(Mock.Of<IPublishedPropertyType>(x => x.EditorAlias == Constants.PropertyEditors.Aliases.BlockList)));
Assert.IsFalse(editor.IsConverter(Mock.Of<IPublishedPropertyType>(x => x.EditorAlias == Constants.PropertyEditors.Aliases.NestedContent)));
}
@@ -115,13 +116,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
[Test]
public void Get_Value_Type_Multiple()
{
var editor = CreateConverter();
var config = ConfigForMany();
BlockListPropertyValueConverter editor = CreateConverter();
BlockListConfiguration config = ConfigForMany();
var dataType = new PublishedDataType(1, "test", new Lazy<object>(() => config));
var propType = Mock.Of<IPublishedPropertyType>(x => x.DataType == dataType);
IPublishedPropertyType propType = Mock.Of<IPublishedPropertyType>(x => x.DataType == dataType);
var valueType = editor.GetPropertyValueType(propType);
Type valueType = editor.GetPropertyValueType(propType);
// the result is always block list model
Assert.AreEqual(typeof(BlockListModel), valueType);
@@ -130,13 +131,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
[Test]
public void Get_Value_Type_Single()
{
var editor = CreateConverter();
var config = ConfigForSingle();
BlockListPropertyValueConverter editor = CreateConverter();
BlockListConfiguration config = ConfigForSingle();
var dataType = new PublishedDataType(1, "test", new Lazy<object>(() => config));
var propType = Mock.Of<IPublishedPropertyType>(x => x.DataType == dataType);
IPublishedPropertyType propType = Mock.Of<IPublishedPropertyType>(x => x.DataType == dataType);
var valueType = editor.GetPropertyValueType(propType);
Type valueType = editor.GetPropertyValueType(propType);
// the result is always block list model
Assert.AreEqual(typeof(BlockListModel), valueType);
@@ -145,10 +146,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
[Test]
public void Convert_Null_Empty()
{
var editor = CreateConverter();
var config = ConfigForMany();
var propertyType = GetPropertyType(config);
var publishedElement = Mock.Of<IPublishedElement>();
BlockListPropertyValueConverter editor = CreateConverter();
BlockListConfiguration config = ConfigForMany();
IPublishedPropertyType propertyType = GetPropertyType(config);
IPublishedElement publishedElement = Mock.Of<IPublishedElement>();
string json = null;
var converted = editor.ConvertIntermediateToObject(publishedElement, propertyType, PropertyCacheLevel.None, json, false) as BlockListModel;
@@ -166,12 +167,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
[Test]
public void Convert_Valid_Empty_Json()
{
var editor = CreateConverter();
var config = ConfigForMany();
var propertyType = GetPropertyType(config);
var publishedElement = Mock.Of<IPublishedElement>();
BlockListPropertyValueConverter editor = CreateConverter();
BlockListConfiguration config = ConfigForMany();
IPublishedPropertyType propertyType = GetPropertyType(config);
IPublishedElement publishedElement = Mock.Of<IPublishedElement>();
var json = "{}";
string json = "{}";
var converted = editor.ConvertIntermediateToObject(publishedElement, propertyType, PropertyCacheLevel.None, json, false) as BlockListModel;
Assert.IsNotNull(converted);
@@ -237,7 +238,7 @@ data: []}";
},
contentData: [
{
'contentTypeKey': '" + ContentKey1 + @"',
'contentTypeKey': '" + _contentKey1 + @"',
'key': '1304E1DD-0000-4396-84FE-8A399231CB3D'
}
]
@@ -252,12 +253,12 @@ data: []}";
[Test]
public void Convert_Valid_Json()
{
var editor = CreateConverter();
var config = ConfigForMany();
var propertyType = GetPropertyType(config);
var publishedElement = Mock.Of<IPublishedElement>();
BlockListPropertyValueConverter editor = CreateConverter();
BlockListConfiguration config = ConfigForMany();
IPublishedPropertyType propertyType = GetPropertyType(config);
IPublishedElement publishedElement = Mock.Of<IPublishedElement>();
var json = @"
string json = @"
{
layout: {
'" + Constants.PropertyEditors.Aliases.BlockList + @"': [
@@ -268,7 +269,7 @@ data: []}";
},
contentData: [
{
'contentTypeKey': '" + ContentKey1 + @"',
'contentTypeKey': '" + _contentKey1 + @"',
'udi': 'umb://element/1304E1DDAC87439684FE8A399231CB3D'
}
]
@@ -277,7 +278,7 @@ data: []}";
Assert.IsNotNull(converted);
Assert.AreEqual(1, converted.Count);
var item0 = converted[0].Content;
IPublishedElement item0 = converted[0].Content;
Assert.AreEqual(Guid.Parse("1304E1DD-AC87-4396-84FE-8A399231CB3D"), item0.Key);
Assert.AreEqual("Test1", item0.ContentType.Alias);
Assert.IsNull(converted[0].Settings);
@@ -287,12 +288,12 @@ data: []}";
[Test]
public void Get_Data_From_Layout_Item()
{
var editor = CreateConverter();
var config = ConfigForMany();
var propertyType = GetPropertyType(config);
var publishedElement = Mock.Of<IPublishedElement>();
BlockListPropertyValueConverter editor = CreateConverter();
BlockListConfiguration config = ConfigForMany();
IPublishedPropertyType propertyType = GetPropertyType(config);
IPublishedElement publishedElement = Mock.Of<IPublishedElement>();
var json = @"
string json = @"
{
layout: {
'" + Constants.PropertyEditors.Aliases.BlockList + @"': [
@@ -308,29 +309,29 @@ data: []}";
},
contentData: [
{
'contentTypeKey': '" + ContentKey1 + @"',
'contentTypeKey': '" + _contentKey1 + @"',
'udi': 'umb://element/1304E1DDAC87439684FE8A399231CB3D'
},
{
'contentTypeKey': '" + ContentKey2 + @"',
'contentTypeKey': '" + _contentKey2 + @"',
'udi': 'umb://element/E05A034704424AB3A520E048E6197E79'
},
{
'contentTypeKey': '" + ContentKey2 + @"',
'contentTypeKey': '" + _contentKey2 + @"',
'udi': 'umb://element/0A4A416E547D464FABCC6F345C17809A'
}
],
settingsData: [
{
'contentTypeKey': '" + SettingKey1 + @"',
'contentTypeKey': '" + _settingKey1 + @"',
'udi': 'umb://element/63027539B0DB45E7B70459762D4E83DD'
},
{
'contentTypeKey': '" + SettingKey2 + @"',
'contentTypeKey': '" + _settingKey2 + @"',
'udi': 'umb://element/1F613E26CE274898908A561437AF5100'
},
{
'contentTypeKey': '" + SettingKey2 + @"',
'contentTypeKey': '" + _settingKey2 + @"',
'udi': 'umb://element/BCF4BA3DA40C496C93EC58FAC85F18B9'
}
],
@@ -341,42 +342,42 @@ data: []}";
Assert.IsNotNull(converted);
Assert.AreEqual(2, converted.Count);
var item0 = converted[0];
BlockListItem item0 = converted[0];
Assert.AreEqual(Guid.Parse("1304E1DD-AC87-4396-84FE-8A399231CB3D"), item0.Content.Key);
Assert.AreEqual("Test1", item0.Content.ContentType.Alias);
Assert.AreEqual(Guid.Parse("1F613E26CE274898908A561437AF5100"), item0.Settings.Key);
Assert.AreEqual("Setting2", item0.Settings.ContentType.Alias);
var item1 = converted[1];
BlockListItem item1 = converted[1];
Assert.AreEqual(Guid.Parse("0A4A416E-547D-464F-ABCC-6F345C17809A"), item1.Content.Key);
Assert.AreEqual("Test2", item1.Content.ContentType.Alias);
Assert.AreEqual(Guid.Parse("63027539B0DB45E7B70459762D4E83DD"), item1.Settings.Key);
Assert.AreEqual("Setting1", item1.Settings.ContentType.Alias);
}
[Test]
public void Data_Item_Removed_If_Removed_From_Config()
{
var editor = CreateConverter();
BlockListPropertyValueConverter editor = CreateConverter();
// The data below expects that ContentKey1 + ContentKey2 + SettingsKey1 + SettingsKey2 exist but only ContentKey2 exists so
// the data should all be filtered.
var config = new BlockListConfiguration
{
Blocks = new[] {
Blocks = new[]
{
new BlockListConfiguration.BlockConfiguration
{
ContentElementTypeKey = ContentKey2,
ContentElementTypeKey = _contentKey2,
SettingsElementTypeKey = null
}
}
};
var propertyType = GetPropertyType(config);
var publishedElement = Mock.Of<IPublishedElement>();
IPublishedPropertyType propertyType = GetPropertyType(config);
IPublishedElement publishedElement = Mock.Of<IPublishedElement>();
var json = @"
string json = @"
{
layout: {
'" + Constants.PropertyEditors.Aliases.BlockList + @"': [
@@ -392,29 +393,29 @@ data: []}";
},
contentData: [
{
'contentTypeKey': '" + ContentKey1 + @"',
'contentTypeKey': '" + _contentKey1 + @"',
'udi': 'umb://element/1304E1DDAC87439684FE8A399231CB3D'
},
{
'contentTypeKey': '" + ContentKey2 + @"',
'contentTypeKey': '" + _contentKey2 + @"',
'udi': 'umb://element/E05A034704424AB3A520E048E6197E79'
},
{
'contentTypeKey': '" + ContentKey2 + @"',
'contentTypeKey': '" + _contentKey2 + @"',
'udi': 'umb://element/0A4A416E547D464FABCC6F345C17809A'
}
],
settingsData: [
{
'contentTypeKey': '" + SettingKey1 + @"',
'contentTypeKey': '" + _settingKey1 + @"',
'udi': 'umb://element/63027539B0DB45E7B70459762D4E83DD'
},
{
'contentTypeKey': '" + SettingKey2 + @"',
'contentTypeKey': '" + _settingKey2 + @"',
'udi': 'umb://element/1F613E26CE274898908A561437AF5100'
},
{
'contentTypeKey': '" + SettingKey2 + @"',
'contentTypeKey': '" + _settingKey2 + @"',
'udi': 'umb://element/BCF4BA3DA40C496C93EC58FAC85F18B9'
}
],
@@ -425,12 +426,10 @@ data: []}";
Assert.IsNotNull(converted);
Assert.AreEqual(1, converted.Count);
var item0 = converted[0];
BlockListItem item0 = converted[0];
Assert.AreEqual(Guid.Parse("0A4A416E-547D-464F-ABCC-6F345C17809A"), item0.Content.Key);
Assert.AreEqual("Test2", item0.Content.ContentType.Alias);
Assert.IsNull(item0.Settings);
}
}
}

View File

@@ -1,4 +1,9 @@
using System.Linq;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
@@ -15,13 +20,24 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
[TestFixture]
public class ColorListValidatorTest
{
private ILoggerFactory _loggerFactory = NullLoggerFactory.Instance;
private readonly ILoggerFactory _loggerFactory = NullLoggerFactory.Instance;
[Test]
public void Only_Tests_On_JArray()
{
var validator = new ColorPickerConfigurationEditor.ColorListValidator();
var result = validator.Validate("hello", null, new ColorPickerPropertyEditor(_loggerFactory, Mock.Of<IDataTypeService>(), Mock.Of<ILocalizationService>(), Mock.Of<IIOHelper>(), Mock.Of<IShortStringHelper>(), Mock.Of<ILocalizedTextService>(), new JsonNetSerializer()));
IEnumerable<ValidationResult> result =
validator.Validate(
"hello",
null,
new ColorPickerPropertyEditor(
_loggerFactory,
Mock.Of<IDataTypeService>(),
Mock.Of<ILocalizationService>(),
Mock.Of<IIOHelper>(),
Mock.Of<IShortStringHelper>(),
Mock.Of<ILocalizedTextService>(),
new JsonNetSerializer()));
Assert.AreEqual(0, result.Count());
}
@@ -29,7 +45,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
public void Only_Tests_On_JArray_Of_Item_JObject()
{
var validator = new ColorPickerConfigurationEditor.ColorListValidator();
var result = validator.Validate(new JArray("hello", "world"), null, new ColorPickerPropertyEditor(_loggerFactory, Mock.Of<IDataTypeService>(), Mock.Of<ILocalizationService>(), Mock.Of<IIOHelper>(), Mock.Of<IShortStringHelper>(), Mock.Of<ILocalizedTextService>(), new JsonNetSerializer()));
IEnumerable<ValidationResult> result =
validator.Validate(
new JArray("hello", "world"),
null,
new ColorPickerPropertyEditor(
_loggerFactory,
Mock.Of<IDataTypeService>(),
Mock.Of<ILocalizationService>(),
Mock.Of<IIOHelper>(),
Mock.Of<IShortStringHelper>(),
Mock.Of<ILocalizedTextService>(),
new JsonNetSerializer()));
Assert.AreEqual(0, result.Count());
}
@@ -37,12 +64,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
public void Validates_Color_Vals()
{
var validator = new ColorPickerConfigurationEditor.ColorListValidator();
var result = validator.Validate(new JArray(
JObject.FromObject(new { value = "CC0000" }),
JObject.FromObject(new { value = "zxcvzxcvxzcv" }),
JObject.FromObject(new { value = "ABC" }),
JObject.FromObject(new { value = "1234567" })),
null, new ColorPickerPropertyEditor(_loggerFactory, Mock.Of<IDataTypeService>(), Mock.Of<ILocalizationService>(), Mock.Of<IIOHelper>(), Mock.Of<IShortStringHelper>(), Mock.Of<ILocalizedTextService>(), new JsonNetSerializer()));
IEnumerable<ValidationResult> result =
validator.Validate(
new JArray(
JObject.FromObject(new { value = "CC0000" }),
JObject.FromObject(new { value = "zxcvzxcvxzcv" }),
JObject.FromObject(new { value = "ABC" }),
JObject.FromObject(new { value = "1234567" })),
null,
new ColorPickerPropertyEditor(
_loggerFactory,
Mock.Of<IDataTypeService>(),
Mock.Of<ILocalizationService>(),
Mock.Of<IIOHelper>(),
Mock.Of<IShortStringHelper>(),
Mock.Of<ILocalizedTextService>(),
new JsonNetSerializer()));
Assert.AreEqual(2, result.Count());
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
@@ -45,7 +48,6 @@ namespace Umbraco.Tests.Published
}, Mock.Of<IPublishedValueFallback>());
register.AddTransient(f => factory);
var cacheMock = new Mock<IPublishedContentCache>();
var cacheContent = new Dictionary<int, IPublishedContent>();
cacheMock.Setup(x => x.GetById(It.IsAny<int>())).Returns<int>(id =>
@@ -62,11 +64,24 @@ namespace Umbraco.Tests.Published
var serializer = new ConfigurationEditorJsonSerializer();
var dataTypeServiceMock = new Mock<IDataTypeService>();
var dataType1 = new DataType(new VoidEditor(NullLoggerFactory.Instance, dataTypeServiceMock.Object,
Mock.Of<ILocalizationService>(), Mock.Of<ILocalizedTextService>(), Mock.Of<IShortStringHelper>(), new JsonNetSerializer()),
var dataType1 = new DataType(
new VoidEditor(
NullLoggerFactory.Instance,
dataTypeServiceMock.Object,
Mock.Of<ILocalizationService>(),
Mock.Of<ILocalizedTextService>(),
Mock.Of<IShortStringHelper>(),
new JsonNetSerializer()),
serializer) { Id = 1 };
var dataType2 = new DataType(new VoidEditor("2", NullLoggerFactory.Instance, Mock.Of<IDataTypeService>(),
Mock.Of<ILocalizationService>(), Mock.Of<ILocalizedTextService>(), Mock.Of<IShortStringHelper>(), new JsonNetSerializer()),
var dataType2 = new DataType(
new VoidEditor(
"2",
NullLoggerFactory.Instance,
Mock.Of<IDataTypeService>(),
Mock.Of<ILocalizationService>(),
Mock.Of<ILocalizedTextService>(),
Mock.Of<IShortStringHelper>(),
new JsonNetSerializer()),
serializer) { Id = 2 };
dataTypeServiceMock.Setup(x => x.GetAll()).Returns(new[] { dataType1, dataType2 });
@@ -87,10 +102,16 @@ namespace Umbraco.Tests.Published
IPublishedContentType contentType2 =
contentTypeFactory.CreateContentType(Guid.NewGuid(), 1003, "content2", t => CreatePropertyTypes(t, 2));
var element1 = new PublishedElement(elementType1, Guid.NewGuid(),
new Dictionary<string, object> { { "prop1", "val1" } }, false);
var element2 = new PublishedElement(elementType2, Guid.NewGuid(),
new Dictionary<string, object> { { "prop2", "1003" } }, false);
var element1 = new PublishedElement(
elementType1,
Guid.NewGuid(),
new Dictionary<string, object> { { "prop1", "val1" } },
false);
var element2 = new PublishedElement(
elementType2,
Guid.NewGuid(),
new Dictionary<string, object> { { "prop2", "1003" } },
false);
var cnt1 = new SolidPublishedContent(contentType1)
{
Id = 1003,
@@ -115,9 +136,11 @@ namespace Umbraco.Tests.Published
// can get the actual property Clr type
// ie ModelType gets properly mapped by IPublishedContentModelFactory
// must test ModelClrType with special equals 'cos they are not ref-equals
Assert.IsTrue(ModelType.Equals(typeof(IEnumerable<>).MakeGenericType(ModelType.For("content1")),
Assert.IsTrue(ModelType.Equals(
typeof(IEnumerable<>).MakeGenericType(ModelType.For("content1")),
contentType2.GetPropertyType("prop2").ModelClrType));
Assert.AreEqual(typeof(IEnumerable<PublishedSnapshotTestObjects.TestContentModel1>),
Assert.AreEqual(
typeof(IEnumerable<PublishedSnapshotTestObjects.TestContentModel1>),
contentType2.GetPropertyType("prop2").ClrType);
// can create a model for an element
@@ -133,9 +156,9 @@ namespace Umbraco.Tests.Published
// and get direct property
Assert.IsInstanceOf<PublishedSnapshotTestObjects.TestContentModel1[]>(
model2.Value(Mock.Of<IPublishedValueFallback>(), "prop2"));
Assert.AreEqual(1,
((PublishedSnapshotTestObjects.TestContentModel1[])model2.Value(Mock.Of<IPublishedValueFallback>(),
"prop2")).Length);
Assert.AreEqual(
1,
((PublishedSnapshotTestObjects.TestContentModel1[])model2.Value(Mock.Of<IPublishedValueFallback>(), "prop2")).Length);
// and get model property
Assert.IsInstanceOf<IEnumerable<PublishedSnapshotTestObjects.TestContentModel1>>(mmodel2.Prop2);
@@ -174,15 +197,21 @@ namespace Umbraco.Tests.Published
public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType)
=> PropertyCacheLevel.Elements;
public override object ConvertSourceToIntermediate(IPublishedElement owner,
IPublishedPropertyType propertyType, object source, bool preview)
public override object ConvertSourceToIntermediate(
IPublishedElement owner,
IPublishedPropertyType propertyType,
object source,
bool preview)
{
var s = source as string;
return s?.Split(',').Select(int.Parse).ToArray() ?? Array.Empty<int>();
}
public override object ConvertIntermediateToObject(IPublishedElement owner,
IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter,
public override object ConvertIntermediateToObject(
IPublishedElement owner,
IPublishedPropertyType propertyType,
PropertyCacheLevel referenceCacheLevel,
object inter,
bool preview) => ((int[])inter).Select(x =>
(PublishedSnapshotTestObjects.TestContentModel1)_publishedSnapshotAccessor.PublishedSnapshot.Content
.GetById(x)).ToArray();

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging.Abstractions;
@@ -20,19 +23,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
[TestFixture]
public class DataValueReferenceFactoryCollectionTests
{
IDataTypeService DataTypeService { get; } = Mock.Of<IDataTypeService>();
private IDataTypeService DataTypeService { get; } = Mock.Of<IDataTypeService>();
private IIOHelper IOHelper { get; } = Mock.Of<IIOHelper>();
ILocalizedTextService LocalizedTextService { get; } = Mock.Of<ILocalizedTextService>();
ILocalizationService LocalizationService { get; } = Mock.Of<ILocalizationService>();
IShortStringHelper ShortStringHelper { get; } = Mock.Of<IShortStringHelper>();
IJsonSerializer JsonSerializer { get; } = new JsonNetSerializer();
private ILocalizedTextService LocalizedTextService { get; } = Mock.Of<ILocalizedTextService>();
private ILocalizationService LocalizationService { get; } = Mock.Of<ILocalizationService>();
private IShortStringHelper ShortStringHelper { get; } = Mock.Of<IShortStringHelper>();
private IJsonSerializer JsonSerializer { get; } = new JsonNetSerializer();
[Test]
public void GetAllReferences_All_Variants_With_IDataValueReferenceFactory()
{
var collection = new DataValueReferenceFactoryCollection(new TestDataValueReferenceFactory().Yield());
// label does not implement IDataValueReference
var labelEditor = new LabelPropertyEditor(
NullLoggerFactory.Instance,
@@ -41,8 +48,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
LocalizedTextService,
LocalizationService,
ShortStringHelper,
JsonSerializer
);
JsonSerializer);
var propertyEditors = new PropertyEditorCollection(new DataEditorCollection(labelEditor.Yield()));
var trackedUdi1 = Udi.Create(Constants.UdiEntityType.Media, Guid.NewGuid()).ToString();
var trackedUdi2 = Udi.Create(Constants.UdiEntityType.Media, Guid.NewGuid()).ToString();
@@ -72,13 +78,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
Segment = "A",
EditedValue = trackedUdi3
},
// Ignored (no culture)
new PropertyValue
{
Segment = "A",
EditedValue = trackedUdi4
},
// duplicate
// Duplicate
new PropertyValue
{
Culture = "en-US",
@@ -91,7 +99,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
property
};
var result = collection.GetAllReferences(properties, propertyEditors);
IEnumerable<UmbracoEntityReference> result = collection.GetAllReferences(properties, propertyEditors);
Assert.AreEqual(2, result.Count());
Assert.AreEqual(trackedUdi2, result.ElementAt(0).Udi.ToString());
@@ -111,8 +119,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
IOHelper,
ShortStringHelper,
LocalizedTextService,
JsonSerializer
);
JsonSerializer);
var propertyEditors = new PropertyEditorCollection(new DataEditorCollection(mediaPicker.Yield()));
var trackedUdi1 = Udi.Create(Constants.UdiEntityType.Media, Guid.NewGuid()).ToString();
var trackedUdi2 = Udi.Create(Constants.UdiEntityType.Media, Guid.NewGuid()).ToString();
@@ -142,13 +149,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
Segment = "A",
EditedValue = trackedUdi3
},
// Ignored (no culture)
new PropertyValue
{
Segment = "A",
EditedValue = trackedUdi4
},
// duplicate
// Duplicate
new PropertyValue
{
Culture = "en-US",
@@ -161,7 +170,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
property
};
var result = collection.GetAllReferences(properties, propertyEditors);
IEnumerable<UmbracoEntityReference> result = collection.GetAllReferences(properties, propertyEditors);
Assert.AreEqual(2, result.Count());
Assert.AreEqual(trackedUdi2, result.ElementAt(0).Udi.ToString());
@@ -181,8 +190,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
IOHelper,
ShortStringHelper,
LocalizedTextService,
JsonSerializer
);
JsonSerializer);
var propertyEditors = new PropertyEditorCollection(new DataEditorCollection(mediaPicker.Yield()));
var trackedUdi1 = Udi.Create(Constants.UdiEntityType.Media, Guid.NewGuid()).ToString();
var trackedUdi2 = Udi.Create(Constants.UdiEntityType.Media, Guid.NewGuid()).ToString();
@@ -200,12 +208,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
EditedValue = trackedUdi1
},
// Ignored (has culture)
new PropertyValue
{
Culture = "en-US",
EditedValue = trackedUdi2
},
// Ignored (has culture)
new PropertyValue
{
@@ -218,7 +228,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
Segment = "A",
EditedValue = trackedUdi4
},
// duplicate
// Duplicate
new PropertyValue
{
Segment = "B",
@@ -230,7 +241,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
property
};
var result = collection.GetAllReferences(properties, propertyEditors);
IEnumerable<UmbracoEntityReference> result = collection.GetAllReferences(properties, propertyEditors);
Assert.AreEqual(2, result.Count());
Assert.AreEqual(trackedUdi1, result.ElementAt(0).Udi.ToString());
@@ -247,14 +258,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors
{
public IEnumerable<UmbracoEntityReference> GetReferences(object value)
{
// This is the same as the media picker, it will just try to parse the value directly as a UDI
// This is the same as the media picker, it will just try to parse the value directly as a UDI.
var asString = value is string str ? str : value?.ToString();
if (string.IsNullOrEmpty(asString)) yield break;
if (string.IsNullOrEmpty(asString))
{
yield break;
}
if (UdiParser.TryParse(asString, out var udi))
if (UdiParser.TryParse(asString, out Udi udi))
{
yield return new UmbracoEntityReference(udi);
}
}
}
}

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