diff --git a/src/Umbraco.Infrastructure/Configuration/NCronTabParser.cs b/src/Umbraco.Infrastructure/Configuration/NCronTabParser.cs index 5642c882e6..ca25563730 100644 --- a/src/Umbraco.Infrastructure/Configuration/NCronTabParser.cs +++ b/src/Umbraco.Infrastructure/Configuration/NCronTabParser.cs @@ -1,9 +1,8 @@ -using System; +using System; using NCrontab; namespace Umbraco.Core.Configuration { - public class NCronTabParser : ICronTabParser { public bool IsValidCronTab(string cronTab) diff --git a/src/Umbraco.Tests.UnitTests/AutoFixture/AutoMoqDataAttribute.cs b/src/Umbraco.Tests.UnitTests/AutoFixture/AutoMoqDataAttribute.cs index 365dca780c..bed11ca866 100644 --- a/src/Umbraco.Tests.UnitTests/AutoFixture/AutoMoqDataAttribute.cs +++ b/src/Umbraco.Tests.UnitTests/AutoFixture/AutoMoqDataAttribute.cs @@ -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 - { - /// - /// 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 - /// - 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 /// - 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( - u => u.FromFactory( - (a,b,c) => BackOfficeIdentityUser.CreateNew(new GlobalSettings(),a,b,c))); + u => u.FromFactory( + (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>(cc => cc.FromFactory(() => Mock.Of>())); @@ -93,13 +81,11 @@ namespace Umbraco.Tests.UnitTests.AutoFixture Mock.Of(x => x.Level == RuntimeLevel.Run)))); var connectionStrings = new ConnectionStrings(); - fixture.Customize(x => x.FromFactory(() => connectionStrings )); - + fixture.Customize(x => x.FromFactory(() => connectionStrings)); var httpContextAccessor = new HttpContextAccessor { HttpContext = new DefaultHttpContext() }; fixture.Customize(x => x.FromFactory(() => httpContextAccessor.HttpContext)); fixture.Customize(x => x.FromFactory(() => httpContextAccessor)); - } } } diff --git a/src/Umbraco.Tests.UnitTests/AutoFixture/InlineAutoMoqDataAttribute.cs b/src/Umbraco.Tests.UnitTests/AutoFixture/InlineAutoMoqDataAttribute.cs new file mode 100644 index 0000000000..0c182e6116 --- /dev/null +++ b/src/Umbraco.Tests.UnitTests/AutoFixture/InlineAutoMoqDataAttribute.cs @@ -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 + { + /// + /// 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 + /// + public InlineAutoMoqDataAttribute(params object[] arguments) + : base(() => AutoMoqDataAttribute.AutoMockCustomizations.Default, arguments) + { + } + } +} diff --git a/src/Umbraco.Tests.UnitTests/TestHelpers/BaseUsingSqlSyntax.cs b/src/Umbraco.Tests.UnitTests/TestHelpers/BaseUsingSqlSyntax.cs index 52bc1880a3..76f96ead05 100644 --- a/src/Umbraco.Tests.UnitTests/TestHelpers/BaseUsingSqlSyntax.cs +++ b/src/Umbraco.Tests.UnitTests/TestHelpers/BaseUsingSqlSyntax.cs @@ -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 Sql() - { - return NPoco.Sql.BuilderFor(SqlContext); - } + protected Sql 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(), TestHelper.GetMockedTypeLoader()); - composition.WithCollectionBuilder() .AddCoreMappers(); - composition.Services.AddUnique(_ => 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(); diff --git a/src/Umbraco.Tests.UnitTests/TestHelpers/CompositionExtensions.cs b/src/Umbraco.Tests.UnitTests/TestHelpers/CompositionExtensions.cs index 5481bfcd76..806878fcc3 100644 --- a/src/Umbraco.Tests.UnitTests/TestHelpers/CompositionExtensions.cs +++ b/src/Umbraco.Tests.UnitTests/TestHelpers/CompositionExtensions.cs @@ -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 { diff --git a/src/Umbraco.Tests.UnitTests/TestHelpers/Objects/TestUmbracoContextFactory.cs b/src/Umbraco.Tests.UnitTests/TestHelpers/Objects/TestUmbracoContextFactory.cs index 7889d49192..91d05ba0df 100644 --- a/src/Umbraco.Tests.UnitTests/TestHelpers/Objects/TestUmbracoContextFactory.cs +++ b/src/Umbraco.Tests.UnitTests/TestHelpers/Objects/TestUmbracoContextFactory.cs @@ -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 /// 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(); - if (publishedUrlProvider == null) publishedUrlProvider = Mock.Of(); + if (globalSettings == null) + { + globalSettings = new GlobalSettings(); + } + + if (umbracoContextAccessor == null) + { + umbracoContextAccessor = new TestUmbracoContextAccessor(); + } + + if (httpContextAccessor == null) + { + httpContextAccessor = Mock.Of(); + } + + if (publishedUrlProvider == null) + { + publishedUrlProvider = Mock.Of(); + } var contentCache = new Mock(); var mediaCache = new Mock(); @@ -37,11 +54,10 @@ namespace Umbraco.Tests.UnitTests.TestHelpers.Objects var snapshotService = new Mock(); snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())).Returns(snapshot.Object); - var hostingEnvironment = Mock.Of(); + IHostingEnvironment hostingEnvironment = Mock.Of(); var backofficeSecurityAccessorMock = new Mock(); backofficeSecurityAccessorMock.Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); - - + 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(), - backofficeSecurityAccessorMock.Object - ); + backofficeSecurityAccessorMock.Object); return umbracoContextFactory; } diff --git a/src/Umbraco.Tests.UnitTests/TestHelpers/TestHelper.cs b/src/Umbraco.Tests.UnitTests/TestHelpers/TestHelper.cs index e7d6eec391..0b0f3120d0 100644 --- a/src/Umbraco.Tests.UnitTests/TestHelpers/TestHelper.cs +++ b/src/Umbraco.Tests.UnitTests/TestHelpers/TestHelper.cs @@ -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 /// 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(); @@ -68,9 +68,9 @@ namespace Umbraco.Tests.TestHelpers { var testPath = TestContext.CurrentContext.TestDirectory.Split("bin")[0]; return new AspNetCoreHostingEnvironment( - Mock.Of>(x=>x.CurrentValue == new HostingSettings()), + Mock.Of>(x => x.CurrentValue == new HostingSettings()), Mock.Of( - x=> + x => x.WebRootPath == "/" && x.ContentRootPath == testPath)); } @@ -82,13 +82,13 @@ namespace Umbraco.Tests.TestHelpers => Mock.Of(); } - 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 GetMockSqlContext() { - var sqlContext = Mock.Of(); + ISqlContext sqlContext = Mock.Of(); var syntax = new SqlServerSyntaxProvider(); Mock.Get(sqlContext).Setup(x => x.SqlSyntax).Returns(syntax); return new Lazy(() => 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(); /// /// Gets the working directory of the test project. /// /// The assembly directory. - 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())); - /// /// 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 /// - /// - /// - 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 { - { 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(false); + EditorBrowsableAttribute att = property.GetCustomAttribute(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 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(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() ?? "", actual?.ToString() ?? ""); + Assert.AreEqual( + expected, + actual, + "Property {0}.{1} does not match. Expected: {2} but was: {3}", + property.DeclaringType.Name, + property.Name, + expected?.ToString() ?? "", + actual?.ToString() ?? ""); } } private static void AssertListsAreEqual(PropertyInfo property, IEnumerable expected, IEnumerable actual, Func 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().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().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(); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Configuration/Models/ConnectionStringsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Configuration/Models/ConnectionStringsTests.cs index 544765ee9c..7d3099eb58 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Configuration/Models/ConnectionStringsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Configuration/Models/ConnectionStringsTests.cs @@ -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; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/AttemptTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/AttemptTests.cs index 9a16c5b10f..be1e3cc0d8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/AttemptTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/AttemptTests.cs @@ -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); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs index 64bdca6437..e681fc6841 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs @@ -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(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 { 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 { ClaimType = expectedClaimType, ClaimValue = expectedClaimValue}); + _testUser.Claims.Add(new IdentityUserClaim { ClaimType = expectedClaimType, ClaimValue = expectedClaimValue }); _mockUserManager.Setup(x => x.SupportsUserClaim).Returns(true); _mockUserManager.Setup(x => x.GetClaimsAsync(_testUser)).ReturnsAsync( - new List {new Claim(expectedClaimType, expectedClaimValue)}); + new List { 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)); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/IdentityExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/IdentityExtensionsTests.cs index 0c8b469f02..3b2d0391e2 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/IdentityExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/IdentityExtensionsTests.cs @@ -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 {new IdentityError {Code = "1", Description = expectedError}}; + var errors = new List { 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 { - 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); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/NopLookupNormalizerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/NopLookupNormalizerTests.cs index 02ff01ff3b..f4ea348892 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/NopLookupNormalizerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/NopLookupNormalizerTests.cs @@ -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("")] diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/UmbracoBackOfficeIdentityTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/UmbracoBackOfficeIdentityTests.cs index 79a9456643..35e143277a 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/UmbracoBackOfficeIdentityTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/UmbracoBackOfficeIdentityTests.cs @@ -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()); } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/AppCacheTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/AppCacheTests.cs index a30e254235..fe5d1ea819 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/AppCacheTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/AppCacheTests.cs @@ -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 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(); 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 { } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DeepCloneAppCacheTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DeepCloneAppCacheTests.cs index cbcd164b62..f653cf50f1 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DeepCloneAppCacheTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DeepCloneAppCacheTests.cs @@ -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 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)); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DefaultCachePolicyTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DefaultCachePolicyTests.cs index a8592356e9..9cb6af72fc 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DefaultCachePolicyTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DefaultCachePolicyTests.cs @@ -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(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback(() => - { - isCached = true; - }); + .Callback(() => isCached = true); var defaultPolicy = new DefaultRepositoryCachePolicy(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions()); @@ -58,15 +58,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache var cached = new List(); var cache = new Mock(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((string cacheKey, Func o, TimeSpan? t, bool b, string[] s) => - { - cached.Add(cacheKey); - }); - cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new AuditItem[] {}); + .Callback((string cacheKey, Func o, TimeSpan? t, bool b, string[] s) => cached.Add(cacheKey)); + cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new AuditItem[] { }); var defaultPolicy = new DefaultRepositoryCachePolicy(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(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(); cache.Setup(x => x.Clear(It.IsAny())) - .Callback(() => - { - cacheCleared = true; - }); + .Callback(() => cacheCleared = true); var defaultPolicy = new DefaultRepositoryCachePolicy(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(); cache.Setup(x => x.Clear(It.IsAny())) - .Callback(() => - { - cacheCleared = true; - }); + .Callback(() => cacheCleared = true); var defaultPolicy = new DefaultRepositoryCachePolicy(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 { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DictionaryAppCacheTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DictionaryAppCacheTests.cs index 91d71d3144..13c0f16d0c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DictionaryAppCacheTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DictionaryAppCacheTests.cs @@ -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 diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DistributedCache/DistributedCacheTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DistributedCache/DistributedCacheTests.cs index 0d5b1edb31..1023e47dfa 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DistributedCache/DistributedCacheTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/DistributedCache/DistributedCacheTests.cs @@ -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 IntIdsRefreshed = new List(); public List GuidIdsRefreshed = new List(); public List IntIdsRemoved = new List(); @@ -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(ICacheRefresher refresher, Func getNumericId, params T[] instances) - { - IntIdsRefreshed.AddRange(instances.Select(getNumericId)); - } + public void PerformRefresh(ICacheRefresher refresher, Func getNumericId, params T[] instances) => IntIdsRefreshed.AddRange(instances.Select(getNumericId)); - public void PerformRefresh(ICacheRefresher refresher, Func getGuidId, params T[] instances) - { - GuidIdsRefreshed.AddRange(instances.Select(getGuidId)); - } + public void PerformRefresh(ICacheRefresher refresher, Func 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(ICacheRefresher refresher, Func getNumericId, params T[] instances) - { - IntIdsRemoved.AddRange(instances.Select(getNumericId)); - } + public void PerformRemove(ICacheRefresher refresher, Func 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 } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/FullDataSetCachePolicyTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/FullDataSetCachePolicyTests.cs index e904f9104e..87b61502c5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/FullDataSetCachePolicyTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/FullDataSetCachePolicyTests.cs @@ -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(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback(() => - { - isCached = true; - }); + .Callback(() => isCached = true); var policy = new FullDataSetRepositoryCachePolicy(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(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(); @@ -84,20 +84,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache list = o() as IList; }); - cache.Setup(x => x.Get(It.IsAny())).Returns(() => - { - //return null if this is the first pass - return cached.Any() ? new DeepCloneableList(ListCloneBehavior.CloneOnce) : null; - }); + + // Return null if this is the first pass. + cache.Setup(x => x.Get(It.IsAny())) + .Returns(() => cached.Any() ? new DeepCloneableList(ListCloneBehavior.CloneOnce) : null); var policy = new FullDataSetRepositoryCachePolicy(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(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(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(); @@ -151,14 +150,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache var defaultPolicy = new FullDataSetRepositoryCachePolicy(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(); cache.Setup(x => x.Clear(It.IsAny())) - .Callback(() => - { - cacheCleared = true; - }); + .Callback(() => cacheCleared = true); var defaultPolicy = new FullDataSetRepositoryCachePolicy(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(); cache.Setup(x => x.Clear(It.IsAny())) - .Callback(() => - { - cacheCleared = true; - }); + .Callback(() => cacheCleared = true); var defaultPolicy = new FullDataSetRepositoryCachePolicy(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 { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/HttpRequestAppCacheTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/HttpRequestAppCacheTests.cs index 02a10fcff4..ac8ded80e3 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/HttpRequestAppCacheTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/HttpRequestAppCacheTests.cs @@ -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); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ObjectAppCacheTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ObjectAppCacheTests.cs index 51639d7c49..255c76ff46 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ObjectAppCacheTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/ObjectAppCacheTests.cs @@ -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; } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RefresherTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RefresherTests.cs index 59d2f010d2..754dc8b830 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RefresherTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RefresherTests.cs @@ -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(json); + MediaCacheRefresher.JsonPayload[] payload = JsonConvert.DeserializeObject(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(json); + ContentCacheRefresher.JsonPayload[] payload = JsonConvert.DeserializeObject(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(json); + ContentTypeCacheRefresher.JsonPayload[] payload = JsonConvert.DeserializeObject(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(json); + DataTypeCacheRefresher.JsonPayload[] payload = JsonConvert.DeserializeObject(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(json); + DomainCacheRefresher.JsonPayload[] payload = JsonConvert.DeserializeObject(json); Assert.AreEqual(source[0].Id, payload[0].Id); Assert.AreEqual(source[0].ChangeType, payload[0].ChangeType); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RuntimeAppCacheTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RuntimeAppCacheTests.cs index 33a71b1044..41214bdb58 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RuntimeAppCacheTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RuntimeAppCacheTests.cs @@ -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("DateTimeTest")); Assert.AreEqual(now, AppCache.GetCacheItem("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("DateTimeTest")); Assert.AreEqual(null, AppCache.GetCacheItem("DateTimeTest")); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/SingleItemsOnlyCachePolicyTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/SingleItemsOnlyCachePolicyTests.cs index 323b83699c..ffd5c90ce3 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/SingleItemsOnlyCachePolicyTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/SingleItemsOnlyCachePolicyTests.cs @@ -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(); var cache = new Mock(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((string cacheKey, Func o, TimeSpan? t, bool b, string[] s) => - { - cached.Add(cacheKey); - }); + .Callback((string cacheKey, Func o, TimeSpan? t, bool b, string[] s) => cached.Add(cacheKey)); cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new AuditItem[] { }); var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy(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(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback(() => - { - isCached = true; - }); + .Callback(() => isCached = true); var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy(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); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ClaimsIdentityExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ClaimsIdentityExtensionsTests.cs index 76f928ca46..7125e13e90 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ClaimsIdentityExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ClaimsIdentityExtensionsTests.cs @@ -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 {expectedClaim}); + var identity = new ClaimsIdentity(new List { 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 {expectedClaim, dupeClaim}); + var identity = new ClaimsIdentity(new List { expectedClaim, dupeClaim }); var value = identity.FindFirstValue("test"); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Collections/DeepCloneableListTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Collections/DeepCloneableListTests.cs index bcfe142d8d..57237d907e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Collections/DeepCloneableListTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Collections/DeepCloneableListTests.cs @@ -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(ListCloneBehavior.CloneOnce); - list.Add(new TestClone()); - list.Add(new TestClone()); - list.Add(new TestClone()); + var list = new DeepCloneableList(ListCloneBehavior.CloneOnce) + { + new TestClone(), + new TestClone(), + new TestClone() + }; var cloned = list.DeepClone() as DeepCloneableList; - //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; - //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(ListCloneBehavior.Always); - list.Add(new TestClone()); - list.Add(new TestClone()); - list.Add(new TestClone()); + var list = new DeepCloneableList(ListCloneBehavior.Always) + { + new TestClone(), + new TestClone(), + new TestClone() + }; var cloned = list.DeepClone() as DeepCloneableList; @@ -60,14 +67,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Collections [Test] public void Clones_Each_Item() { - var list = new DeepCloneableList(ListCloneBehavior.Always); - list.Add(new TestClone()); - list.Add(new TestClone()); - list.Add(new TestClone()); + var list = new DeepCloneableList(ListCloneBehavior.Always) + { + new TestClone(), + new TestClone(), + new TestClone() + }; - var cloned = (DeepCloneableList) list.DeepClone(); + var cloned = (DeepCloneableList)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(ListCloneBehavior.Always); - list.Add(new TestClone()); - list.Add(new TestClone()); - list.Add(new TestClone()); + var list = new DeepCloneableList(ListCloneBehavior.Always) + { + new TestClone(), + new TestClone(), + new TestClone() + }; - var cloned = (DeepCloneableList) list.DeepClone(); + var cloned = (DeepCloneableList)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); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Collections/OrderedHashSetTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Collections/OrderedHashSetTests.cs index df7f004884..06d935cfd8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Collections/OrderedHashSetTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Collections/OrderedHashSetTests.cs @@ -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(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(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; } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs index 6d51603502..dcedfb83d4 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Components/ComponentTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.IO; @@ -35,17 +38,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components private static IServiceProvider MockFactory(Action> setup = null) { // FIXME: use IUmbracoDatabaseFactory vs UmbracoDatabaseFactory, clean it all up! - var mock = new Mock(); - var loggerFactory = NullLoggerFactory.Instance; - var logger = loggerFactory.CreateLogger("GenericLogger"); - var typeFinder = TestHelper.GetTypeFinder(); + NullLoggerFactory loggerFactory = NullLoggerFactory.Instance; + ILogger logger = loggerFactory.CreateLogger("GenericLogger"); + ITypeFinder typeFinder = TestHelper.GetTypeFinder(); var globalSettings = new GlobalSettings(); var connectionStrings = new ConnectionStrings(); var f = new UmbracoDatabaseFactory(loggerFactory.CreateLogger(), loggerFactory, Options.Create(globalSettings), Options.Create(connectionStrings), new Lazy(() => new MapperCollection(Enumerable.Empty())), TestHelper.DbProviderFactoryCreator); var fs = new FileSystems(mock.Object, loggerFactory.CreateLogger(), loggerFactory, IOHelper, Options.Create(globalSettings), Mock.Of()); var coreDebug = new CoreDebugSettings(); - var mediaFileSystem = Mock.Of(); + IMediaFileSystem mediaFileSystem = Mock.Of(); var p = new ScopeProvider(f, fs, Options.Create(coreDebug), mediaFileSystem, loggerFactory.CreateLogger(), loggerFactory, typeFinder, NoAppCache.Instance); mock.Setup(x => x.GetService(typeof(ILogger))).Returns(logger); @@ -59,57 +61,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(); - } - - private static TypeLoader MockTypeLoader() - { - var ioHelper = IOHelper; - return new TypeLoader(Mock.Of(), Mock.Of(), new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of>(), Mock.Of()); - } - + private static IServiceCollection MockRegister() => new ServiceCollection(); + private static TypeLoader MockTypeLoader() => new TypeLoader(Mock.Of(), Mock.Of(), new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of>(), Mock.Of()); [Test] public void Boot1A() { - var register = MockRegister(); + IServiceCollection register = MockRegister(); var composition = new UmbracoBuilder(register, Mock.Of(), TestHelper.GetMockedTypeLoader()); - var types = TypeArray(); + Type[] types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of>()); Composed.Clear(); + // 2 is Core and requires 4 // 3 is User // => reorder components accordingly composers.Compose(); AssertTypeArray(TypeArray(), Composed); - var factory = MockFactory(m => + IServiceProvider factory = MockFactory(m => { m.Setup(x => x.GetService(It.Is(t => t == typeof(ISomeResource)))).Returns(() => new SomeResource()); m.Setup(x => x.GetService(It.IsAny())).Returns((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>(), Mock.Of()); + } + if (type == typeof(ILogger)) + { return Mock.Of>(); + } + throw new NotSupportedException(type.FullName); }); }); - var builder = composition.WithCollectionBuilder(); + ComponentCollectionBuilder builder = composition.WithCollectionBuilder(); builder.RegisterWith(register); - var components = builder.CreateCollection(factory); + ComponentCollection components = builder.CreateCollection(factory); Assert.IsEmpty(components); components.Initialize(); @@ -121,12 +129,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(), TestHelper.GetMockedTypeLoader()); - var types = TypeArray(); + Type[] types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of>()); Composed.Clear(); + // 2 is Core and requires 4 // 3 is User - stays with RuntimeLevel.Run // => reorder components accordingly @@ -137,12 +146,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(), TestHelper.GetMockedTypeLoader()); - var types = TypeArray(); + Type[] types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of>()); Composed.Clear(); + // 21 is required by 20 // => reorder components accordingly composers.Compose(); @@ -152,12 +162,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(), TestHelper.GetMockedTypeLoader()); - var types = TypeArray(); + Type[] types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of>()); Composed.Clear(); + // i23 requires 22 // 24, 25 implement i23 // 25 required by i23 @@ -169,10 +180,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(), TestHelper.GetMockedTypeLoader()); - var types = TypeArray(); + Type[] types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of>()); Composed.Clear(); try @@ -192,12 +203,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(), TestHelper.GetMockedTypeLoader()); - var types = TypeArray(); + Type[] types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of>()); Composed.Clear(); + // 2 is Core and requires 4 // 13 is required by 1 // 1 is missing @@ -213,42 +225,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(t => t == typeof(ISomeResource)))).Returns(() => new SomeResource()); m.Setup(x => x.GetService(It.IsAny())).Returns((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>(), Mock.Of()); + } + if (type == typeof(ILogger)) + { return Mock.Of>(); + } + throw new NotSupportedException(type.FullName); }); }); var composition = new UmbracoBuilder(register, Mock.Of(), 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(), Mock.Of>()); Assert.IsEmpty(Composed); composers.Compose(); AssertTypeArray(TypeArray(), Composed); - var builder = composition.WithCollectionBuilder(); + ComponentCollectionBuilder builder = composition.WithCollectionBuilder(); builder.RegisterWith(register); - var components = builder.CreateCollection(factory); + ComponentCollection components = builder.CreateCollection(factory); Assert.IsEmpty(Initialized); components.Initialize(); @@ -262,10 +295,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(), 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(), Mock.Of>()); Composed.Clear(); composers.Compose(); @@ -277,10 +310,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(), 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(), Mock.Of>()); Composed.Clear(); composers.Compose(); @@ -292,18 +325,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(), 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(), Mock.Of>()); Composed.Clear(); composers.Compose(); - var builder = composition.WithCollectionBuilder(); + ComponentCollectionBuilder builder = composition.WithCollectionBuilder(); 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]); @@ -313,10 +346,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(), TestHelper.GetMockedTypeLoader()); - var types = new[] { typeof(Composer10) }; + Type[] types = new[] { typeof(Composer10) }; var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of>()); Composed.Clear(); composers.Compose(); @@ -329,7 +362,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components Assert.Throws(() => composers.Compose()); Console.WriteLine("throws:"); composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of>()); - var requirements = composers.GetRequirements(false); + Dictionary> requirements = composers.GetRequirements(false); Console.WriteLine(Composers.GetComposersReport(requirements)); types = new[] { typeof(Composer2) }; @@ -352,10 +385,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(), 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(), Mock.Of>()); Composed.Clear(); composers.Compose(); @@ -367,11 +400,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(), 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>()); Composed.Clear(); composers.Compose(); @@ -389,47 +422,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>(), Mock.Of()); - var register = MockRegister(); + IServiceCollection register = MockRegister(); var builder = new UmbracoBuilder(register, Mock.Of(), TestHelper.GetMockedTypeLoader()); - var allComposers = typeLoader.GetTypes().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(), Mock.Of>()); - var requirements = composers.GetRequirements(); - var report = Composers.GetComposersReport(requirements); + Dictionary> requirements = composers.GetRequirements(); + string report = Composers.GetComposersReport(requirements); Console.WriteLine(report); - var composerTypes = composers.SortComposers(requirements); + IEnumerable 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 { @@ -452,151 +485,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() => new[] { typeof(T1) }; - private static Type[] TypeArray() - { - return new[] { typeof(T1) }; - } + private static Type[] TypeArray() => new[] { typeof(T1), typeof(T2) }; - private static Type[] TypeArray() - { - return new[] { typeof(T1), typeof(T2) }; - } + private static Type[] TypeArray() => new[] { typeof(T1), typeof(T2), typeof(T3) }; - private static Type[] TypeArray() - { - return new[] { typeof(T1), typeof(T2), typeof(T3) }; - } + private static Type[] TypeArray() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }; - private static Type[] TypeArray() - { - return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }; - } + private static Type[] TypeArray() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }; - private static Type[] TypeArray() - { - return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }; - } + private static Type[] TypeArray() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }; - private static Type[] TypeArray() - { - return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }; - } + private static Type[] TypeArray() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) }; - private static Type[] TypeArray() - { - return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) }; - } - - private static Type[] TypeArray() - { - return new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) }; - } + private static Type[] TypeArray() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) }; private static void AssertTypeArray(IReadOnlyList expected, IReadOnlyList 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 } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/CollectionBuildersTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/CollectionBuildersTests.cs index b4131ca790..1c4a401e2e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/CollectionBuildersTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/CollectionBuildersTests.cs @@ -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(), TestHelper.GetMockedTypeLoader()); } @@ -32,24 +35,24 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing [Test] public void ContainsTypes() { - var builder = _composition.WithCollectionBuilder() + TestCollectionBuilder builder = _composition.WithCollectionBuilder() .Append() .Append(); Assert.IsTrue(builder.Has()); Assert.IsTrue(builder.Has()); Assert.IsFalse(builder.Has()); - //Assert.IsFalse(col.ContainsType()); // does not compile + //// Assert.IsFalse(col.ContainsType()); // 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 builder = _composition.WithCollectionBuilder() .Append() .Append(); @@ -57,20 +60,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.IsFalse(builder.Has()); Assert.IsFalse(builder.Has()); - 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 builder = _composition.WithCollectionBuilder() .Append() .Append(); - var factory = _composition.CreateServiceProvider(); - var col = builder.CreateCollection(factory); + IServiceProvider factory = _composition.CreateServiceProvider(); + TestCollection col = builder.CreateCollection(factory); Assert.Throws(() => builder.Clear()); } @@ -78,7 +81,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing [Test] public void CanAppendToBuilder() { - var builder = _composition.WithCollectionBuilder(); + TestCollectionBuilder builder = _composition.WithCollectionBuilder(); builder.Append(); builder.Append(); @@ -86,52 +89,48 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.IsTrue(builder.Has()); Assert.IsFalse(builder.Has()); - 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 builder = _composition.WithCollectionBuilder(); - var factory = _composition.CreateServiceProvider(); - var col = builder.CreateCollection(factory); + IServiceProvider factory = _composition.CreateServiceProvider(); + TestCollection col = builder.CreateCollection(factory); - Assert.Throws(() => - builder.Append() - ); + Assert.Throws(() => builder.Append()); } [Test] public void CanAppendDuplicateToBuilderAndDeDuplicate() { - var builder = _composition.WithCollectionBuilder(); + TestCollectionBuilder builder = _composition.WithCollectionBuilder(); builder.Append(); builder.Append(); - 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 builder = _composition.WithCollectionBuilder(); - //builder.Append(); // does not compile - Assert.Throws(() => - builder.Append(new[] { typeof(Resolved4) }) // throws - ); + ////builder.Append(); // does not compile + Assert.Throws(() => builder.Append(new[] { typeof(Resolved4) })); } [Test] public void CanRemoveFromBuilder() { - var builder = _composition.WithCollectionBuilder() + TestCollectionBuilder builder = _composition.WithCollectionBuilder() .Append() .Append() .Remove(); @@ -140,42 +139,40 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.IsFalse(builder.Has()); Assert.IsFalse(builder.Has()); - 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 builder = _composition.WithCollectionBuilder() .Append() .Append() .Remove(); - 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 builder = _composition.WithCollectionBuilder() .Append() .Append(); - var factory = _composition.CreateServiceProvider(); - var col = builder.CreateCollection(factory); - Assert.Throws(() => - builder.Remove() // throws - ); + IServiceProvider factory = _composition.CreateServiceProvider(); + TestCollection col = builder.CreateCollection(factory); + Assert.Throws(() => builder.Remove()); } [Test] public void CanInsertIntoBuilder() { - var builder = _composition.WithCollectionBuilder() + TestCollectionBuilder builder = _composition.WithCollectionBuilder() .Append() .Append() .Insert(); @@ -184,69 +181,63 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.IsTrue(builder.Has()); Assert.IsTrue(builder.Has()); - 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 builder = _composition.WithCollectionBuilder() .Append() .Append(); - var factory = _composition.CreateServiceProvider(); - var col = builder.CreateCollection(factory); - Assert.Throws(() => - builder.Insert() // throws - ); + IServiceProvider factory = _composition.CreateServiceProvider(); + TestCollection col = builder.CreateCollection(factory); + Assert.Throws(() => builder.Insert()); } [Test] public void CanInsertDuplicateIntoBuilderAndDeDuplicate() { - var builder = _composition.WithCollectionBuilder() + TestCollectionBuilder builder = _composition.WithCollectionBuilder() .Append() .Append() .Insert(); - 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 builder = _composition.WithCollectionBuilder(); builder.Insert(); - 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 builder = _composition.WithCollectionBuilder() .Append() .Append(); - Assert.Throws(() => - builder.Insert(99) // throws - ); + Assert.Throws(() => builder.Insert(99)); - Assert.Throws(() => - builder.Insert(-1) // throws - ); + Assert.Throws(() => builder.Insert(-1)); } [Test] public void CanInsertIntoBuilderBefore() { - var builder = _composition.WithCollectionBuilder() + TestCollectionBuilder builder = _composition.WithCollectionBuilder() .Append() .Append() .InsertBefore(); @@ -255,15 +246,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.IsTrue(builder.Has()); Assert.IsTrue(builder.Has()); - 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 builder = _composition.WithCollectionBuilder() .Append() .Append() .InsertAfter(); @@ -272,15 +263,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.IsTrue(builder.Has()); Assert.IsTrue(builder.Has()); - 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 builder = _composition.WithCollectionBuilder() .Append() .Append() .InsertAfter(); @@ -289,47 +280,45 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.IsTrue(builder.Has()); Assert.IsTrue(builder.Has()); - 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 builder = _composition.WithCollectionBuilder() .Append() .Append(); - var factory = _composition.CreateServiceProvider(); - var col = builder.CreateCollection(factory); + IServiceProvider factory = _composition.CreateServiceProvider(); + TestCollection col = builder.CreateCollection(factory); Assert.Throws(() => - builder.InsertBefore() - ); + builder.InsertBefore()); } [Test] public void CanInsertDuplicateIntoBuilderBeforeAndDeDuplicate() { - var builder = _composition.WithCollectionBuilder() + TestCollectionBuilder builder = _composition.WithCollectionBuilder() .Append() .Append() .InsertBefore(); - 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 builder = _composition.WithCollectionBuilder() .Append(); Assert.Throws(() => - builder.InsertBefore() - ); + builder.InsertBefore()); } [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 col1 = scope.ServiceProvider.GetRequiredService(); AssertCollection(col1, typeof(Resolved1), typeof(Resolved2)); - var col2 = scope.ServiceProvider.GetRequiredService(); + TestCollection col2 = scope.ServiceProvider.GetRequiredService(); 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 col1 = factory.GetRequiredService(); AssertCollection(col1, typeof(Resolved1), typeof(Resolved2)); - var col2 = factory.GetRequiredService(); + TestCollection col2 = factory.GetRequiredService(); 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 builder = _composition.WithCollectionBuilder() .Append() .Insert() .InsertBefore(); - 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(); col1B = scope.ServiceProvider.GetRequiredService(); @@ -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(); } @@ -432,43 +416,43 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing [Test] public void WeightedBuilderCreatesWeightedCollection() { - var builder = _composition.WithCollectionBuilder() + TestCollectionBuilderWeighted builder = _composition.WithCollectionBuilder() .Add() .Add(); - 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 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 col1, IEnumerable 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 @@ -542,9 +527,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing { public TestCollection(IEnumerable items) : base(items) - { } + { + } } - - #endregion } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/ComposingTestBase.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/ComposingTestBase.cs index 1c8bf139ac..1010424f75 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/ComposingTestBase.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/ComposingTestBase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Collections.Generic; using System.IO; using System.Reflection; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/CompositionTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/CompositionTests.cs index 1401d7c66f..984f598ef4 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/CompositionTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/CompositionTests.cs @@ -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 { - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/LazyCollectionBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/LazyCollectionBuilderTests.cs index c87b267c1a..9179e9e086 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/LazyCollectionBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/LazyCollectionBuilderTests.cs @@ -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 { + /// + /// Tests for lazy collection builder. + /// + /// + /// 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. + /// [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(), TestHelper.GetMockedTypeLoader()); - composition.WithCollectionBuilder() .Add() .Add() .Add() .Add(); - var factory = composition.CreateServiceProvider(); + IServiceProvider factory = composition.CreateServiceProvider(); - var values = factory.GetRequiredService(); + TestCollection values = factory.GetRequiredService(); 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 other = factory.GetRequiredService(); 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(), TestHelper.GetMockedTypeLoader()); - composition.WithCollectionBuilder() .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 values = factory.GetRequiredService(); 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 other = factory.GetRequiredService(); 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(), TestHelper.GetMockedTypeLoader()); - composition.WithCollectionBuilder() .Add() .Add() .Add() .Add(() => new[] { typeof(TransientObject1) }); - var factory = composition.CreateServiceProvider(); + IServiceProvider factory = composition.CreateServiceProvider(); - var values = factory.GetRequiredService(); + TestCollection values = factory.GetRequiredService(); 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 other = factory.GetRequiredService(); 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(), TestHelper.GetMockedTypeLoader()); composition.WithCollectionBuilder() .Add() // illegal, does not implement the interface! - //.Add() + ////.Add() // legal so far... .Add(() => new[] { typeof(TransientObject4) }); @@ -125,14 +123,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.Throws(() => { // 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(), TestHelper.GetMockedTypeLoader()); composition.WithCollectionBuilder() @@ -140,9 +138,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing .Add(() => new[] { typeof(TransientObject3), typeof(TransientObject2), typeof(TransientObject1) }) .Exclude(); - var factory = composition.CreateServiceProvider(); + IServiceProvider factory = composition.CreateServiceProvider(); - var values = factory.GetRequiredService(); + TestCollection values = factory.GetRequiredService(); 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 other = factory.GetRequiredService(); 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 @@ -186,9 +187,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing { public TestCollection(IEnumerable items) : base(items) - { } + { + } } - - #endregion } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/PackageActionCollectionTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/PackageActionCollectionTests.cs index 17e406e02f..702d4f9c8a 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/PackageActionCollectionTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/PackageActionCollectionTests.cs @@ -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(), TestHelper.GetMockedTypeLoader()); - - var expectedPackageActions = TypeLoader.GetPackageActions(); + IEnumerable expectedPackageActions = TypeLoader.GetPackageActions(); composition.WithCollectionBuilder() .Add(() => expectedPackageActions); - var factory = composition.CreateServiceProvider(); + IServiceProvider factory = composition.CreateServiceProvider(); - var actions = factory.GetRequiredService(); + PackageActionCollection actions = factory.GetRequiredService(); 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 } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeFinderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeFinderTests.cs index 9ef2cf5ae0..1becc88138 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeFinderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeFinderTests.cs @@ -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 { - /// /// Tests for typefinder /// @@ -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>(), new DefaultUmbracoAssemblyProvider(GetType().Assembly), new VaryingRuntimeHash()); - var typesFound = typeFinder.FindClassesOfTypeWithAttribute(_assemblies); + IEnumerable typesFound = typeFinder.FindClassesOfTypeWithAttribute(_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>(), new DefaultUmbracoAssemblyProvider(GetType().Assembly), new VaryingRuntimeHash()); - var typesFound = typeFinder.FindClassesWithAttribute(_assemblies); + IEnumerable typesFound = typeFinder.FindClassesWithAttribute(_assemblies); Assert.AreEqual(0, typesFound.Count()); // 0 classes in _assemblies are marked with [Tree] - typesFound = typeFinder.FindClassesWithAttribute(new[] { typeof (TreeAttribute).Assembly }); + typesFound = typeFinder.FindClassesWithAttribute(new[] { typeof(TreeAttribute).Assembly }); Assert.AreEqual(22, typesFound.Count()); // + classes in Umbraco.Web are marked with [Tree] typesFound = typeFinder.FindClassesWithAttribute(); @@ -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 { - } - } - - } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeHelperTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeHelperTests.cs index c78992d68c..3126cce538 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeHelperTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeHelperTests.cs @@ -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 + { + } + private interface IBase + { + } - class Base { } + private interface IDerived : IBase + { + } - interface IBase { } + private class Derived : Base, IBase + { + } - interface IDerived : IBase { } + private class Derived2 : Derived + { + } - class Derived : Base, IBase { } - - class Derived2 : Derived { } - - class DerivedI : IDerived { } + private class DerivedI : IDerived + { + } [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 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 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 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 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 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), typeof(System.Collections.IEnumerable), bindings)); Assert.AreEqual(0, bindings.Count); - var t1 = typeof(IList<>); // IList<> - var a1 = t1.GetGenericArguments()[0]; // + Type t1 = typeof(IList<>); // IList<> + Type a1 = t1.GetGenericArguments()[0]; // t1 = t1.MakeGenericType(a1); // IList - var t2 = a1; + Type t2 = a1; bindings = new Dictionary(); 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), 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 // both are OK - Assert.IsTrue(TypeHelper.MatchType(typeof(Dictionary), t1)); Assert.IsFalse(TypeHelper.MatchType(typeof(Dictionary), t1)); @@ -164,7 +174,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.IsTrue(TypeHelper.MatchType(typeof(Derived2), typeof(IBase<>))); Assert.IsTrue(TypeHelper.MatchType(typeof(int?), typeof(Nullable<>))); - Assert.IsTrue(TypeHelper.MatchType(typeof(Derived), typeof(object))); Assert.IsFalse(TypeHelper.MatchType(typeof(Derived), typeof(List<>))); Assert.IsFalse(TypeHelper.MatchType(typeof(Derived), typeof(IEnumerable<>))); @@ -172,21 +181,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing Assert.IsTrue(TypeHelper.MatchType(typeof(List), typeof(IEnumerable))); Assert.IsFalse(TypeHelper.MatchType(typeof(int), typeof(Nullable<>))); - //This get's the "Type" from the Count extension method on IEnumerable, however the type IEnumerable isn't + // This get's the "Type" from the Count extension method on IEnumerable, however the type IEnumerable 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), 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); 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); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderExtensions.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderExtensions.cs index 6bab57ee41..3179985c99 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderExtensions.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderExtensions.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using Umbraco.Core.Composing; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderTests.cs index 36843ad1cc..5049f6cc0b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderTests.cs @@ -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>(), new ProfilingLogger(Mock.Of>(), Mock.Of()), 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>(), + new ProfilingLogger(Mock.Of>(), Mock.Of()), + 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(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(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, @" @@ -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> plugins = _typeLoader.TryGetCached(typeof(object), null); + Attempt> 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 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>(), Mock.Of())); - var hash2 = GetFileHash(list2, new ProfilingLogger(Mock.Of>(), Mock.Of())); - var hash3 = GetFileHash(list3, new ProfilingLogger(Mock.Of>(), Mock.Of())); + // Act + string hash1 = GetFileHash(list1, new ProfilingLogger(Mock.Of>(), Mock.Of())); + string hash2 = GetFileHash(list2, new ProfilingLogger(Mock.Of>(), Mock.Of())); + string hash3 = GetFileHash(list3, new ProfilingLogger(Mock.Of>(), Mock.Of())); - //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 foundTypes1 = _typeLoader.ResolveFindMeTypes(); Assert.AreEqual(2, foundTypes1.Count()); } [Test] public void GetDataEditors() { - var types = _typeLoader.GetDataEditors(); + IEnumerable 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 { - } - /// /// Returns a unique hash for a combination of FileInfo objects. /// @@ -324,19 +333,23 @@ AnotherContentFinder { using (logger.DebugDuration("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(); + using var generator = new HashGenerator(); - foreach (var fileOrFolder in filesAndFolders) + // Get the distinct file infos to hash. + var uniqInfos = new HashSet(); + + 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(); } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configurations/GlobalSettingsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/GlobalSettingsTests.cs similarity index 88% rename from src/Umbraco.Tests.UnitTests/Umbraco.Core/Configurations/GlobalSettingsTests.cs rename to src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/GlobalSettingsTests.cs index 3b0d13c584..3c3de455f5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configurations/GlobalSettingsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/GlobalSettingsTests.cs @@ -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 diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/GlobalSettingsValidatorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/GlobalSettingsValidatorTests.cs index f286dd42b0..ca20129092 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/GlobalSettingsValidatorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/GlobalSettingsValidatorTests.cs @@ -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() diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/HealthChecksSettingsValidatorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/HealthChecksSettingsValidatorTests.cs index 9ae5444134..b645c758dc 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/HealthChecksSettingsValidatorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/HealthChecksSettingsValidatorTests.cs @@ -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() diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configurations/NCronTabParserTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/NCronTabParserTests.cs similarity index 89% rename from src/Umbraco.Tests.UnitTests/Umbraco.Core/Configurations/NCronTabParserTests.cs rename to src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/NCronTabParserTests.cs index 4a38de831d..8ab3d01882 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configurations/NCronTabParserTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/NCronTabParserTests.cs @@ -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 diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/CallContextTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/CallContextTests.cs index dec0ff9a29..82eef0eb71 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/CallContextTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/CallContextTests.cs @@ -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.SetData("test1", null); - CallContext.SetData("test2", null); - return null; - }, o => { }); - } + static CallContextTests() => SafeCallContext.Register( + () => + { + CallContext.SetData("test1", null); + CallContext.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.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.SetData("test3a", "test3a"); - if (_first) + if (s_first) { - _first = false; + s_first = false; } else { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/ObjectExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/ObjectExtensionsTests.cs index f3fa46ef5e..848edddf1c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/ObjectExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/ObjectExtensionsTests.cs @@ -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 {"hello", "world", "awesome"}; - var result = list.TryConvertTo>(); + var list = new List { "hello", "world", "awesome" }; + Attempt> result = list.TryConvertTo>(); 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(); - - //Assert + // Act + IDictionary d = obj.ToDictionary(); + // 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 i = 1; + Attempt result = i.TryConvertTo(); 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(); + Attempt result = i.TryConvertTo(); Assert.That(result.Success, Is.True); } @@ -79,20 +76,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings { var testCases = new Dictionary { - {"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 testCase in testCases) { - var result = testCase.Key.TryConvertTo(); + Attempt result = testCase.Key.TryConvertTo(); 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(); + Attempt result = date.TryConvertTo(); 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(); + Attempt result = string.Empty.TryConvertTo(); 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(); + Attempt result = string.Empty.TryConvertTo(); 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(); + Attempt result = string.Empty.TryConvertTo(); 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(); + Attempt result = new MyTestObject().TryConvertTo(); 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(); + Attempt result = obj.TryConvertTo(); Assert.AreEqual(obj, result.Result); } @@ -164,7 +161,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreThings [Test] public void ConvertToIntegerTest() { - var conv = "100".TryConvertTo(); + Attempt conv = "100".TryConvertTo(); 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(); + Attempt conv = "100".TryConvertTo(); 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(); + Attempt conv = "100".TryConvertTo(); 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(); + Attempt conv = "2016-06-07".TryConvertTo(); 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(); + Attempt conv = "2016-06-07".TryConvertTo(); 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 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"; } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/TryConvertToTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/TryConvertToTests.cs index a0dddd8b5e..7ebbe72ac1 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/TryConvertToTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/TryConvertToTests.cs @@ -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 { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/UdiTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/UdiTests.cs index e8fe9d5415..8703d4d7f4 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/UdiTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/UdiTests.cs @@ -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(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(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(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(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(json, settings); + Udi dudi = JsonConvert.DeserializeObject(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(json, settings); + UdiRange drange = JsonConvert.DeserializeObject(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 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(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 udis) - { - throw new NotImplementedException(); - } + public void Explode(UdiRange range, List 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 differences = null) - { - throw new NotImplementedException(); - } + public bool Compare(IArtifact art1, IArtifact art2, ICollection differences = null) => throw new NotImplementedException(); } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/FrameworkXmlTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/FrameworkXmlTests.cs index 42e3aa7357..e91f47893f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/FrameworkXmlTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/FrameworkXmlTests.cs @@ -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 = @" + private const string Xml1 = @" @@ -27,31 +25,29 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml "; - // 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(""); - 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(""); - 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 } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/NavigableNavigatorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/NavigableNavigatorTests.cs index c5629aca10..d0990114e8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/NavigableNavigatorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/NavigableNavigatorTests.cs @@ -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 = @""; - 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 ]]> "; - 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(); // "poo" - 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 = @""; - 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("poo"); - var docNav = doc.CreateNavigator(); - var docIter = docNav.Select("//item2 [@xx=33]"); + XPathDocument doc = XmlHelper.CreateXPathDocument("poo"); + 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(@" + XPathDocument doc = XmlHelper.CreateXPathDocument(@" dang "); - 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(""); - 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 Microsoft’s 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(@" + XPathDocument doc = XmlHelper.CreateXPathDocument(@" @@ -835,9 +836,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml "); - var docNav = doc.CreateNavigator(); + XPathNavigator docNav = doc.CreateNavigator(); - Assert.AreEqual(@" + Assert.AreEqual( + @" @@ -859,7 +861,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml -".Lf(), docNav.OuterXml.Lf()); +".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(@" + Assert.AreEqual( + @" @@ -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 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 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 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 Content = new Dictionary(); - 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 = "poo"; 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("", "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 { - // - // - // - // - // - // - // - // - // blah - // - // bam - // - // - // - // - // + //// + //// + //// + //// + //// + //// + //// + //// + //// blah + //// + //// bam + //// + //// + //// + //// + //// 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 ", "bam", - "\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 } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/RenamedRootNavigatorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/RenamedRootNavigatorTests.cs index 5afc68955d..2b6b584ca8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/RenamedRootNavigatorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/RenamedRootNavigatorTests.cs @@ -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 "); var nav = doc.CreateNavigator(); var xml = nav.OuterXml; - Assert.AreEqual(EnsureNativeLineEndings(@" + Assert.AreEqual( + EnsureNativeLineEndings(@" "), xml); @@ -35,7 +39,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml "); var nav = doc.CreateNavigator(); var xml = nav.OuterXml; - Assert.AreEqual(EnsureNativeLineEndings(@" + Assert.AreEqual( + EnsureNativeLineEndings(@" "), xml); @@ -51,7 +56,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml "); var nav = new RenamedRootNavigator(doc.CreateNavigator(), "test"); var xml = nav.OuterXml; - Assert.AreEqual(EnsureNativeLineEndings(@" + Assert.AreEqual( + EnsureNativeLineEndings(@" "), xml); @@ -73,7 +79,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.CoreXml "); var nav = new RenamedRootNavigator(doc.CreateNavigator(), "test"); var xml = nav.OuterXml; - Assert.AreEqual(EnsureNativeLineEndings(@" + Assert.AreEqual( + EnsureNativeLineEndings(@" "), xml); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/DelegateExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/DelegateExtensionsTests.cs index a3e36c8ae6..cc4b716944 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/DelegateExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/DelegateExtensionsTests.cs @@ -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.Fail(); - }, 5, TimeSpan.FromMilliseconds(10)); + DelegateExtensions.RetryUntilSuccessOrMaxAttempts( + (currentTry) => + { + totalTries = currentTry; + return Attempt.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.Succeed() : Attempt.Fail(); - }, 5, TimeSpan.FromMilliseconds(10)); + DelegateExtensions.RetryUntilSuccessOrMaxAttempts( + (currentTry) => + { + totalTries = currentTry; + return totalTries == 2 ? Attempt.Succeed() : Attempt.Fail(); + }, + 5, + TimeSpan.FromMilliseconds(10)); Assert.AreEqual(2, totalTries); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/EnumExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/EnumExtensionsTests.cs index d5ea4d2677..bf1e35a5ac 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/EnumExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/EnumExtensionsTests.cs @@ -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 are set (other bits can be set too) - + // The built-in Enum.HasFlag() method determines whether + // all bits from 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 are set (other bits can be set too) - + // The HasFlagAll() extension method determines whether + // all bits from 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 is set - + // The HasFlagAny() extension method determines whether + // at least one bit from is set. if (expected) + { Assert.IsTrue(value.HasFlagAny(test)); + } else + { Assert.IsFalse(value.HasFlagAny(test)); + } } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/EnumerableExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/EnumerableExtensionsTests.cs index 32e039f26a..72a1ce25c6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/EnumerableExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/EnumerableExtensionsTests.cs @@ -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 - { - new TestItem("1.1"), - new TestItem("1.2"), - new TestItem("1.3") - } - }; + Children = new List + { + new TestItem("1.1"), + new TestItem("1.2"), + new TestItem("1.3") + } + }; - var selectRecursive = hierarchy.Children.SelectRecursive(x => x.Children); + IEnumerable 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 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(); Name = name; } + public string Name { get; } + public IEnumerable 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[] 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[] 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> 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> iteratorSource = list.DistinctBy(x => x.Item2); // Assert // First check distinction diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/ClaimsPrincipalExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/ClaimsPrincipalExtensionsTests.cs index ad0f292fae..7b699e7b0c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/ClaimsPrincipalExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/ClaimsPrincipalExtensionsTests.cs @@ -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(), Enumerable.Empty(), "en-US", Guid.NewGuid().ToString(), - Enumerable.Empty(), Enumerable.Empty()); + var backOfficeIdentity = new UmbracoBackOfficeIdentity( + Constants.Security.SuperUserIdAsString, + "test", + "test", + Enumerable.Empty(), + Enumerable.Empty(), + "en-US", + Guid.NewGuid().ToString(), + Enumerable.Empty(), + Enumerable.Empty()); 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( diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UriExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UriExtensionsTests.cs index e832f13671..a072a1a189 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UriExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UriExtensionsTests.cs @@ -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 diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/GuidUtilsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/GuidUtilsTests.cs index 62e0955d78..db16dbeb8b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/GuidUtilsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/GuidUtilsTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; using Umbraco.Core; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/HashCodeCombinerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/HashCodeCombinerTests.cs index ecd2d13e78..e9b43852c3 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/HashCodeCombinerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/HashCodeCombinerTests.cs @@ -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"); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/HashGeneratorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/HashGeneratorTests.cs index 08f5b69cab..a0e75352dd 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/HashGeneratorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/HashGeneratorTests.cs @@ -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()); } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/HexEncoderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/HexEncoderTests.cs index f22c3f2ac1..47d97ffaf8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/HexEncoderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/HexEncoderTests.cs @@ -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); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/IO/AbstractFileSystemTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/IO/AbstractFileSystemTests.cs index 3502c74494..71757c788d 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/IO/AbstractFileSystemTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/IO/AbstractFileSystemTests.cs @@ -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 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(() => - { - _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 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 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 } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/IO/PhysicalFileSystemTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/IO/PhysicalFileSystemTests.cs index 7b98d77f58..5ec7e5873e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/IO/PhysicalFileSystemTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/IO/PhysicalFileSystemTests.cs @@ -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>(), 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); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Manifest/ManifestContentAppTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Manifest/ManifestContentAppTests.cs index 92876f1b98..b3c75adfde 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Manifest/ManifestContentAppTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Manifest/ManifestContentAppTests.cs @@ -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 contentType = Mock.Of(); Mock.Get(contentType).Setup(x => x.Alias).Returns("type1"); - var content = Mock.Of(); + IContent content = Mock.Of(); Mock.Get(content).Setup(x => x.ContentType).Returns(new SimpleContentType(contentType)); - var group1 = Mock.Of(); + IReadOnlyUserGroup group1 = Mock.Of(); Mock.Get(group1).Setup(x => x.Alias).Returns("group1"); - var group2 = Mock.Of(); + IReadOnlyUserGroup group2 = Mock.Of(); Mock.Get(group2).Setup(x => x.Alias).Returns("group2"); // no rule = ok - AssertDefinition(content, true, Array.Empty(), new [] { group1, group2 }); + AssertDefinition(content, true, Array.Empty(), 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("{" + (show.Length == 0 ? "" : " \"show\": [" + string.Join(",", show.Select(x => "\"" + x + "\"")) + "] ") + "}"); + ManifestContentAppDefinition definition = JsonConvert.DeserializeObject("{" + (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); + } } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Manifest/ManifestParserTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Manifest/ManifestParserTests.cs index e1a34e38a3..ccab1885bb 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Manifest/ManifestParserTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Manifest/ManifestParserTests.cs @@ -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()), loggerFactory.CreateLogger(), loggerFactory, _ioHelper, TestHelper.GetHostingEnvironment(), Mock.Of(), Mock.Of(), new JsonNetSerializer(), Mock.Of(), Mock.Of()); } [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(() => _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 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 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 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 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(() => { - 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 config = editor.Config; Assert.AreEqual(2, config.Count); Assert.IsTrue(config.ContainsKey("image")); - var c = config["image"]; + object c = config["image"]; Assert.IsInstanceOf(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(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(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(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); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs index 8593d01946..192daee0bf 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs @@ -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(); - } + protected Item() => _propertyChangedInfo = new Dictionary(); /// - /// Integer Id + /// Gets or sets the integer Id /// [DataMember] public int Id @@ -36,7 +36,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections } /// - /// Guid based Id + /// Gets or sets the Guid based Id /// /// The key is currectly used to store the Unique Id from the /// umbracoNode table, which many of the entities are based on. @@ -66,8 +66,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections public DateTime? DeleteDate { get; set; } /// - /// 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. /// @@ -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; } /// @@ -111,15 +112,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections /// /// Method to call on entity saved/updated /// - internal virtual void UpdatingEntity() - { - UpdateDate = DateTime.Now; - } + internal virtual void UpdatingEntity() => UpdateDate = DateTime.Now; /// /// Tracks the properties that have changed /// - //private readonly IDictionary _propertyChangedInfo = new Dictionary(); private readonly IDictionary _propertyChangedInfo; /// @@ -127,24 +124,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models.Collections /// /// Name of the property to check /// True if Property is dirty, otherwise False - 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 GetDirtyProperties() - { - return _propertyChangedInfo.Keys; - } + public virtual IEnumerable GetDirtyProperties() => _propertyChangedInfo.Keys; /// /// Indicates whether the current entity is dirty. /// /// True if entity is dirty, otherwise False - public virtual bool IsDirty() - { - return _propertyChangedInfo.Any(); - } + public virtual bool IsDirty() => _propertyChangedInfo.Any(); /// /// 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. /// - public virtual void ResetDirtyProperties() - { - _propertyChangedInfo.Clear(); - } + public virtual void ResetDirtyProperties() => _propertyChangedInfo.Clear(); /// /// Disables change tracking. /// - public void DisableChangeTracking() - { - _withChanges = false; - } + public void DisableChangeTracking() => _withChanges = false; /// /// Enables change tracking. /// - public void EnableChangeTracking() - { - _withChanges = true; - } + public void EnableChangeTracking() => _withChanges = true; /// - /// 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. /// 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(); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/OrderItem.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/OrderItem.cs index 60c57dd1e5..91ccc3cac8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/OrderItem.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/OrderItem.cs @@ -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); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/PropertyCollectionTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/PropertyCollectionTests.cs index 6c76cc29a2..643ad1f64e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/PropertyCollectionTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/PropertyCollectionTests.cs @@ -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; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/SimpleOrder.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/SimpleOrder.cs index d8c47f45f4..86022f094b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/SimpleOrder.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/SimpleOrder.cs @@ -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 properties) + public SimpleOrder() + : base() { - Reset(properties); } + public SimpleOrder(IEnumerable 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 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); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentExtensionsTests.cs index eb46a2b919..556e855c83 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentExtensionsTests.cs @@ -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(); - var contentType = ContentTypeBuilder.CreateTextPageContentType(); + IContentTypeService contentTypeService = Mock.Of(); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As().Setup(x => x.Get(It.IsAny())).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(); - var contentType = ContentTypeBuilder.CreateTextPageContentType(); + IContentTypeService contentTypeService = Mock.Of(); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As().Setup(x => x.Get(It.IsAny())).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(); - var contentType = ContentTypeBuilder.CreateTextPageContentType(); + IContentTypeService contentTypeService = Mock.Of(); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As().Setup(x => x.Get(It.IsAny())).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(); - var contentType = ContentTypeBuilder.CreateTextPageContentType(); + IContentTypeService contentTypeService = Mock.Of(); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As().Setup(x => x.Get(It.IsAny())).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(); - var contentType = ContentTypeBuilder.CreateTextPageContentType(); + IContentTypeService contentTypeService = Mock.Of(); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As().Setup(x => x.Get(It.IsAny())).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(); - var contentType = ContentTypeBuilder.CreateTextPageContentType(); + IContentTypeService contentTypeService = Mock.Of(); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As().Setup(x => x.Get(It.IsAny())).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(); - var contentType = ContentTypeBuilder.CreateTextPageContentType(); + IContentTypeService contentTypeService = Mock.Of(); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); Mock.Get(contentTypeService).As().Setup(x => x.Get(It.IsAny())).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! } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentScheduleTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentScheduleTests.cs index 36bf5418b3..bdf1591301 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentScheduleTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentScheduleTests.cs @@ -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(() => 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 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 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 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()); } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTests.cs index 6b226e7e59..d59dafcda0 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTests.cs @@ -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(); + private readonly IContentTypeService _contentTypeService = Mock.Of(); [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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).Returns(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); - var nonGrouped = content.GetNonGroupedProperties(); + IEnumerable 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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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(); + ILogger logger = NullLoggerFactory.Instance.CreateLogger(); 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("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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).Returns(contentType); - //// Arrange - //var contentType = ContentTypeBuilder.CreateTextPageContentType(); - //var simpleContentType = ContentTypeBuilder.CreateSimpleContentType(); - //var content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1); + //// Mock.Get(_contentTypeService).As().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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().Setup(x => x.Get(It.IsAny())).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 })); // Act - var added = simpleContentType.AddContentType(simple2ContentType); - var compositionPropertyGroups = simpleContentType.CompositionPropertyGroups; - var compositionPropertyTypes = simpleContentType.CompositionPropertyTypes; + bool added = simpleContentType.AddContentType(simple2ContentType); + IEnumerable compositionPropertyGroups = simpleContentType.CompositionPropertyGroups; + IEnumerable 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 })); // 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 compositionPropertyGroups = simpleContentType.CompositionPropertyGroups; + IEnumerable 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 { 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 { 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 aliases = textPage.CompositionAliases(); + IEnumerable propertyTypes = textPage.CompositionPropertyTypes; + IEnumerable propertyGroups = textPage.CompositionPropertyGroups; // Assert Assert.That(mixin2.ContentTypeCompositionExists("meta"), Is.True); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTypeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTypeTests.cs index c571a79785..3970fb9f53 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTypeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTypeTests.cs @@ -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(() => 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); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/CultureImpactTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/CultureImpactTests.cs index 753c0e2b4d..f72a28b0f3 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/CultureImpactTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/CultureImpactTests.cs @@ -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(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(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(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); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DeepCloneHelperTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DeepCloneHelperTests.cs index fcad67c221..6dc251d9f8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DeepCloneHelperTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DeepCloneHelperTests.cs @@ -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 MyTest1 { get; set; } + public IEnumerable MyTest1 { get; set; } } public class Test7 : BaseCloneable { public string Name { get; set; } - public List MyTest1 { get; set; } + public List MyTest1 { get; set; } } public class Test8 : BaseCloneable { public string Name { get; set; } - public ICollection MyTest1 { get; set; } + public ICollection MyTest1 { get; set; } } public abstract class BaseCloneable : IDeepCloneable diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DictionaryItemTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DictionaryItemTests.cs index 54a935c891..4994c12f84 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DictionaryItemTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DictionaryItemTests.cs @@ -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(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DictionaryTranslationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DictionaryTranslationTests.cs index 957acf293e..073a168e23 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DictionaryTranslationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DictionaryTranslationTests.cs @@ -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(); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DocumentEntityTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DocumentEntityTests.cs index 1829720aad..ec3ed57bd6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DocumentEntityTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/DocumentEntityTests.cs @@ -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") diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/LanguageTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/LanguageTests.cs index 5b1fc2d56b..5523f57680 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/LanguageTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/LanguageTests.cs @@ -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)); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MacroTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MacroTests.cs index 9d22387cd6..d7964e45b2 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MacroTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MacroTests.cs @@ -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")); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberGroupTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberGroupTests.cs index 47138a5fb4..165a42b225 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberGroupTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberGroupTests.cs @@ -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(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberTests.cs index 58f88affa1..8ca253c224 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberTests.cs @@ -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(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyGroupTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyGroupTests.cs index 08e025a6b1..647684ff2f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyGroupTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyGroupTests.cs @@ -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(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyTests.cs index ce87174d7c..99188759af 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyTests.cs @@ -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(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyTypeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyTypeTests.cs index 6fa061b1d2..cce3f43db0 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyTypeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/PropertyTypeTests.cs @@ -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(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(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(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTests.cs index fa7e540533..66fce7f93f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTests.cs @@ -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(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTypeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTypeTests.cs index 2d5b88d945..d29f89283d 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTypeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTypeTests.cs @@ -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)); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/StylesheetTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/StylesheetTests.cs index f744fee829..a2d9ed18f8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/StylesheetTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/StylesheetTests.cs @@ -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 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 { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/TemplateTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/TemplateTests.cs index d1c731184e..04a49456b6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/TemplateTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/TemplateTests.cs @@ -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(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserExtensionsTests.cs index faf96a6457..426f698969 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserExtensionsTests.cs @@ -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(c => c.Path == contentPath && c.Id == 5); + IContent content = Mock.Of(c => c.Path == contentPath && c.Id == 5); var esmock = new Mock(); esmock @@ -80,7 +81,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Models // 6 // 7 // 8 - var paths = new Dictionary { { 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) + "\"."); + } } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserTests.cs index e4b9f89067..9f0613f9d6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserTests.cs @@ -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(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/VariationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/VariationTests.cs index cab26fd7d2..f92ba1ddeb 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/VariationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/VariationTests.cs @@ -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 } /// /// Asserts the result of /// - /// - /// - /// /// Validate using Exact + Wildcards flags /// Validate using non Exact + no Wildcard flags /// Validate using Exact + no Wildcard flags /// Validate using non Exact + Wildcard flags - 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 /// where expectedResult matches all combinations of Exact + Wildcard /// - /// - /// - /// - /// - 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(() => 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(); - var dataTypeService = Mock.Of(); - var localizedTextService = Mock.Of(); - var localizationService = Mock.Of(); - var shortStringHelper = Mock.Of(); - var jsonSerializer = Mock.Of(); + IIOHelper ioHelper = Mock.Of(); + IDataTypeService dataTypeService = Mock.Of(); + ILocalizedTextService localizedTextService = Mock.Of(); + ILocalizationService localizationService = Mock.Of(); + IShortStringHelper shortStringHelper = Mock.Of(); + IJsonSerializer jsonSerializer = Mock.Of(); 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(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Packaging/PackageExtractionTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Packaging/PackageExtractionTests.cs index 48f26f210c..a5025b6ec5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Packaging/PackageExtractionTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Packaging/PackageExtractionTests.cs @@ -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 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 result = sut.FindMissingFiles(GetTestPackagePath(PackageFileName), new[] { "DoesNotExists.XYZ" }); // Assert Assert.AreEqual(1, result.Count()); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/BlockEditorComponentTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/BlockEditorComponentTests.cs index bc54a7b999..438d2053e8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/BlockEditorComponentTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/BlockEditorComponentTests.cs @@ -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 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 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 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 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; } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/BlockListPropertyValueConverterTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/BlockListPropertyValueConverterTests.cs index eb77ad2e1c..a174a7e511 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/BlockListPropertyValueConverterTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/BlockListPropertyValueConverterTests.cs @@ -1,9 +1,9 @@ -using Moq; -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using Moq; +using NUnit.Framework; 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"; /// /// Setup mocks for IPublishedSnapshotAccessor /// - /// private IPublishedSnapshotAccessor GetPublishedSnapshotAccessor() { - var test1ContentType = Mock.Of(x => + IPublishedContentType2 test1ContentType = Mock.Of(x => x.IsElement == true - && x.Key == ContentKey1 + && x.Key == _contentKey1 && x.Alias == ContentAlias1); - var test2ContentType = Mock.Of(x => + IPublishedContentType2 test2ContentType = Mock.Of(x => x.IsElement == true - && x.Key == ContentKey2 + && x.Key == _contentKey2 && x.Alias == ContentAlias2); - var test3ContentType = Mock.Of(x => + IPublishedContentType2 test3ContentType = Mock.Of(x => x.IsElement == true - && x.Key == SettingKey1 + && x.Key == _settingKey1 && x.Alias == SettingAlias1); - var test4ContentType = Mock.Of(x => + IPublishedContentType2 test4ContentType = Mock.Of(x => x.IsElement == true - && x.Key == SettingKey2 + && x.Key == _settingKey2 && x.Alias == SettingAlias2); var contentCache = new Mock(); - 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(x => x.Content == contentCache.Object); - var publishedSnapshotAccessor = Mock.Of(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(x => x.Content == contentCache.Object); + IPublishedSnapshotAccessor publishedSnapshotAccessor = Mock.Of(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(), @@ -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(() => config)); - var propertyType = Mock.Of(x => + IPublishedPropertyType propertyType = Mock.Of(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(x => x.EditorAlias == Constants.PropertyEditors.Aliases.BlockList))); Assert.IsFalse(editor.IsConverter(Mock.Of(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(() => config)); - var propType = Mock.Of(x => x.DataType == dataType); + IPublishedPropertyType propType = Mock.Of(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(() => config)); - var propType = Mock.Of(x => x.DataType == dataType); + IPublishedPropertyType propType = Mock.Of(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(); + BlockListPropertyValueConverter editor = CreateConverter(); + BlockListConfiguration config = ConfigForMany(); + IPublishedPropertyType propertyType = GetPropertyType(config); + IPublishedElement publishedElement = Mock.Of(); 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(); + BlockListPropertyValueConverter editor = CreateConverter(); + BlockListConfiguration config = ConfigForMany(); + IPublishedPropertyType propertyType = GetPropertyType(config); + IPublishedElement publishedElement = Mock.Of(); - 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(); + BlockListPropertyValueConverter editor = CreateConverter(); + BlockListConfiguration config = ConfigForMany(); + IPublishedPropertyType propertyType = GetPropertyType(config); + IPublishedElement publishedElement = Mock.Of(); - 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(); + BlockListPropertyValueConverter editor = CreateConverter(); + BlockListConfiguration config = ConfigForMany(); + IPublishedPropertyType propertyType = GetPropertyType(config); + IPublishedElement publishedElement = Mock.Of(); - 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(); + IPublishedPropertyType propertyType = GetPropertyType(config); + IPublishedElement publishedElement = Mock.Of(); - 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); - } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/ColorListValidatorTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/ColorListValidatorTest.cs index 98820ccac9..1264e24e58 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/ColorListValidatorTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/ColorListValidatorTest.cs @@ -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(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer())); + IEnumerable result = + validator.Validate( + "hello", + null, + new ColorPickerPropertyEditor( + _loggerFactory, + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + 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(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer())); + IEnumerable result = + validator.Validate( + new JArray("hello", "world"), + null, + new ColorPickerPropertyEditor( + _loggerFactory, + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + 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(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer())); + IEnumerable 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(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer())); Assert.AreEqual(2, result.Count()); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/ConvertersTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/ConvertersTests.cs index f41a950c27..f78a72b42a 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/ConvertersTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/ConvertersTests.cs @@ -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()); register.AddTransient(f => factory); - var cacheMock = new Mock(); var cacheContent = new Dictionary(); cacheMock.Setup(x => x.GetById(It.IsAny())).Returns(id => @@ -62,11 +64,24 @@ namespace Umbraco.Tests.Published var serializer = new ConfigurationEditorJsonSerializer(); var dataTypeServiceMock = new Mock(); - var dataType1 = new DataType(new VoidEditor(NullLoggerFactory.Instance, dataTypeServiceMock.Object, - Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()), + var dataType1 = new DataType( + new VoidEditor( + NullLoggerFactory.Instance, + dataTypeServiceMock.Object, + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer()), serializer) { Id = 1 }; - var dataType2 = new DataType(new VoidEditor("2", NullLoggerFactory.Instance, Mock.Of(), - Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()), + var dataType2 = new DataType( + new VoidEditor( + "2", + NullLoggerFactory.Instance, + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + 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 { { "prop1", "val1" } }, false); - var element2 = new PublishedElement(elementType2, Guid.NewGuid(), - new Dictionary { { "prop2", "1003" } }, false); + var element1 = new PublishedElement( + elementType1, + Guid.NewGuid(), + new Dictionary { { "prop1", "val1" } }, + false); + var element2 = new PublishedElement( + elementType2, + Guid.NewGuid(), + new Dictionary { { "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), + Assert.AreEqual( + typeof(IEnumerable), 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( model2.Value(Mock.Of(), "prop2")); - Assert.AreEqual(1, - ((PublishedSnapshotTestObjects.TestContentModel1[])model2.Value(Mock.Of(), - "prop2")).Length); + Assert.AreEqual( + 1, + ((PublishedSnapshotTestObjects.TestContentModel1[])model2.Value(Mock.Of(), "prop2")).Length); // and get model property Assert.IsInstanceOf>(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(); } - 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(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/DataValueReferenceFactoryCollectionTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/DataValueReferenceFactoryCollectionTests.cs index 3229c3652c..d29ba45531 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/DataValueReferenceFactoryCollectionTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/DataValueReferenceFactoryCollectionTests.cs @@ -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(); + private IDataTypeService DataTypeService { get; } = Mock.Of(); + private IIOHelper IOHelper { get; } = Mock.Of(); - ILocalizedTextService LocalizedTextService { get; } = Mock.Of(); - ILocalizationService LocalizationService { get; } = Mock.Of(); - IShortStringHelper ShortStringHelper { get; } = Mock.Of(); - IJsonSerializer JsonSerializer { get; } = new JsonNetSerializer(); + + private ILocalizedTextService LocalizedTextService { get; } = Mock.Of(); + + private ILocalizationService LocalizationService { get; } = Mock.Of(); + + private IShortStringHelper ShortStringHelper { get; } = Mock.Of(); + + 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 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 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 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 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); + } } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/EnsureUniqueValuesValidatorTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/EnsureUniqueValuesValidatorTest.cs index 2b81620b27..230be138ce 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/EnsureUniqueValuesValidatorTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/EnsureUniqueValuesValidatorTest.cs @@ -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,12 +20,24 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [TestFixture] public class EnsureUniqueValuesValidatorTest { - private ILoggerFactory _loggerFactory = NullLoggerFactory.Instance; + private readonly ILoggerFactory _loggerFactory = NullLoggerFactory.Instance; + [Test] public void Only_Tests_On_JArray() { var validator = new ValueListUniqueValueValidator(); - var result = validator.Validate("hello", null, new ColorPickerPropertyEditor(_loggerFactory, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer())); + IEnumerable result = + validator.Validate( + "hello", + null, + new ColorPickerPropertyEditor( + _loggerFactory, + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer())); Assert.AreEqual(0, result.Count()); } @@ -28,7 +45,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors public void Only_Tests_On_JArray_Of_Item_JObject() { var validator = new ValueListUniqueValueValidator(); - var result = validator.Validate(new JArray("hello", "world"), null, new ColorPickerPropertyEditor(_loggerFactory, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer())); + IEnumerable result = + validator.Validate( + new JArray("hello", "world"), + null, + new ColorPickerPropertyEditor( + _loggerFactory, + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer())); Assert.AreEqual(0, result.Count()); } @@ -36,7 +64,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors public void Allows_Unique_Values() { var validator = new ValueListUniqueValueValidator(); - var result = validator.Validate(new JArray(JObject.FromObject(new { value = "hello" }), JObject.FromObject(new { value = "world" })), null, new ColorPickerPropertyEditor(_loggerFactory, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer())); + IEnumerable result = + validator.Validate( + new JArray( + JObject.FromObject(new { value = "hello" }), + JObject.FromObject(new { value = "world" })), + null, + new ColorPickerPropertyEditor( + _loggerFactory, + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer())); Assert.AreEqual(0, result.Count()); } @@ -44,8 +85,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors public void Does_Not_Allow_Multiple_Values() { var validator = new ValueListUniqueValueValidator(); - var result = validator.Validate(new JArray(JObject.FromObject(new { value = "hello" }), JObject.FromObject(new { value = "hello" })), - null, new ColorPickerPropertyEditor(_loggerFactory, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer())); + IEnumerable result = + validator.Validate( + new JArray( + JObject.FromObject(new { value = "hello" }), + JObject.FromObject(new { value = "hello" })), + null, + new ColorPickerPropertyEditor( + _loggerFactory, + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer())); Assert.AreEqual(1, result.Count()); } @@ -53,12 +106,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors public void Validates_Multiple_Duplicate_Values() { var validator = new ValueListUniqueValueValidator(); - var result = validator.Validate(new JArray( - JObject.FromObject(new { value = "hello" }), - JObject.FromObject(new { value = "hello" }), - JObject.FromObject(new { value = "world" }), - JObject.FromObject(new { value = "world" })), - null, new ColorPickerPropertyEditor(_loggerFactory, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer())); + IEnumerable result = + validator.Validate( + new JArray( + JObject.FromObject(new { value = "hello" }), + JObject.FromObject(new { value = "hello" }), + JObject.FromObject(new { value = "world" }), + JObject.FromObject(new { value = "world" })), + null, + new ColorPickerPropertyEditor( + _loggerFactory, + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer())); Assert.AreEqual(2, result.Count()); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/MultiValuePropertyEditorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/MultiValuePropertyEditorTests.cs index 2952ac032d..0b069d9662 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/MultiValuePropertyEditorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/MultiValuePropertyEditorTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Globalization; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -45,14 +48,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors var dataTypeServiceMock = new Mock(); dataTypeServiceMock - .Setup(x=>x.GetDataType(It.IsAny())) + .Setup(x => x.GetDataType(It.IsAny())) .Returns(dataType); var prop = new Property(1, new PropertyType(Mock.Of(), dataType)); prop.SetValue("Value 1,Value 2,Value 3"); - var valueEditor = dataType.Editor.GetValueEditor(); - ((DataValueEditor) valueEditor).Configuration = dataType.Configuration; + IDataValueEditor valueEditor = dataType.Editor.GetValueEditor(); + ((DataValueEditor)valueEditor).Configuration = dataType.Configuration; var result = valueEditor.ConvertDbToString(prop.PropertyType, prop.GetValue(), dataTypeServiceMock.Object); Assert.AreEqual("Value 1,Value 2,Value 3", result); @@ -77,9 +80,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors }; var dataTypeServiceMock = new Mock(); - dataTypeServiceMock - .Setup(x=>x.GetDataType(It.IsAny())) - .Returns(dataType); + dataTypeServiceMock + .Setup(x => x.GetDataType(It.IsAny())) + .Returns(dataType); var prop = new Property(1, new PropertyType(Mock.Of(), dataType)); prop.SetValue("Value 2"); @@ -96,17 +99,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors // (that should be fixed with proper injection) var textService = new Mock(); textService.Setup(x => x.Localize(It.IsAny(), It.IsAny(), It.IsAny>())).Returns("blah"); - //var appContext = new ApplicationContext( - // new DatabaseContext(TestObjects.GetIDatabaseFactoryMock(), logger, Mock.Of(), Mock.Of()), - // new ServiceContext( - // localizedTextService: textService.Object - // ), - // Mock.Of(), - // new ProfilingLogger(logger, Mock.Of())) - //{ - // //IsReady = true - //}; - //Current.ApplicationContext = appContext; + + //// var appContext = new ApplicationContext( + //// new DatabaseContext(TestObjects.GetIDatabaseFactoryMock(), logger, Mock.Of(), Mock.Of()), + //// new ServiceContext( + //// localizedTextService: textService.Object + //// ), + //// Mock.Of(), + //// new ProfilingLogger(logger, Mock.Of())) + //// { + //// //IsReady = true + //// }; + //// Current.ApplicationContext = appContext; var configuration = new ValueListConfiguration { @@ -120,7 +124,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors var editor = new ValueListConfigurationEditor(Mock.Of(), Mock.Of()); - var result = editor.ToConfigurationEditor(configuration); + Dictionary result = editor.ToConfigurationEditor(configuration); // 'result' is meant to be serialized, is built with anonymous objects // so we cannot really test what's in it - but by serializing it diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/NestedContentPropertyComponentTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/NestedContentPropertyComponentTests.cs index 930f1b623f..022e19c18e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/NestedContentPropertyComponentTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/NestedContentPropertyComponentTests.cs @@ -1,15 +1,13 @@ -using Newtonsoft.Json; -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Newtonsoft.Json; +using NUnit.Framework; using Umbraco.Web.Compose; namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors { - [TestFixture] public class NestedContentPropertyComponentTests { @@ -24,9 +22,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void No_Nesting() { - var guids = new[] { Guid.NewGuid(), Guid.NewGuid() }; + Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; - Func guidFactory = () => guids[guidCounter++]; + Guid GuidFactory() => guids[guidCounter++]; var json = @"[ {""key"":""04a6dba8-813c-4144-8aca-86a3f24ebf08"",""name"":""Item 1"",""ncContentTypeAlias"":""nested"",""text"":""woot""}, @@ -37,7 +35,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors .Replace("d8e214d8-c5a5-4b45-9b51-4050dd47f5fa", guids[1].ToString()); var component = new NestedContentPropertyComponent(); - var result = component.CreateNestedContentKeys(json, false, guidFactory); + var result = component.CreateNestedContentKeys(json, false, GuidFactory); Assert.AreEqual(JsonConvert.DeserializeObject(expected).ToString(), JsonConvert.DeserializeObject(result).ToString()); } @@ -45,9 +43,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void One_Level_Nesting_Unescaped() { - var guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; + Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; - Func guidFactory = () => guids[guidCounter++]; + Guid GuidFactory() => guids[guidCounter++]; var json = @"[{ ""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"", @@ -81,7 +79,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors .Replace("fbde4288-8382-4e13-8933-ed9c160de050", guids[3].ToString()); var component = new NestedContentPropertyComponent(); - var result = component.CreateNestedContentKeys(json, false, guidFactory); + var result = component.CreateNestedContentKeys(json, false, GuidFactory); Assert.AreEqual(JsonConvert.DeserializeObject(expected).ToString(), JsonConvert.DeserializeObject(result).ToString()); } @@ -89,9 +87,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void One_Level_Nesting_Escaped() { - var guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; + Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; - Func guidFactory = () => guids[guidCounter++]; + Guid GuidFactory() => guids[guidCounter++]; // 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. @@ -129,7 +127,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors .Replace("fbde4288-8382-4e13-8933-ed9c160de050", guids[3].ToString()); var component = new NestedContentPropertyComponent(); - var result = component.CreateNestedContentKeys(json, false, guidFactory); + var result = component.CreateNestedContentKeys(json, false, GuidFactory); Assert.AreEqual(JsonConvert.DeserializeObject(expected).ToString(), JsonConvert.DeserializeObject(result).ToString()); } @@ -137,9 +135,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void Nested_In_Complex_Editor_Escaped() { - var guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; + Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; - Func guidFactory = () => guids[guidCounter++]; + Guid GuidFactory() => guids[guidCounter++]; // 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. @@ -212,7 +210,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors }] }"; - var json = @"[{ ""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"", ""name"": ""Item 1"", @@ -234,18 +231,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors .Replace("fbde4288-8382-4e13-8933-ed9c160de050", guids[3].ToString()); var component = new NestedContentPropertyComponent(); - var result = component.CreateNestedContentKeys(json, false, guidFactory); + var result = component.CreateNestedContentKeys(json, false, GuidFactory); Assert.AreEqual(JsonConvert.DeserializeObject(expected).ToString(), JsonConvert.DeserializeObject(result).ToString()); } - [Test] public void No_Nesting_Generates_Keys_For_Missing_Items() { - var guids = new[] { Guid.NewGuid() }; + Guid[] guids = new[] { Guid.NewGuid() }; var guidCounter = 0; - Func guidFactory = () => guids[guidCounter++]; + Guid GuidFactory() => guids[guidCounter++]; var json = @"[ {""key"":""04a6dba8-813c-4144-8aca-86a3f24ebf08"",""name"":""Item 1 my key wont change"",""ncContentTypeAlias"":""nested"",""text"":""woot""}, @@ -253,7 +249,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors ]"; var component = new NestedContentPropertyComponent(); - var result = component.CreateNestedContentKeys(json, true, guidFactory); + var result = component.CreateNestedContentKeys(json, true, GuidFactory); // Ensure the new GUID is put in a key into the JSON Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains(guids[0].ToString())); @@ -265,9 +261,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void One_Level_Nesting_Escaped_Generates_Keys_For_Missing_Items() { - var guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; + Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; - Func guidFactory = () => guids[guidCounter++]; + Guid GuidFactory() => guids[guidCounter++]; // 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. @@ -296,7 +292,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors ]"; var component = new NestedContentPropertyComponent(); - var result = component.CreateNestedContentKeys(json, true, guidFactory); + var result = component.CreateNestedContentKeys(json, true, GuidFactory); // Ensure the new GUID is put in a key into the JSON for each item Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains(guids[0].ToString())); @@ -307,9 +303,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void Nested_In_Complex_Editor_Escaped_Generates_Keys_For_Missing_Items() { - var guids = new[] { Guid.NewGuid(), Guid.NewGuid() }; + Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; - Func guidFactory = () => guids[guidCounter++]; + Guid GuidFactory() => guids[guidCounter++]; // 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. @@ -381,7 +377,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors }] }"; - var json = @"[{ ""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"", ""name"": ""Item 1"", @@ -396,7 +391,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors ]"; var component = new NestedContentPropertyComponent(); - var result = component.CreateNestedContentKeys(json, true, guidFactory); + var result = component.CreateNestedContentKeys(json, true, GuidFactory); // Ensure the new GUID is put in a key into the JSON for each item Assert.IsTrue(JsonConvert.DeserializeObject(result).ToString().Contains(guids[0].ToString())); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueConverterTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueConverterTests.cs index be72eff1e7..94e68af881 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueConverterTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueConverterTests.cs @@ -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; @@ -9,8 +12,6 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.PropertyEditors.ValueConverters; using Umbraco.Core.Serialization; using Umbraco.Core.Strings; -using Umbraco.Tests.TestHelpers; -using Umbraco.Web.PropertyEditors; using Umbraco.Web.PropertyEditors.ValueConverters; namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors @@ -21,15 +22,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors // see notes in the converter // only ONE date format is expected here - //[TestCase("2012-11-10", true)] - //[TestCase("2012/11/10", true)] - //[TestCase("10/11/2012", true)] - //[TestCase("11/10/2012", false)] - //[TestCase("Sat 10, Nov 2012", true)] - //[TestCase("Saturday 10, Nov 2012", true)] - //[TestCase("Sat 10, November 2012", true)] - //[TestCase("Saturday 10, November 2012", true)] - //[TestCase("2012-11-10 13:14:15", true)] + // [TestCase("2012-11-10", true)] + // [TestCase("2012/11/10", true)] + // [TestCase("10/11/2012", true)] + // [TestCase("11/10/2012", false)] + // [TestCase("Sat 10, Nov 2012", true)] + // [TestCase("Saturday 10, Nov 2012", true)] + // [TestCase("Sat 10, November 2012", true)] + // [TestCase("Saturday 10, November 2012", true)] + // [TestCase("2012-11-10 13:14:15", true)] [TestCase("2012-11-10 13:14:15", true)] [TestCase("2012-11-10T13:14:15", true)] [TestCase("", false)] @@ -40,9 +41,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors var result = converter.ConvertSourceToIntermediate(null, null, date, false); // does not use type for conversion if (expected) - Assert.AreEqual(dateTime.Date, ((DateTime) result).Date); + { + Assert.AreEqual(dateTime.Date, ((DateTime)result).Date); + } else + { Assert.AreNotEqual(dateTime.Date, ((DateTime)result).Date); + } } [TestCase("TRUE", true)] @@ -96,10 +101,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors }))); var publishedPropType = new PublishedPropertyType( - new PublishedContentType(Guid.NewGuid(),1234, "test", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing), + new PublishedContentType(Guid.NewGuid(), 1234, "test", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing), new PropertyType(Mock.Of(), "test", ValueStorageType.Nvarchar) { DataTypeId = 123 }, new PropertyValueConverterCollection(Enumerable.Empty()), - Mock.Of(), mockPublishedContentTypeFactory.Object); + Mock.Of(), + mockPublishedContentTypeFactory.Object); var converter = new FlexibleDropdownPropertyValueConverter(); var inter = converter.ConvertSourceToIntermediate(null, publishedPropType, value, false); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueEditorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueEditorTests.cs index 4fe391d1e9..a351439c90 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueEditorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueEditorTests.cs @@ -1,10 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Moq; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Composing; -using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Strings; @@ -24,23 +24,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors var prop = new Property(1, new PropertyType(Mock.Of(), "test", ValueStorageType.Nvarchar)); prop.SetValue(value); - var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.String); + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.String); - var result = valueEditor.ToEditor(prop); + object result = valueEditor.ToEditor(prop); Assert.AreEqual(isOk, !(result is string)); - } [TestCase("STRING", "hello", "hello")] [TestCase("TEXT", "hello", "hello")] [TestCase("INT", "123", 123)] - [TestCase("INT", "", null)] //test empty string for int - [TestCase("DATETIME", "", null)] //test empty string for date + [TestCase("INT", "", null)] // test empty string for int + [TestCase("DATETIME", "", null)] // test empty string for date public void Value_Editor_Can_Convert_To_Clr_Type(string valueType, string val, object expected) { - var valueEditor = MockedValueEditors.CreateDataValueEditor(valueType); + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(valueType); - var result = valueEditor.TryConvertValueToCrlType(val); + Attempt result = valueEditor.TryConvertValueToCrlType(val); Assert.IsTrue(result.Success); Assert.AreEqual(expected, result.Result); } @@ -50,9 +49,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void Value_Editor_Can_Convert_To_Decimal_Clr_Type() { - var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); - var result = valueEditor.TryConvertValueToCrlType("12.34"); + Attempt result = valueEditor.TryConvertValueToCrlType("12.34"); Assert.IsTrue(result.Success); Assert.AreEqual(12.34M, result.Result); } @@ -60,9 +59,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void Value_Editor_Can_Convert_To_Decimal_Clr_Type_With_Other_Separator() { - var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); - var result = valueEditor.TryConvertValueToCrlType("12,34"); + Attempt result = valueEditor.TryConvertValueToCrlType("12,34"); Assert.IsTrue(result.Success); Assert.AreEqual(12.34M, result.Result); } @@ -70,9 +69,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void Value_Editor_Can_Convert_To_Decimal_Clr_Type_With_Empty_String() { - var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); - var result = valueEditor.TryConvertValueToCrlType(string.Empty); + Attempt result = valueEditor.TryConvertValueToCrlType(string.Empty); Assert.IsTrue(result.Success); Assert.IsNull(result.Result); } @@ -80,9 +79,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [Test] public void Value_Editor_Can_Convert_To_Date_Clr_Type() { - var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Date); + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Date); - var result = valueEditor.TryConvertValueToCrlType("2010-02-05"); + Attempt result = valueEditor.TryConvertValueToCrlType("2010-02-05"); Assert.IsTrue(result.Success); Assert.AreEqual(new DateTime(2010, 2, 5), result.Result); } @@ -90,54 +89,54 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.PropertyEditors [TestCase(ValueTypes.String, "hello", "hello")] [TestCase(ValueTypes.Text, "hello", "hello")] [TestCase(ValueTypes.Integer, 123, "123")] - [TestCase(ValueTypes.Integer, "", "")] //test empty string for int - [TestCase(ValueTypes.DateTime, "", "")] //test empty string for date + [TestCase(ValueTypes.Integer, "", "")] // test empty string for int + [TestCase(ValueTypes.DateTime, "", "")] // test empty string for date public void Value_Editor_Can_Serialize_Value(string valueType, object val, string expected) { var prop = new Property(1, new PropertyType(Mock.Of(), "test", ValueStorageType.Nvarchar)); prop.SetValue(val); - var valueEditor = MockedValueEditors.CreateDataValueEditor(valueType); + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(valueType); - var result = valueEditor.ToEditor(prop); + object result = valueEditor.ToEditor(prop); Assert.AreEqual(expected, result); } [Test] public void Value_Editor_Can_Serialize_Decimal_Value() { - var value = 12.34M; - var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); + decimal value = 12.34M; + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); var prop = new Property(1, new PropertyType(Mock.Of(), "test", ValueStorageType.Decimal)); prop.SetValue(value); - var result = valueEditor.ToEditor(prop); + object result = valueEditor.ToEditor(prop); Assert.AreEqual("12.34", result); } [Test] public void Value_Editor_Can_Serialize_Decimal_Value_With_Empty_String() { - var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Decimal); var prop = new Property(1, new PropertyType(Mock.Of(), "test", ValueStorageType.Decimal)); prop.SetValue(string.Empty); - var result = valueEditor.ToEditor(prop); + object result = valueEditor.ToEditor(prop); Assert.AreEqual(string.Empty, result); } [Test] public void Value_Editor_Can_Serialize_Date_Value() { - var now = DateTime.Now; - var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Date); + DateTime now = DateTime.Now; + DataValueEditor valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Date); var prop = new Property(1, new PropertyType(Mock.Of(), "test", ValueStorageType.Date)); prop.SetValue(now); - var result = valueEditor.ToEditor(prop); + object result = valueEditor.ToEditor(prop); Assert.AreEqual(now.ToIsoString(), result); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/ConvertersTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/ConvertersTests.cs index 13c4ae071c..352a1f45cd 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/ConvertersTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/ConvertersTests.cs @@ -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; @@ -19,8 +22,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published [TestFixture] public class ConvertersTests { - #region SimpleConverter1 - [Test] public void SimpleConverter1Test() { @@ -31,8 +32,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published var serializer = new ConfigurationEditorJsonSerializer(); var dataTypeServiceMock = new Mock(); - var dataType = new DataType(new VoidEditor(Mock.Of(), dataTypeServiceMock.Object, - Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()), serializer) + var dataType = new DataType( + new VoidEditor( + Mock.Of(), + dataTypeServiceMock.Object, + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer()), serializer) { Id = 1 }; dataTypeServiceMock.Setup(x => x.GetAll()).Returns(dataType.Yield); @@ -43,7 +50,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published yield return contentTypeFactory.CreatePropertyType(contentType, "prop1", 1); } - var elementType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "element1", CreatePropertyTypes); + IPublishedContentType elementType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "element1", CreatePropertyTypes); var element1 = new PublishedElement(elementType1, Guid.NewGuid(), new Dictionary { { "prop1", "1234" } }, false); @@ -92,10 +99,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published => ((int)inter).ToString(); } - #endregion - - #region SimpleConverter2 - [Test] public void SimpleConverter2Test() { @@ -106,7 +109,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published publishedSnapshotMock.Setup(x => x.Content).Returns(cacheMock.Object); var publishedSnapshotAccessorMock = new Mock(); publishedSnapshotAccessorMock.Setup(x => x.PublishedSnapshot).Returns(publishedSnapshotMock.Object); - var publishedSnapshotAccessor = publishedSnapshotAccessorMock.Object; + IPublishedSnapshotAccessor publishedSnapshotAccessor = publishedSnapshotAccessorMock.Object; var converters = new PropertyValueConverterCollection(new IPropertyValueConverter[] { @@ -115,8 +118,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published var serializer = new ConfigurationEditorJsonSerializer(); var dataTypeServiceMock = new Mock(); - var dataType = new DataType(new VoidEditor(Mock.Of(), dataTypeServiceMock.Object, - Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()), serializer) + var dataType = new DataType( + new VoidEditor( + Mock.Of(), + dataTypeServiceMock.Object, + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer()), serializer) { Id = 1 }; dataTypeServiceMock.Setup(x => x.GetAll()).Returns(dataType.Yield); @@ -127,11 +136,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published yield return contentTypeFactory.CreatePropertyType(contentType, "prop1", 1); } - var elementType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "element1", CreatePropertyTypes); + IPublishedContentType elementType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "element1", CreatePropertyTypes); var element1 = new PublishedElement(elementType1, Guid.NewGuid(), new Dictionary { { "prop1", "1234" } }, false); - var cntType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1001, "cnt1", t => Enumerable.Empty()); + IPublishedContentType cntType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1001, "cnt1", t => Enumerable.Empty()); var cnt1 = new SolidPublishedContent(cntType1) { Id = 1234 }; cacheContent[cnt1.Id] = cnt1; @@ -156,10 +165,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published => propertyType.EditorAlias.InvariantEquals("Umbraco.Void"); public Type GetPropertyValueType(IPublishedPropertyType propertyType) - // the first version would be the "generic" version, but say we want to be more precise + + // The first version would be the "generic" version, but say we want to be more precise // and return: whatever Clr type is generated for content type with alias "cnt1" -- which // we cannot really typeof() at the moment because it has not been generated, hence ModelType. - // => typeof (IPublishedContent); + // => typeof(IPublishedContent); => ModelType.For("cnt1"); public PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType) @@ -174,7 +184,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published public object ConvertIntermediateToXPath(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview) => ((int)inter).ToString(); } - - #endregion } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/ModelTypeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/ModelTypeTests.cs index 9b4f377247..456cfeb170 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/ModelTypeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/ModelTypeTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using NUnit.Framework; @@ -27,7 +30,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published [Test] public void TypeToStringTests() { - var type = typeof(int); + Type type = typeof(int); Assert.AreEqual("System.Int32", type.ToString()); Assert.AreEqual("System.Int32[]", type.MakeArrayType().ToString()); Assert.AreEqual("System.Collections.Generic.IEnumerable`1[System.Int32[]]", typeof(IEnumerable<>).MakeGenericType(type.MakeArrayType()).ToString()); @@ -36,10 +39,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published [Test] public void TypeFullNameTests() { - var type = typeof(int); + Type type = typeof(int); Assert.AreEqual("System.Int32", type.FullName); Assert.AreEqual("System.Int32[]", type.MakeArrayType().FullName); - // note the inner assembly qualified name + + // Note the inner assembly qualified name Assert.AreEqual("System.Collections.Generic.IEnumerable`1[[System.Int32[], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", typeof(IEnumerable<>).MakeGenericType(type.MakeArrayType()).FullName); } @@ -48,17 +52,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published { var map = new Dictionary { - { "alias1", typeof (PublishedSnapshotTestObjects.TestElementModel1) }, - { "alias2", typeof (PublishedSnapshotTestObjects.TestElementModel2) }, + { "alias1", typeof(PublishedSnapshotTestObjects.TestElementModel1) }, + { "alias2", typeof(PublishedSnapshotTestObjects.TestElementModel2) }, }; - Assert.AreEqual("Umbraco.Tests.Published.PublishedSnapshotTestObjects+TestElementModel1", + Assert.AreEqual( + "Umbraco.Tests.Published.PublishedSnapshotTestObjects+TestElementModel1", ModelType.Map(ModelType.For("alias1"), map).ToString()); - Assert.AreEqual("Umbraco.Tests.Published.PublishedSnapshotTestObjects+TestElementModel1[]", + Assert.AreEqual( + "Umbraco.Tests.Published.PublishedSnapshotTestObjects+TestElementModel1[]", ModelType.Map(ModelType.For("alias1").MakeArrayType(), map).ToString()); - Assert.AreEqual("System.Collections.Generic.IEnumerable`1[Umbraco.Tests.Published.PublishedSnapshotTestObjects+TestElementModel1]", + Assert.AreEqual( + "System.Collections.Generic.IEnumerable`1[Umbraco.Tests.Published.PublishedSnapshotTestObjects+TestElementModel1]", ModelType.Map(typeof(IEnumerable<>).MakeGenericType(ModelType.For("alias1")), map).ToString()); - Assert.AreEqual("System.Collections.Generic.IEnumerable`1[Umbraco.Tests.Published.PublishedSnapshotTestObjects+TestElementModel1[]]", + Assert.AreEqual( + "System.Collections.Generic.IEnumerable`1[Umbraco.Tests.Published.PublishedSnapshotTestObjects+TestElementModel1[]]", ModelType.Map(typeof(IEnumerable<>).MakeGenericType(ModelType.For("alias1").MakeArrayType()), map).ToString()); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/NestedContentTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/NestedContentTests.cs index 7493d59d72..102dd6388e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/NestedContentTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/NestedContentTests.cs @@ -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; @@ -27,14 +30,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published { private (IPublishedContentType, IPublishedContentType) CreateContentTypes() { - var logger = Mock.Of>(); - var loggerFactory = NullLoggerFactory.Instance; - var profiler = Mock.Of(); + ILogger logger = Mock.Of>(); + NullLoggerFactory loggerFactory = NullLoggerFactory.Instance; + IProfiler profiler = Mock.Of(); var proflog = new ProfilingLogger(logger, profiler); - var localizationService = Mock.Of(); + ILocalizationService localizationService = Mock.Of(); PropertyEditorCollection editors = null; - var editor = new NestedContentPropertyEditor(loggerFactory, new Lazy(() => editors), Mock.Of(),localizationService, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()); + var editor = new NestedContentPropertyEditor(loggerFactory, new Lazy(() => editors), Mock.Of(), localizationService, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()); editors = new PropertyEditorCollection(new DataEditorCollection(new DataEditor[] { editor })); var serializer = new ConfigurationEditorJsonSerializer(); @@ -74,7 +77,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published // mocked dataservice returns nested content preValues var dataTypeServiceMock = new Mock(); - dataTypeServiceMock.Setup(x => x.GetAll()).Returns(new []{dataType1, dataType2, dataType3}); + dataTypeServiceMock.Setup(x => x.GetAll()).Returns(new[] { dataType1, dataType2, dataType3 }); var publishedModelFactory = new Mock(); @@ -93,7 +96,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published .Returns((IPublishedElement element) => { if (element.ContentType.Alias.InvariantEquals("contentN1")) + { return new TestElementModel(element); + } + return element; }); @@ -101,11 +107,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published publishedModelFactory .Setup(x => x.CreateModelList(It.IsAny())) .Returns((string alias) => - { - return alias == "contentN1" + alias == "contentN1" ? (IList)new List() - : (IList)new List(); - }); + : (IList)new List()); var contentCache = new Mock(); var publishedSnapshot = new Mock(); @@ -145,16 +149,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published yield return factory.CreatePropertyType(contentType, "propertyN1", 3); } - var contentType1 = factory.CreateContentType(Guid.NewGuid(), 1, "content1", CreatePropertyTypes1); - var contentType2 = factory.CreateContentType(Guid.NewGuid(), 2, "content2", CreatePropertyTypes2); - var contentTypeN1 = factory.CreateContentType(Guid.NewGuid(), 2, "contentN1", CreatePropertyTypesN1, isElement: true); + IPublishedContentType contentType1 = factory.CreateContentType(Guid.NewGuid(), 1, "content1", CreatePropertyTypes1); + IPublishedContentType contentType2 = factory.CreateContentType(Guid.NewGuid(), 2, "content2", CreatePropertyTypes2); + IPublishedContentType contentTypeN1 = factory.CreateContentType(Guid.NewGuid(), 2, "contentN1", CreatePropertyTypesN1, isElement: true); // mocked content cache returns content types contentCache .Setup(x => x.GetContentType(It.IsAny())) .Returns((string alias) => { - if (alias.InvariantEquals("contentN1")) return contentTypeN1; + if (alias.InvariantEquals("contentN1")) + { + return contentTypeN1; + } + return null; }); @@ -164,7 +172,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published [Test] public void SingleNestedTest() { - (var contentType1, _) = CreateContentTypes(); + (IPublishedContentType contentType1, _) = CreateContentTypes(); // nested single converter returns the proper value clr type TestModel, and cache level Assert.AreEqual(typeof(TestElementModel), contentType1.GetPropertyType("property1").ClrType); @@ -177,12 +185,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published Key = key, Properties = new[] { - new TestPublishedProperty(contentType1.GetPropertyType("property1"), $@"[ + new TestPublishedProperty( + contentType1.GetPropertyType("property1"), $@"[ {{ ""key"": ""{keyA}"", ""propertyN1"": ""foo"", ""ncContentTypeAlias"": ""contentN1"" }} ]") } }; - var value = content.Value(Mock.Of(),"property1"); + var value = content.Value(Mock.Of(), "property1"); // nested single converter returns proper TestModel value Assert.IsInstanceOf(value); @@ -194,7 +203,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published [Test] public void ManyNestedTest() { - (_, var contentType2) = CreateContentTypes(); + (_, IPublishedContentType contentType2) = CreateContentTypes(); // nested many converter returns the proper value clr type IEnumerable, and cache level Assert.AreEqual(typeof(IEnumerable), contentType2.GetPropertyType("property2").ClrType); @@ -214,7 +223,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published ]") } }; - var value = content.Value(Mock.Of(), ("property2")); + var value = content.Value(Mock.Of(), "property2"); // nested many converter returns proper IEnumerable value Assert.IsInstanceOf>(value); @@ -230,12 +239,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published { public TestElementModel(IPublishedElement content) : base(content) - { } + { + } - public string PropValue => this.Value(Mock.Of(),"propertyN1"); + public string PropValue => this.Value(Mock.Of(), "propertyN1"); } - class TestPublishedProperty : PublishedPropertyBase + public class TestPublishedProperty : PublishedPropertyBase { private readonly bool _preview; private readonly object _sourceValue; @@ -260,14 +270,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published private object InterValue => PropertyType.ConvertSourceToInter(null, _sourceValue, false); - internal void SetOwner(IPublishedElement owner) - { - _owner = owner; - } + internal void SetOwner(IPublishedElement owner) => _owner = owner; public override bool HasValue(string culture = null, string segment = null) => _hasValue; + public override object GetSourceValue(string culture = null, string segment = null) => _sourceValue; + public override object GetValue(string culture = null, string segment = null) => PropertyType.ConvertInterToObject(_owner, ReferenceCacheLevel, InterValue, _preview); + public override object GetXPathValue(string culture = null, string segment = null) => throw new InvalidOperationException("This method won't be implemented."); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PropertyCacheLevelTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PropertyCacheLevelTests.cs index 163020b6f6..d020fb01d5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PropertyCacheLevelTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PropertyCacheLevelTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -34,12 +37,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published var configurationEditorJsonSerializer = new ConfigurationEditorJsonSerializer(); var jsonSerializer = new JsonNetSerializer(); var dataTypeServiceMock = new Mock(); - var dataType = new DataType(new VoidEditor(NullLoggerFactory.Instance, dataTypeServiceMock.Object, - Mock.Of(), Mock.Of(), Mock.Of(), jsonSerializer), configurationEditorJsonSerializer) + var dataType = new DataType( + new VoidEditor( + NullLoggerFactory.Instance, + dataTypeServiceMock.Object, + Mock.Of(), + Mock.Of(), + Mock.Of(), + jsonSerializer), configurationEditorJsonSerializer) { Id = 1 }; dataTypeServiceMock.Setup(x => x.GetAll()).Returns(dataType.Yield); - var publishedContentTypeFactory = new PublishedContentTypeFactory(Mock.Of(), converters, dataTypeServiceMock.Object); IEnumerable CreatePropertyTypes(IPublishedContentType contentType) @@ -47,7 +55,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published yield return publishedContentTypeFactory.CreatePropertyType(contentType, "prop1", dataType.Id); } - var setType1 = publishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "set1", CreatePropertyTypes); + IPublishedContentType setType1 = publishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "set1", CreatePropertyTypes); // PublishedElementPropertyBase.GetCacheLevels: // @@ -61,7 +69,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published // anything else is not > None, use Content // // for standalone elements, it's only None or Content - var set1 = new PublishedElement(setType1, Guid.NewGuid(), new Dictionary { { "prop1", "1234" } }, false); Assert.AreEqual(1234, set1.Value(Mock.Of(), "prop1")); @@ -70,7 +77,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published // source is always converted once and cached per content // inter conversion depends on the specified cache level - Assert.AreEqual(1234, set1.Value(Mock.Of(), "prop1")); Assert.AreEqual(1, converter.SourceConverts); Assert.AreEqual(interConverts, converter.InterConverts); @@ -108,8 +114,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published [TestCase(PropertyCacheLevel.Snapshot, PropertyCacheLevel.Elements, 1, 0, 0, 0, 0)] [TestCase(PropertyCacheLevel.Snapshot, PropertyCacheLevel.Snapshot, 1, 0, 0, 0, 0)] - public void CachePublishedSnapshotTest(PropertyCacheLevel referenceCacheLevel, PropertyCacheLevel converterCacheLevel, int interConverts, - int elementsCount1, int snapshotCount1, int elementsCount2, int snapshotCount2) + public void CachePublishedSnapshotTest( + PropertyCacheLevel referenceCacheLevel, + PropertyCacheLevel converterCacheLevel, + int interConverts, + int elementsCount1, + int snapshotCount1, + int elementsCount2, + int snapshotCount2) { var converter = new CacheConverter1(converterCacheLevel); @@ -119,8 +131,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published }); var dataTypeServiceMock = new Mock(); - var dataType = new DataType(new VoidEditor(NullLoggerFactory.Instance, dataTypeServiceMock.Object, - Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()), new ConfigurationEditorJsonSerializer()) + var dataType = new DataType( + new VoidEditor( + NullLoggerFactory.Instance, + dataTypeServiceMock.Object, + Mock.Of(), + Mock.Of(), + Mock.Of(), + new JsonNetSerializer()), new ConfigurationEditorJsonSerializer()) { Id = 1 }; dataTypeServiceMock.Setup(x => x.GetAll()).Returns(dataType.Yield); @@ -131,7 +149,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published yield return publishedContentTypeFactory.CreatePropertyType(contentType, "prop1", 1); } - var setType1 = publishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "set1", CreatePropertyTypes); + IPublishedContentType setType1 = publishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "set1", CreatePropertyTypes); var elementsCache = new FastDictionaryAppCache(); var snapshotCache = new FastDictionaryAppCache(); @@ -146,7 +164,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published // pretend we're creating this set as a value for a property // referenceCacheLevel is the cache level for this fictious property // converterCacheLevel is the cache level specified by the converter - var set1 = new PublishedElement(setType1, Guid.NewGuid(), new Dictionary { { "prop1", "1234" } }, false, referenceCacheLevel, publishedSnapshotAccessor.Object); Assert.AreEqual(1234, set1.Value(Mock.Of(), "prop1")); @@ -163,7 +180,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published Assert.AreEqual(elementsCount2, elementsCache.Count); Assert.AreEqual(snapshotCount2, snapshotCache.Count); - var oldSnapshotCache = snapshotCache; + FastDictionaryAppCache oldSnapshotCache = snapshotCache; snapshotCache.Clear(); Assert.AreEqual(1234, set1.Value(Mock.Of(), "prop1")); @@ -175,7 +192,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published Assert.AreEqual((interConverts == 1 ? 1 : 3) + snapshotCache.Count, converter.InterConverts); - var oldElementsCache = elementsCache; + FastDictionaryAppCache oldElementsCache = elementsCache; elementsCache.Clear(); Assert.AreEqual(1234, set1.Value(Mock.Of(), "prop1")); @@ -203,7 +220,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published new VoidEditor( NullLoggerFactory.Instance, dataTypeServiceMock.Object, - Mock.Of(), + Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()), @@ -218,7 +235,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published yield return publishedContentTypeFactory.CreatePropertyType(contentType, "prop1", 1); } - var setType1 = publishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "set1", CreatePropertyTypes); + IPublishedContentType setType1 = publishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "set1", CreatePropertyTypes); Assert.Throws(() => { @@ -230,16 +247,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published { private readonly PropertyCacheLevel _cacheLevel; - public CacheConverter1(PropertyCacheLevel cacheLevel) - { - _cacheLevel = cacheLevel; - } + public CacheConverter1(PropertyCacheLevel cacheLevel) => _cacheLevel = cacheLevel; public int SourceConverts { get; private set; } + public int InterConverts { get; private set; } public bool? IsValue(object value, PropertyValueLevel level) - => value != null && (!(value is string) || string.IsNullOrWhiteSpace((string) value) == false); + => value != null && (!(value is string) || string.IsNullOrWhiteSpace((string)value) == false); public bool IsConverter(IPublishedPropertyType propertyType) => propertyType.EditorAlias.InvariantEquals("Umbraco.Void"); @@ -259,11 +274,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Published public object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview) { InterConverts++; - return (int) inter; + return (int)inter; } public object ConvertIntermediateToXPath(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview) - => ((int) inter).ToString(); + => ((int)inter).ToString(); } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionTests.cs index 063a8c2621..6950c50cc0 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionTests.cs @@ -1,4 +1,8 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Linq; using NUnit.Framework; using Umbraco.Core; @@ -11,9 +15,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core public void GetBaseTypesIsOk() { // tests that the GetBaseTypes extension method works. - - var type = typeof(Class2); - var types = type.GetBaseTypes(true).ToArray(); + Type type = typeof(Class2); + Type[] types = type.GetBaseTypes(true).ToArray(); Assert.AreEqual(3, types.Length); Assert.Contains(typeof(Class2), types); Assert.Contains(typeof(Class1), types); @@ -25,8 +28,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core Assert.Contains(typeof(object), types); } - #region Test Objects - private class Class1 { } @@ -34,7 +35,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core private class Class2 : Class1 { } - - #endregion } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionUtilitiesTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionUtilitiesTests.cs index 0f48f2cea2..ba397522ae 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionUtilitiesTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ReflectionUtilitiesTests.cs @@ -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,28 +17,28 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core [Test] public void EmitCtorEmits() { - var ctor1 = ReflectionUtilities.EmitConstructor>(); + Func ctor1 = ReflectionUtilities.EmitConstructor>(); Assert.IsInstanceOf(ctor1()); - var ctor2 = ReflectionUtilities.EmitConstructor>(declaring: typeof(Class1)); + Func ctor2 = ReflectionUtilities.EmitConstructor>(declaring: typeof(Class1)); Assert.IsInstanceOf(ctor2()); - var ctor3 = ReflectionUtilities.EmitConstructor>(); + Func ctor3 = ReflectionUtilities.EmitConstructor>(); Assert.IsInstanceOf(ctor3(42)); - var ctor4 = ReflectionUtilities.EmitConstructor>(declaring: typeof(Class3)); + Func ctor4 = ReflectionUtilities.EmitConstructor>(declaring: typeof(Class3)); Assert.IsInstanceOf(ctor4(42)); } [Test] public void EmitCtorEmitsFromInfo() { - var ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, Array.Empty(), null); - var ctor1 = ReflectionUtilities.EmitConstructor>(ctorInfo); + ConstructorInfo ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, Array.Empty(), null); + Func ctor1 = ReflectionUtilities.EmitConstructor>(ctorInfo); Assert.IsInstanceOf(ctor1()); ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, new[] { typeof(int) }, null); - var ctor3 = ReflectionUtilities.EmitConstructor>(ctorInfo); + Func ctor3 = ReflectionUtilities.EmitConstructor>(ctorInfo); Assert.IsInstanceOf(ctor3(42)); Assert.Throws(() => ReflectionUtilities.EmitConstructor>(ctorInfo)); @@ -44,67 +47,63 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core [Test] public void EmitCtorEmitsPrivateCtor() { - var ctor = ReflectionUtilities.EmitConstructor>(); + Func ctor = ReflectionUtilities.EmitConstructor>(); Assert.IsInstanceOf(ctor("foo")); } [Test] - public void EmitCtorThrowsIfNotFound() - { + public void EmitCtorThrowsIfNotFound() => Assert.Throws(() => ReflectionUtilities.EmitConstructor>()); - } [Test] public void EmitCtorThrowsIfInvalid() { - var ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, Array.Empty(), null); + ConstructorInfo ctorInfo = typeof(Class1).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, Array.Empty(), null); Assert.Throws(() => ReflectionUtilities.EmitConstructor>(ctorInfo)); } [Test] - public void EmitCtorReturnsNull() - { + public void EmitCtorReturnsNull() => Assert.IsNull(ReflectionUtilities.EmitConstructor>(false)); - } [Test] public void EmitMethodEmitsInstance() { var class1 = new Class1(); - var method1 = ReflectionUtilities.EmitMethod>("Method1"); + Action method1 = ReflectionUtilities.EmitMethod>("Method1"); method1(class1); - var method2 = ReflectionUtilities.EmitMethod>("Method2"); + Action method2 = ReflectionUtilities.EmitMethod>("Method2"); method2(class1, 42); - var method3 = ReflectionUtilities.EmitMethod>("Method3"); + Func method3 = ReflectionUtilities.EmitMethod>("Method3"); Assert.AreEqual(42, method3(class1)); - var method4 = ReflectionUtilities.EmitMethod>("Method4"); + Func method4 = ReflectionUtilities.EmitMethod>("Method4"); Assert.AreEqual(42, method4(class1, "42")); } [Test] public void EmitMethodEmitsStatic() { - var method1 = ReflectionUtilities.EmitMethod("SMethod1"); + Action method1 = ReflectionUtilities.EmitMethod("SMethod1"); method1(); - var method2 = ReflectionUtilities.EmitMethod>("SMethod2"); + Action method2 = ReflectionUtilities.EmitMethod>("SMethod2"); method2(42); - var method3 = ReflectionUtilities.EmitMethod>("SMethod3"); + Func method3 = ReflectionUtilities.EmitMethod>("SMethod3"); Assert.AreEqual(42, method3()); - var method4 = ReflectionUtilities.EmitMethod>("SMethod4"); + Func method4 = ReflectionUtilities.EmitMethod>("SMethod4"); Assert.AreEqual(42, method4("42")); } [Test] public void EmitMethodEmitsStaticStatic() { - var method = ReflectionUtilities.EmitMethod(typeof (StaticClass1), "Method"); + Action method = ReflectionUtilities.EmitMethod(typeof(StaticClass1), "Method"); method(); } @@ -113,40 +112,40 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core { var class1 = new Class1(); - var methodInfo = typeof (Class1).GetMethod("Method1", BindingFlags.Instance | BindingFlags.Public); - var method1 = ReflectionUtilities.EmitMethod>(methodInfo); + MethodInfo methodInfo = typeof(Class1).GetMethod("Method1", BindingFlags.Instance | BindingFlags.Public); + Action method1 = ReflectionUtilities.EmitMethod>(methodInfo); method1(class1); - methodInfo = typeof(Class1).GetMethod("Method2", BindingFlags.Instance | BindingFlags.Public, null, new [] { typeof(int) }, null); - var method2 = ReflectionUtilities.EmitMethod>(methodInfo); + methodInfo = typeof(Class1).GetMethod("Method2", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(int) }, null); + Action method2 = ReflectionUtilities.EmitMethod>(methodInfo); method2(class1, 42); methodInfo = typeof(Class1).GetMethod("Method3", BindingFlags.Instance | BindingFlags.Public); - var method3 = ReflectionUtilities.EmitMethod>(methodInfo); + Func method3 = ReflectionUtilities.EmitMethod>(methodInfo); Assert.AreEqual(42, method3(class1)); methodInfo = typeof(Class1).GetMethod("Method4", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(string) }, null); - var method4 = ReflectionUtilities.EmitMethod>(methodInfo); + Func method4 = ReflectionUtilities.EmitMethod>(methodInfo); Assert.AreEqual(42, method4(class1, "42")); methodInfo = typeof(Class1).GetMethod("SMethod1", BindingFlags.Static | BindingFlags.Public); - var smethod1 = ReflectionUtilities.EmitMethod(methodInfo); + Action smethod1 = ReflectionUtilities.EmitMethod(methodInfo); smethod1(); methodInfo = typeof(Class1).GetMethod("SMethod2", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(int) }, null); - var smethod2 = ReflectionUtilities.EmitMethod>(methodInfo); + Action smethod2 = ReflectionUtilities.EmitMethod>(methodInfo); smethod2(42); methodInfo = typeof(Class1).GetMethod("SMethod3", BindingFlags.Static | BindingFlags.Public); - var smethod3 = ReflectionUtilities.EmitMethod>(methodInfo); + Func smethod3 = ReflectionUtilities.EmitMethod>(methodInfo); Assert.AreEqual(42, smethod3()); methodInfo = typeof(Class1).GetMethod("SMethod4", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string) }, null); - var smethod4 = ReflectionUtilities.EmitMethod>(methodInfo); + Func smethod4 = ReflectionUtilities.EmitMethod>(methodInfo); Assert.AreEqual(42, smethod4("42")); methodInfo = typeof(StaticClass1).GetMethod("Method", BindingFlags.Static | BindingFlags.Public); - var method = ReflectionUtilities.EmitMethod(methodInfo); + Action method = ReflectionUtilities.EmitMethod(methodInfo); method(); } @@ -155,10 +154,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core { var class1 = new Class1(); - var method1 = ReflectionUtilities.EmitMethod>("MethodP1"); + Action method1 = ReflectionUtilities.EmitMethod>("MethodP1"); method1(class1); - var method2 = ReflectionUtilities.EmitMethod("SMethodP1"); + Action method2 = ReflectionUtilities.EmitMethod("SMethodP1"); method2(); } @@ -172,7 +171,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core [Test] public void EmitMethodThrowsIfInvalid() { - var methodInfo = typeof(Class1).GetMethod("Method1", BindingFlags.Instance | BindingFlags.Public); + MethodInfo methodInfo = typeof(Class1).GetMethod("Method1", BindingFlags.Instance | BindingFlags.Public); Assert.Throws(() => ReflectionUtilities.EmitMethod>(methodInfo)); } @@ -188,19 +187,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core { var class1 = new Class1(); - var getter1 = ReflectionUtilities.EmitPropertyGetter("Value1"); + Func getter1 = ReflectionUtilities.EmitPropertyGetter("Value1"); Assert.AreEqual(42, getter1(class1)); - var getter2 = ReflectionUtilities.EmitPropertyGetter("Value3"); + Func getter2 = ReflectionUtilities.EmitPropertyGetter("Value3"); Assert.AreEqual(42, getter2(class1)); - var setter1 = ReflectionUtilities.EmitPropertySetter("Value2"); + Action setter1 = ReflectionUtilities.EmitPropertySetter("Value2"); setter1(class1, 42); - var setter2 = ReflectionUtilities.EmitPropertySetter("Value3"); + Action setter2 = ReflectionUtilities.EmitPropertySetter("Value3"); setter2(class1, 42); - (var getter3, var setter3) = ReflectionUtilities.EmitPropertyGetterAndSetter("Value3"); + (Func getter3, Action setter3) = ReflectionUtilities.EmitPropertyGetterAndSetter("Value3"); Assert.AreEqual(42, getter3(class1)); setter3(class1, 42); } @@ -210,23 +209,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core { var class1 = new Class1(); - var propertyInfo = typeof (Class1).GetProperty("Value1"); - var getter1 = ReflectionUtilities.EmitPropertyGetter(propertyInfo); + PropertyInfo propertyInfo = typeof(Class1).GetProperty("Value1"); + Func getter1 = ReflectionUtilities.EmitPropertyGetter(propertyInfo); Assert.AreEqual(42, getter1(class1)); propertyInfo = typeof(Class1).GetProperty("Value3"); - var getter2 = ReflectionUtilities.EmitPropertyGetter(propertyInfo); + Func getter2 = ReflectionUtilities.EmitPropertyGetter(propertyInfo); Assert.AreEqual(42, getter2(class1)); propertyInfo = typeof(Class1).GetProperty("Value2"); - var setter1 = ReflectionUtilities.EmitPropertySetter(propertyInfo); + Action setter1 = ReflectionUtilities.EmitPropertySetter(propertyInfo); setter1(class1, 42); propertyInfo = typeof(Class1).GetProperty("Value3"); - var setter2 = ReflectionUtilities.EmitPropertySetter(propertyInfo); + Action setter2 = ReflectionUtilities.EmitPropertySetter(propertyInfo); setter2(class1, 42); - (var getter3, var setter3) = ReflectionUtilities.EmitPropertyGetterAndSetter(propertyInfo); + (Func getter3, Action setter3) = ReflectionUtilities.EmitPropertyGetterAndSetter(propertyInfo); Assert.AreEqual(42, getter3(class1)); setter3(class1, 42); } @@ -236,7 +235,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core { var class1 = new Class1(); - var getter1 = ReflectionUtilities.EmitPropertyGetter("ValueP1"); + Func getter1 = ReflectionUtilities.EmitPropertyGetter("ValueP1"); Assert.AreEqual(42, getter1(class1)); } @@ -246,15 +245,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core Assert.Throws(() => ReflectionUtilities.EmitPropertyGetter("Zalue1")); Assert.Throws(() => ReflectionUtilities.EmitPropertyGetter("Value2")); - var propertyInfo = typeof(Class1).GetProperty("Value1"); + PropertyInfo propertyInfo = typeof(Class1).GetProperty("Value1"); Assert.Throws(() => ReflectionUtilities.EmitPropertySetter(propertyInfo)); } [Test] - public void EmitPropertyThrowsIfInvalid() - { + public void EmitPropertyThrowsIfInvalid() => Assert.Throws(() => ReflectionUtilities.EmitPropertyGetter("Value1")); - } [Test] public void EmitPropertyReturnsNull() @@ -267,18 +264,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core public void PropertySetterCanCastUnsafeValue() { // test that we can emit property setters that cast from eg 'object' - - var type4 = typeof(Class4); - var propInt4 = type4.GetProperty("IntValue"); - var propString4 = type4.GetProperty("StringValue"); - var propClassA4 = type4.GetProperty("ClassAValue"); + Type type4 = typeof(Class4); + PropertyInfo propInt4 = type4.GetProperty("IntValue"); + PropertyInfo propString4 = type4.GetProperty("StringValue"); + PropertyInfo propClassA4 = type4.GetProperty("ClassAValue"); var object4 = new Class4(); var object2A = new Class2A(); // works with a string property Assert.IsNotNull(propString4); - var setterString4 = ReflectionUtilities.EmitPropertySetterUnsafe(propString4); + Action setterString4 = ReflectionUtilities.EmitPropertySetterUnsafe(propString4); Assert.IsNotNull(setterString4); setterString4(object4, "foo"); Assert.IsNotNull(object4.StringValue); @@ -289,7 +285,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core // works with a reference property Assert.IsNotNull(propClassA4); - var setterClassA4 = ReflectionUtilities.EmitPropertySetterUnsafe(propClassA4); + Action setterClassA4 = ReflectionUtilities.EmitPropertySetterUnsafe(propClassA4); Assert.IsNotNull(setterClassA4); setterClassA4(object4, object2A); Assert.IsNotNull(object4.ClassAValue); @@ -297,7 +293,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core // works with a boxed value type Assert.IsNotNull(propInt4); - var setterInt4 = ReflectionUtilities.EmitPropertySetterUnsafe(propInt4); + Action setterInt4 = ReflectionUtilities.EmitPropertySetterUnsafe(propInt4); Assert.IsNotNull(setterInt4); setterInt4(object4, 42); @@ -318,14 +314,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core public void PropertySetterCanCastObject() { // Class5 inherits from Class4 and ClassValue is defined on Class4 - - var type5 = typeof(Class5); - var propClass4 = type5.GetProperty("ClassValue"); + Type type5 = typeof(Class5); + PropertyInfo propClass4 = type5.GetProperty("ClassValue"); var object2 = new Class2(); // can cast the object type from Class5 to Class4 - var setterClass4 = ReflectionUtilities.EmitPropertySetter(propClass4); + Action setterClass4 = ReflectionUtilities.EmitPropertySetter(propClass4); var object4 = new Class5(); setterClass4(object4, object2); @@ -336,13 +331,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core [Test] public void PropertySetterCanCastUnsafeObject() { - var type5 = typeof(Class5); - var propClass4 = type5.GetProperty("ClassValue"); + Type type5 = typeof(Class5); + PropertyInfo propClass4 = type5.GetProperty("ClassValue"); var object2 = new Class2(); // can cast the object type from object to Class4 - var setterClass4 = ReflectionUtilities.EmitPropertySetterUnsafe(propClass4); + Action setterClass4 = ReflectionUtilities.EmitPropertySetterUnsafe(propClass4); var object4 = new Class5(); setterClass4(object4, object2); @@ -353,17 +348,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core [Test] public void PropertyGetterCanCastValue() { - var type4 = typeof(Class4); - var propClassA4 = type4.GetProperty("ClassAValue"); - var propInt4 = type4.GetProperty("IntValue"); + Type type4 = typeof(Class4); + PropertyInfo propClassA4 = type4.GetProperty("ClassAValue"); + PropertyInfo propInt4 = type4.GetProperty("IntValue"); var object2A = new Class2A(); var object4 = new Class4 { ClassAValue = object2A, IntValue = 159 }; // can cast the return type from Class2A to Class2 - var getterClassA4 = ReflectionUtilities.EmitPropertyGetter(propClassA4); + Func getterClassA4 = ReflectionUtilities.EmitPropertyGetter(propClassA4); - var valueClass4A = getterClassA4(object4); + Class2 valueClass4A = getterClassA4(object4); Assert.IsNotNull(valueClass4A); Assert.AreSame(object2A, valueClass4A); @@ -372,9 +367,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core => ReflectionUtilities.EmitPropertyGetter(propClassA4)); // can cast and box the return type from int to object - var getterInt4 = ReflectionUtilities.EmitPropertyGetter(propInt4); + Func getterInt4 = ReflectionUtilities.EmitPropertyGetter(propInt4); - var valueInt4 = getterInt4(object4); + object valueInt4 = getterInt4(object4); Assert.IsTrue(valueInt4 is int); Assert.AreEqual(159, valueInt4); @@ -386,16 +381,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core [Test] public void PropertyGetterCanCastObject() { - var type5 = typeof(Class5); - var propClass4 = type5.GetProperty("ClassValue"); + Type type5 = typeof(Class5); + PropertyInfo propClass4 = type5.GetProperty("ClassValue"); var object2 = new Class2(); var object4 = new Class5 { ClassValue = object2 }; // can cast the object type from Class5 to Class4 - var getterClass4 = ReflectionUtilities.EmitPropertyGetter(propClass4); + Func getterClass4 = ReflectionUtilities.EmitPropertyGetter(propClass4); - var valueClass4 = getterClass4(object4); + Class2 valueClass4 = getterClass4(object4); Assert.IsNotNull(valueClass4); Assert.AreSame(object2, valueClass4); @@ -408,10 +403,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core public void EmitPropertyCastGetterEmits() { // test that we can emit property getters that cast the returned value to 'object' - // test simple class - - var type4 = typeof(Class4); + Type type4 = typeof(Class4); var object4 = new Class4 { @@ -421,69 +414,71 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core }; // works with a string property - var propString4 = type4.GetProperty("StringValue"); + PropertyInfo propString4 = type4.GetProperty("StringValue"); Assert.IsNotNull(propString4); - var getterString4 = ReflectionUtilities.EmitPropertyGetter(propString4); + Func getterString4 = ReflectionUtilities.EmitPropertyGetter(propString4); Assert.IsNotNull(getterString4); - var valueString4 = getterString4(object4); + object valueString4 = getterString4(object4); Assert.IsNotNull(valueString4); Assert.AreEqual("foo", valueString4); // works with a reference property - var propClass4 = type4.GetProperty("ClassValue"); + PropertyInfo propClass4 = type4.GetProperty("ClassValue"); Assert.IsNotNull(propClass4); - var getterClass4 = ReflectionUtilities.EmitPropertyGetter(propClass4); + Func getterClass4 = ReflectionUtilities.EmitPropertyGetter(propClass4); Assert.IsNotNull(getterClass4); - var valueClass4 = getterClass4(object4); + object valueClass4 = getterClass4(object4); Assert.IsNotNull(valueClass4); Assert.IsInstanceOf(valueClass4); // works with a value type property - var propInt4 = type4.GetProperty("IntValue"); + PropertyInfo propInt4 = type4.GetProperty("IntValue"); Assert.IsNotNull(propInt4); // ... if explicitly getting a value type - var getterInt4T = ReflectionUtilities.EmitPropertyGetter(propInt4); + Func getterInt4T = ReflectionUtilities.EmitPropertyGetter(propInt4); Assert.IsNotNull(getterInt4T); - var valueInt4T = getterInt4T(object4); + int valueInt4T = getterInt4T(object4); Assert.AreEqual(1, valueInt4T); // ... if using a compiled getter - var valueInt4D = GetIntValue(object4); + object valueInt4D = GetIntValue(object4); Assert.IsNotNull(valueInt4D); Assert.IsTrue(valueInt4D is int); Assert.AreEqual(1, valueInt4D); // ... if getting a non-value type (emit adds a box) - var getterInt4 = ReflectionUtilities.EmitPropertyGetter(propInt4); + Func getterInt4 = ReflectionUtilities.EmitPropertyGetter(propInt4); Assert.IsNotNull(getterInt4); - var valueInt4 = getterInt4(object4); + object valueInt4 = getterInt4(object4); Assert.IsNotNull(valueInt4); Assert.IsTrue(valueInt4 is int); Assert.AreEqual(1, valueInt4); var getters4 = type4 .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy) - .ToDictionary(x => x.Name, x => (object) ReflectionUtilities.EmitPropertyGetter(x)); + .ToDictionary(x => x.Name, x => (object)ReflectionUtilities.EmitPropertyGetter(x)); Console.WriteLine("Getting object4 values..."); - var values4 = getters4.ToDictionary(kvp => kvp.Key, kvp => ((Func) kvp.Value)(object4)); + var values4 = getters4.ToDictionary(kvp => kvp.Key, kvp => ((Func)kvp.Value)(object4)); Console.WriteLine("Writing object4 values..."); - foreach ((var name, var value) in values4) + foreach ((string name, object value) in values4) + { Console.WriteLine($"{name}: {value}"); + } + Assert.AreEqual(4, values4.Count); Assert.AreEqual("foo", values4["StringValue"]); Assert.IsInstanceOf(values4["ClassValue"]); Assert.AreEqual(1, values4["IntValue"]); // test hierarchy - - var type5 = typeof(Class5); + Type type5 = typeof(Class5); var getters5 = type5 .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy) - .ToDictionary(x => x.Name, x => (object) ReflectionUtilities.EmitPropertyGetter(x)); + .ToDictionary(x => x.Name, x => (object)ReflectionUtilities.EmitPropertyGetter(x)); var object5 = new Class5 { @@ -496,11 +491,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core }; Console.WriteLine("Getting object5 values..."); - var values5 = getters5.ToDictionary(kvp => kvp.Key, kvp => ((Func) kvp.Value)(object5)); + var values5 = getters5.ToDictionary(kvp => kvp.Key, kvp => ((Func)kvp.Value)(object5)); Console.WriteLine("Writing object5 values..."); - foreach ((var name, var value) in values5) + foreach ((string name, object value) in values5) + { Console.WriteLine($"{name}: {value}"); + } + Assert.AreEqual(7, values5.Count); Assert.AreEqual("foo", values5["StringValue"]); Assert.IsInstanceOf(values5["ClassValue"]); @@ -510,13 +508,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core Assert.AreEqual(1, values5["IntValue2"]); // test object extensions - Console.WriteLine("Getting object5D values..."); - var values5D = ObjectJsonExtensions.ToObjectDictionary(object5); + Dictionary values5D = ObjectJsonExtensions.ToObjectDictionary(object5); Console.WriteLine("Writing object5D values..."); - foreach ((var name, var value) in values5) + foreach ((string name, object value) in values5) + { Console.WriteLine($"{name}: {value}"); + } + Assert.AreEqual(7, values5.Count); Assert.AreEqual("foo", values5D["StringValue"]); Assert.IsInstanceOf(values5D["ClassValue"]); @@ -529,18 +529,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core [Test] public void EmitFieldGetterSetterEmits() { - var getter1 = ReflectionUtilities.EmitFieldGetter("Field1"); - var getter2 = ReflectionUtilities.EmitFieldGetter("Field2"); + Func getter1 = ReflectionUtilities.EmitFieldGetter("Field1"); + Func getter2 = ReflectionUtilities.EmitFieldGetter("Field2"); var c = new Class1(); Assert.AreEqual(33, getter1(c)); Assert.AreEqual(66, getter2(c)); - var setter2 = ReflectionUtilities.EmitFieldSetter("Field2"); + Action setter2 = ReflectionUtilities.EmitFieldSetter("Field2"); setter2(c, 99); Assert.AreEqual(99, getter2(c)); // works on readonly fields! - var (getter3, setter3) = ReflectionUtilities.EmitFieldGetterAndSetter("Field3"); + (Func getter3, Action setter3) = ReflectionUtilities.EmitFieldGetterAndSetter("Field3"); Assert.AreEqual(22, getter3(c)); setter3(c, 44); Assert.AreEqual(44, getter3(c)); @@ -554,8 +554,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core var o = new { a = 1, b = "hello" }; var getters = new Dictionary>(); - foreach (var prop in o.GetType().GetProperties()) + foreach (PropertyInfo prop in o.GetType().GetProperties()) + { getters[prop.Name] = ReflectionUtilities.EmitMethodUnsafe>(prop.GetMethod); + } Assert.AreEqual(2, getters.Count); Assert.IsTrue(getters.ContainsKey("a")); @@ -564,40 +566,46 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core Assert.AreEqual("hello", getters["b"](o)); } - #region IL Code - // these functions can be examined in eg DotPeek to understand IL works // box [mscorlib]System.Int32 public object GetIntValue(Class4 object4) => object4.IntValue; // unbox.any [mscorlib]System.Int32 - public void SetIntValue(Class4 object4, object i) => object4.IntValue = (int) i; + public void SetIntValue(Class4 object4, object i) => object4.IntValue = (int)i; // castclass [mscorlib]System.String - public void SetStringValue(Class4 object4, object s) => object4.StringValue = (string) s; + public void SetStringValue(Class4 object4, object s) => object4.StringValue = (string)s; // conv.i4 - public void SetIntValue(Class4 object4, double d) => object4.IntValue = (int) d; + public void SetIntValue(Class4 object4, double d) => object4.IntValue = (int)d; // unbox.any [mscorlib]System.Double // conv.i4 - public void SetIntValue2(Class4 object4, object d) => object4.IntValue = (int) (double) d; + public void SetIntValue2(Class4 object4, object d) => object4.IntValue = (int)(double)d; public void SetIntValue3(Class4 object4, object v) { if (v is int i) + { object4.IntValue = i; + } else + { object4.IntValue = Convert.ToInt32(v); + } } public void SetIntValue4(Class4 object4, object v) { if (v is int i) + { object4.IntValue = i; + } else - object4.IntValue = (int) Convert.ChangeType(v, typeof(int)); + { + object4.IntValue = (int)Convert.ChangeType(v, typeof(int)); + } } // get field @@ -606,38 +614,69 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core // set field public void SetIntField(Class1 object1, int i) => object1.Field1 = i; - #endregion - - #region Test Objects - public static class StaticClass1 { - public static void Method() { } + public static void Method() + { + } } public class Class1 { - public Class1() { } - public Class1(int i) { } + public Class1() + { + } + + public Class1(int i) + { + } + + public void Method1() + { + } + + public void Method2(int i) + { + } - public void Method1() { } - public void Method2(int i) { } public int Method3() => 42; + public int Method4(string s) => int.Parse(s); public string Method5() => "foo"; - public static void SMethod1() { } - public static void SMethod2(int i) { } + public static void SMethod1() + { + } + + public static void SMethod2(int i) + { + } + public static int SMethod3() => 42; + public static int SMethod4(string s) => int.Parse(s); - private void MethodP1() { } - private static void SMethodP1() { } + private void MethodP1() + { + } + + private static void SMethodP1() + { + } public int Value1 => 42; - public int Value2 { set { } } - public int Value3 { get { return 42; } set { } } + + public int Value2 + { + set { } + } + + public int Value3 + { + get => 42; set { } + } + private int ValueP1 => 42; public int Field1 = 33; @@ -645,22 +684,33 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core public readonly int Field3 = 22; } - public class Class2 { } + public class Class2 + { + } - public class Class2A : Class2 { } + public class Class2A : Class2 + { + } public class Class3 { - public Class3(int i) { } + public Class3(int i) + { + } - private Class3(string s) { } + private Class3(string s) + { + } } public class Class4 { public int IntValue { get; set; } + public string StringValue { get; set; } - public Class2 ClassValue { get;set; } + + public Class2 ClassValue { get; set; } + public Class2A ClassAValue { get; set; } } @@ -668,10 +718,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core { [JsonProperty("intValue2")] public int IntValue2 { get; set; } - public string StringValue2 { get; set; } - public Class2 ClassValue2 { get;set; } - } - #endregion + public string StringValue2 { get; set; } + + public Class2 ClassValue2 { get; set; } + } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/SiteDomainHelperTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/SiteDomainHelperTests.cs index d32340b6b0..2aed3e0216 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/SiteDomainHelperTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/SiteDomainHelperTests.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using NUnit.Framework; @@ -10,19 +14,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing public class SiteDomainHelperTests { [SetUp] - public void SetUp() - { - SiteDomainHelper.Clear(); // assuming this works! - } + public void SetUp() => SiteDomainHelper.Clear(); // assuming this works! [TearDown] - public void TearDown() - { - SiteDomainHelper.Clear(); // assuming this works! - } + public void TearDown() => SiteDomainHelper.Clear(); // assuming this works! - private static CultureInfo _cultureFr = CultureInfo.GetCultureInfo("fr-fr"); - private static CultureInfo _cultureGb = CultureInfo.GetCultureInfo("en-gb"); + private static readonly CultureInfo s_cultureFr = CultureInfo.GetCultureInfo("fr-fr"); + private static readonly CultureInfo s_cultureGb = CultureInfo.GetCultureInfo("en-gb"); [Test] public void AddSites() @@ -30,14 +28,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing SiteDomainHelper.AddSite("site1", "domain1.com", "domain1.net", "domain1.org"); SiteDomainHelper.AddSite("site2", "domain2.com", "domain2.net", "domain2.org"); - var sites = SiteDomainHelper.Sites; + Dictionary sites = SiteDomainHelper.Sites; Assert.AreEqual(2, sites.Count); Assert.Contains("site1", sites.Keys); Assert.Contains("site2", sites.Keys); - var domains = sites["site1"]; + string[] domains = sites["site1"]; Assert.AreEqual(3, domains.Length); Assert.Contains("domain1.com", domains); Assert.Contains("domain1.net", domains); @@ -60,18 +58,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing [TestCase("http://www.domain.com:12/")] [TestCase("https://foo.www.domain.com")] [TestCase("https://foo.www.domain.com:5478/")] - public void AddValidSite(string domain) - { - SiteDomainHelper.AddSite("site1", domain); - } + public void AddValidSite(string domain) => SiteDomainHelper.AddSite("site1", domain); [TestCase("domain.com/foo")] [TestCase("http:/domain.com")] [TestCase("*")] - public void AddInvalidSite(string domain) - { - Assert.Throws(() => SiteDomainHelper.AddSite("site1", domain)); - } + public void AddInvalidSite(string domain) => Assert.Throws(() => SiteDomainHelper.AddSite("site1", domain)); [Test] public void AddRemoveSites() @@ -79,7 +71,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing SiteDomainHelper.AddSite("site1", "domain1.com", "domain1.net", "domain1.org"); SiteDomainHelper.AddSite("site2", "domain2.com", "domain2.net", "domain2.org"); - var sites = SiteDomainHelper.Sites; + Dictionary sites = SiteDomainHelper.Sites; SiteDomainHelper.RemoveSite("site1"); SiteDomainHelper.RemoveSite("site3"); @@ -95,13 +87,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing SiteDomainHelper.AddSite("site1", "domain1.com", "domain1.net", "domain1.org"); SiteDomainHelper.AddSite("site1", "domain2.com", "domain1.net"); - var sites = SiteDomainHelper.Sites; + Dictionary sites = SiteDomainHelper.Sites; Assert.AreEqual(1, sites.Count); Assert.Contains("site1", sites.Keys); - var domains = sites["site1"]; + string[] domains = sites["site1"]; Assert.AreEqual(2, domains.Count()); Assert.Contains("domain2.com", domains); Assert.Contains("domain1.net", domains); @@ -117,13 +109,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing SiteDomainHelper.BindSites("site1", "site2"); - var bindings = SiteDomainHelper.Bindings; + Dictionary> bindings = SiteDomainHelper.Bindings; Assert.AreEqual(2, bindings.Count); Assert.Contains("site1", bindings.Keys); Assert.Contains("site2", bindings.Keys); - var others = bindings["site1"]; + List others = bindings["site1"]; Assert.AreEqual(1, others.Count); Assert.Contains("site2", others); @@ -143,14 +135,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing SiteDomainHelper.BindSites("site1", "site2"); SiteDomainHelper.BindSites("site1", "site3"); - var bindings = SiteDomainHelper.Bindings; + Dictionary> bindings = SiteDomainHelper.Bindings; Assert.AreEqual(3, bindings.Count); Assert.Contains("site1", bindings.Keys); Assert.Contains("site2", bindings.Keys); Assert.Contains("site3", bindings.Keys); - var others = bindings["site1"]; + List others = bindings["site1"]; Assert.AreEqual(2, others.Count); Assert.Contains("site2", others); Assert.Contains("site3", others); @@ -166,14 +158,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing Assert.Contains("site2", others); } - private DomainAndUri[] DomainAndUris(Uri current, Domain[] domains) - { - return domains + private DomainAndUri[] DomainAndUris(Uri current, Domain[] domains) => + domains .Where(d => d.IsWildcard == false) .Select(d => new DomainAndUri(d, current)) .OrderByDescending(d => d.Uri.ToString()) .ToArray(); - } [Test] public void MapDomainWithScheme() @@ -189,40 +179,44 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing // this works, but it's purely by chance / arbitrary // don't use the www in tests here! var current = new Uri("https://www.domain1.com/foo/bar"); - var domainAndUris = DomainAndUris(current, new[] - { - new Domain(1, "domain2.com", -1, _cultureFr, false), - new Domain(1, "domain1.com", -1, _cultureGb, false), - }); - var output = helper.MapDomain(domainAndUris, current, _cultureFr.Name, _cultureFr.Name).Uri.ToString(); + Domain[] domains = new[] + { + new Domain(1, "domain2.com", -1, s_cultureFr, false), + new Domain(1, "domain1.com", -1, s_cultureGb, false), + }; + DomainAndUri[] domainAndUris = DomainAndUris(current, domains); + string output = helper.MapDomain(domainAndUris, current, s_cultureFr.Name, s_cultureFr.Name).Uri.ToString(); Assert.AreEqual("https://domain1.com/", output); // will pick it all right current = new Uri("https://domain1.com/foo/bar"); - domainAndUris = DomainAndUris(current, new[] - { - new Domain(1, "https://domain1.com", -1, _cultureFr, false), - new Domain(1, "https://domain2.com", -1, _cultureGb, false) - }); - output = helper.MapDomain(domainAndUris, current, _cultureFr.Name, _cultureFr.Name).Uri.ToString(); + domains = new[] + { + new Domain(1, "https://domain1.com", -1, s_cultureFr, false), + new Domain(1, "https://domain2.com", -1, s_cultureGb, false) + }; + domainAndUris = DomainAndUris(current, domains); + output = helper.MapDomain(domainAndUris, current, s_cultureFr.Name, s_cultureFr.Name).Uri.ToString(); Assert.AreEqual("https://domain1.com/", output); current = new Uri("https://domain1.com/foo/bar"); - domainAndUris = DomainAndUris(current, new[] - { - new Domain(1, "https://domain1.com", -1, _cultureFr, false), - new Domain(1, "https://domain4.com", -1, _cultureGb, false) - }); - output = helper.MapDomain(domainAndUris, current, _cultureFr.Name, _cultureFr.Name).Uri.ToString(); + domains = new[] + { + new Domain(1, "https://domain1.com", -1, s_cultureFr, false), + new Domain(1, "https://domain4.com", -1, s_cultureGb, false) + }; + domainAndUris = DomainAndUris(current, domains); + output = helper.MapDomain(domainAndUris, current, s_cultureFr.Name, s_cultureFr.Name).Uri.ToString(); Assert.AreEqual("https://domain1.com/", output); current = new Uri("https://domain4.com/foo/bar"); - domainAndUris = DomainAndUris(current, new[] + domains = new[] { - new Domain(1, "https://domain1.com", -1, _cultureFr, false), - new Domain(1, "https://domain4.com", -1, _cultureGb, false) - }); - output = helper.MapDomain(domainAndUris, current, _cultureFr.Name, _cultureFr.Name).Uri.ToString(); + new Domain(1, "https://domain1.com", -1, s_cultureFr, false), + new Domain(1, "https://domain4.com", -1, s_cultureGb, false) + }; + domainAndUris = DomainAndUris(current, domains); + output = helper.MapDomain(domainAndUris, current, s_cultureFr.Name, s_cultureFr.Name).Uri.ToString(); Assert.AreEqual("https://domain4.com/", output); } @@ -239,36 +233,42 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing // current is a site1 uri, domains contain current // so we'll get current - // var current = new Uri("http://domain1.com/foo/bar"); - var output = helper.MapDomain(new[] + string output = helper.MapDomain( + new[] { - new DomainAndUri(new Domain(1, "domain1.com", -1, _cultureFr, false), current), - new DomainAndUri(new Domain(1, "domain2.com", -1, _cultureGb, false), current), - }, current, _cultureFr.Name, _cultureFr.Name).Uri.ToString(); + new DomainAndUri(new Domain(1, "domain1.com", -1, s_cultureFr, false), current), + new DomainAndUri(new Domain(1, "domain2.com", -1, s_cultureGb, false), current), + }, current, + s_cultureFr.Name, + s_cultureFr.Name).Uri.ToString(); Assert.AreEqual("http://domain1.com/", output); // current is a site1 uri, domains do not contain current // so we'll get the corresponding site1 domain - // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomain(new[] + output = helper.MapDomain( + new[] { - new DomainAndUri(new Domain(1, "domain1.net", -1, _cultureFr, false), current), - new DomainAndUri(new Domain(1, "domain2.net", -1, _cultureGb, false), current) - }, current, _cultureFr.Name, _cultureFr.Name).Uri.ToString(); + new DomainAndUri(new Domain(1, "domain1.net", -1, s_cultureFr, false), current), + new DomainAndUri(new Domain(1, "domain2.net", -1, s_cultureGb, false), current) + }, current, + s_cultureFr.Name, + s_cultureFr.Name).Uri.ToString(); Assert.AreEqual("http://domain1.net/", output); // current is a site1 uri, domains do not contain current // so we'll get the corresponding site1 domain // order does not matter - // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomain(new[] + output = helper.MapDomain( + new[] { - new DomainAndUri(new Domain(1, "domain2.net", -1, _cultureFr, false), current), - new DomainAndUri(new Domain(1, "domain1.net", -1, _cultureGb, false), current) - }, current, _cultureFr.Name, _cultureFr.Name).Uri.ToString(); + new DomainAndUri(new Domain(1, "domain2.net", -1, s_cultureFr, false), current), + new DomainAndUri(new Domain(1, "domain1.net", -1, s_cultureGb, false), current) + }, current, + s_cultureFr.Name, + s_cultureFr.Name).Uri.ToString(); Assert.AreEqual("http://domain1.net/", output); } @@ -289,31 +289,39 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing // - return all domains from same site, or bound sites // current is a site1 uri, domains contains current - // var current = new Uri("http://domain1.com/foo/bar"); - var output = helper.MapDomains(new[] + DomainAndUri[] output = helper.MapDomains( + new[] { - new DomainAndUri(new Domain(1, "domain1.com", -1, _cultureFr, false), current), // no: current + what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain4.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, _cultureGb, false), current), // yes: same site (though bogus setup) - }, current, true, _cultureFr.Name, _cultureFr.Name).ToArray(); + new DomainAndUri(new Domain(1, "domain1.com", -1, s_cultureFr, false), current), // no: current + what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain4.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, s_cultureGb, false), current), // yes: same site (though bogus setup) + }, + current, + true, + s_cultureFr.Name, + s_cultureFr.Name).ToArray(); Assert.AreEqual(1, output.Count()); Assert.Contains("http://domain1.org/", output.Select(d => d.Uri.ToString()).ToArray()); // current is a site1 uri, domains does not contain current - // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomains(new[] + output = helper.MapDomains( + new[] { - new DomainAndUri(new Domain(1, "domain1.net", -1, _cultureFr, false), current), // no: what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain4.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, _cultureGb, false), current), // yes: same site (though bogus setup) - }, current, true, _cultureFr.Name, _cultureFr.Name).ToArray(); + new DomainAndUri(new Domain(1, "domain1.net", -1, s_cultureFr, false), current), // no: what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain4.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, s_cultureGb, false), current), // yes: same site (though bogus setup) + }, + current, + true, + s_cultureFr.Name, + s_cultureFr.Name).ToArray(); Assert.AreEqual(1, output.Count()); Assert.Contains("http://domain1.org/", output.Select(d => d.Uri.ToString()).ToArray()); @@ -322,17 +330,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing SiteDomainHelper.BindSites("site2", "site4"); // current is a site1 uri, domains contains current - // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomains(new[] + output = helper.MapDomains( + new[] { - new DomainAndUri(new Domain(1, "domain1.com", -1, _cultureFr, false), current), // no: current + what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, _cultureGb, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain3.org", -1, _cultureGb, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain4.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, _cultureGb, false), current), // yes: same site (though bogus setup) - }, current, true, _cultureFr.Name, _cultureFr.Name).ToArray(); + new DomainAndUri(new Domain(1, "domain1.com", -1, s_cultureFr, false), current), // no: current + what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, s_cultureGb, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain3.org", -1, s_cultureGb, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain4.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, s_cultureGb, false), current), // yes: same site (though bogus setup) + }, + current, + true, + s_cultureFr.Name, + s_cultureFr.Name).ToArray(); Assert.AreEqual(3, output.Count()); Assert.Contains("http://domain1.org/", output.Select(d => d.Uri.ToString()).ToArray()); @@ -340,17 +352,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing Assert.Contains("http://domain3.org/", output.Select(d => d.Uri.ToString()).ToArray()); // current is a site1 uri, domains does not contain current - // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomains(new[] + output = helper.MapDomains( + new[] { - new DomainAndUri(new Domain(1, "domain1.net", -1, _cultureFr, false), current), // no: what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, _cultureGb, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain3.org", -1, _cultureGb, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain4.com", -1, _cultureGb, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, _cultureGb, false), current), // yes: same site (though bogus setup) - }, current, true, _cultureFr.Name, _cultureFr.Name).ToArray(); + new DomainAndUri(new Domain(1, "domain1.net", -1, s_cultureFr, false), current), // no: what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, s_cultureGb, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain3.org", -1, s_cultureGb, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain4.com", -1, s_cultureGb, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, s_cultureGb, false), current), // yes: same site (though bogus setup) + }, current, + true, + s_cultureFr.Name, + s_cultureFr.Name).ToArray(); Assert.AreEqual(3, output.Count()); Assert.Contains("http://domain1.org/", output.Select(d => d.Uri.ToString()).ToArray()); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UriUtilityTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UriUtilityTests.cs index e577fc28fa..dee487621f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UriUtilityTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UriUtilityTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Moq; using NUnit.Framework; using Umbraco.Core.Configuration.Models; @@ -46,10 +49,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing { // Arrange var sourceUri = new Uri(sourceUrl); - var uriUtility = BuildUriUtility("/"); + UriUtility uriUtility = BuildUriUtility("/"); // Act - var resultUri = uriUtility.UriToUmbraco(sourceUri); + Uri resultUri = uriUtility.UriToUmbraco(sourceUri); // Assert var expectedUri = new Uri(expectedUrl); @@ -70,10 +73,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing // Arrange var sourceUri = new Uri(sourceUrl, UriKind.Relative); var requestHandlerSettings = new RequestHandlerSettings { AddTrailingSlash = trailingSlash }; - var uriUtility = BuildUriUtility("/"); + UriUtility uriUtility = BuildUriUtility("/"); // Act - var resultUri = uriUtility.UriFromUmbraco(sourceUri, requestHandlerSettings); + Uri resultUri = uriUtility.UriFromUmbraco(sourceUri, requestHandlerSettings); // Assert var expectedUri = new Uri(expectedUrl, UriKind.Relative); @@ -90,7 +93,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing public void Uri_To_Absolute(string virtualPath, string sourceUrl, string expectedUrl) { // Arrange - var uriUtility = BuildUriUtility(virtualPath); + UriUtility uriUtility = BuildUriUtility(virtualPath); // Act var resultUrl = uriUtility.ToAbsolute(sourceUrl); @@ -109,7 +112,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing public void Url_To_App_Relative(string virtualPath, string sourceUrl, string expectedUrl) { // Arrange - var uriUtility = BuildUriUtility(virtualPath); + UriUtility uriUtility = BuildUriUtility(virtualPath); // Act var resultUrl = uriUtility.ToAppRelative(sourceUrl); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/WebPathTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/WebPathTests.cs index 6c2e5f3fcb..ec1602e629 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/WebPathTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/WebPathTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using NUnit.Framework; using Umbraco.Core.Routing; @@ -19,21 +22,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing [TestCase("~/umbraco/", "/config/", "/lang/", ExpectedResult = "~/umbraco/config/lang")] [TestCase("~/umbraco/", "config/", "lang/", ExpectedResult = "~/umbraco/config/lang")] [TestCase("~/umbraco", ExpectedResult = "~/umbraco")] - public string Combine(params string[] parts) - { - return WebPath.Combine(parts); - } + public string Combine(params string[] parts) => WebPath.Combine(parts); [Test] - public void Combine_must_handle_empty_array() - { - Assert.AreEqual(string.Empty,WebPath.Combine(Array.Empty())); - } + public void Combine_must_handle_empty_array() => Assert.AreEqual(string.Empty, WebPath.Combine(Array.Empty())); [Test] - public void Combine_must_handle_null() - { - Assert.Throws(() => WebPath.Combine(null)); - } + public void Combine_must_handle_null() => Assert.Throws(() => WebPath.Combine(null)); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Scoping/EventNameExtractorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Scoping/EventNameExtractorTests.cs index be3129aab0..60e3915325 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Scoping/EventNameExtractorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Scoping/EventNameExtractorTests.cs @@ -1,5 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; +using Umbraco.Core; using Umbraco.Core.Events; namespace Umbraco.Tests.UnitTests.Umbraco.Core.Scoping @@ -10,7 +14,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Scoping [Test] public void Find_Event_Ing() { - var found = EventNameExtractor.FindEvent(this, new SaveEventArgs("test"), EventNameExtractor.MatchIngNames); + Attempt found = EventNameExtractor.FindEvent(this, new SaveEventArgs("test"), EventNameExtractor.MatchIngNames); Assert.IsTrue(found.Success); Assert.AreEqual("FoundMe", found.Result.Name); } @@ -18,7 +22,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Scoping [Test] public void Find_Event_Non_Ing() { - var found = EventNameExtractor.FindEvent(this, new SaveEventArgs("test"), EventNameExtractor.MatchNonIngNames); + Attempt found = EventNameExtractor.FindEvent(this, new SaveEventArgs("test"), EventNameExtractor.MatchNonIngNames); Assert.IsTrue(found.Success); Assert.AreEqual("FindingMe", found.Result.Name); } @@ -26,7 +30,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Scoping [Test] public void Ambiguous_Match() { - var found = EventNameExtractor.FindEvent(this, new SaveEventArgs(0), EventNameExtractor.MatchIngNames); + Attempt found = EventNameExtractor.FindEvent(this, new SaveEventArgs(0), EventNameExtractor.MatchIngNames); Assert.IsFalse(found.Success); Assert.AreEqual(EventNameExtractorError.Ambiguous, found.Result.Error); } @@ -34,18 +38,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Scoping [Test] public void No_Match() { - var found = EventNameExtractor.FindEvent(this, new SaveEventArgs(0), EventNameExtractor.MatchIngNames); + Attempt found = EventNameExtractor.FindEvent(this, new SaveEventArgs(0), EventNameExtractor.MatchIngNames); Assert.IsFalse(found.Success); Assert.AreEqual(EventNameExtractorError.NoneFound, found.Result.Error); } public static event EventHandler> FindingMe; + public static event EventHandler> FoundMe; - //will lead to ambiguous matches + // will lead to ambiguous matches public static event EventHandler> SavingThis; + public static event EventHandler> SavedThis; + public static event EventHandler> SavingThat; + public static event EventHandler> SavedThat; } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/ContentPermissionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/ContentPermissionsTests.cs index 8a7b26c6cf..f4bd63f1f8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/ContentPermissionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/ContentPermissionsTests.cs @@ -1,4 +1,7 @@ -using Moq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Moq; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; @@ -16,352 +19,353 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Security [Test] public void Access_Allowed_By_Path() { - //arrange - var user = CreateUser(id: 9); + // Arrange + IUser user = CreateUser(id: 9); var contentMock = new Mock(); contentMock.Setup(c => c.Path).Returns("-1,1234,5678"); - var content = contentMock.Object; + IContent content = contentMock.Object; var contentServiceMock = new Mock(); contentServiceMock.Setup(x => x.GetById(1234)).Returns(content); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var userServiceMock = new Mock(); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Granted, result); } [Test] public void No_Content_Found() { - //arrange - var user = CreateUser(id: 9); + // Arrange + IUser user = CreateUser(id: 9); var contentMock = new Mock(); contentMock.Setup(c => c.Path).Returns("-1,1234,5678"); - var content = contentMock.Object; + IContent content = contentMock.Object; var contentServiceMock = new Mock(); contentServiceMock.Setup(x => x.GetById(0)).Returns(content); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var userServiceMock = new Mock(); var permissions = new EntityPermissionCollection(); var permissionSet = new EntityPermissionSet(1234, permissions); userServiceMock.Setup(x => x.GetPermissionsForPath(user, "-1,1234,5678")).Returns(permissionSet); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent, new[] { 'F' }); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent, new[] { 'F' }); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.NotFound, result); } [Test] public void No_Access_By_Path() { - //arrange - var user = CreateUser(id: 9, startContentId: 9876); + // Arrange + IUser user = CreateUser(id: 9, startContentId: 9876); var contentMock = new Mock(); contentMock.Setup(c => c.Path).Returns("-1,1234,5678"); - var content = contentMock.Object; + IContent content = contentMock.Object; var contentServiceMock = new Mock(); contentServiceMock.Setup(x => x.GetById(1234)).Returns(content); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var userServiceMock = new Mock(); var permissions = new EntityPermissionCollection(); var permissionSet = new EntityPermissionSet(1234, permissions); userServiceMock.Setup(x => x.GetPermissionsForPath(user, "-1,1234")).Returns(permissionSet); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); entityServiceMock.Setup(x => x.GetAllPaths(It.IsAny(), It.IsAny())) .Returns(new[] { Mock.Of(entity => entity.Id == 9876 && entity.Path == "-1,9876") }); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent, new[] { 'F' }); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent, new[] { 'F' }); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Denied, result); } [Test] public void No_Access_By_Permission() { - //arrange - var user = CreateUser(id: 9); + // Arrange + IUser user = CreateUser(id: 9); var contentMock = new Mock(); contentMock.Setup(c => c.Path).Returns("-1,1234,5678"); - var content = contentMock.Object; + IContent content = contentMock.Object; var contentServiceMock = new Mock(); contentServiceMock.Setup(x => x.GetById(1234)).Returns(content); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var userServiceMock = new Mock(); var permissions = new EntityPermissionCollection { - new EntityPermission(9876, 1234, new string[]{ "A", "B", "C" }) + new EntityPermission(9876, 1234, new string[] { "A", "B", "C" }) }; var permissionSet = new EntityPermissionSet(1234, permissions); userServiceMock.Setup(x => x.GetPermissionsForPath(user, "-1,1234,5678")).Returns(permissionSet); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent, new[] { 'F' }); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent, new[] { 'F' }); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Denied, result); } [Test] public void Access_Allowed_By_Permission() { - //arrange - var user = CreateUser(id: 9); + // Arrange + IUser user = CreateUser(id: 9); var contentMock = new Mock(); contentMock.Setup(c => c.Path).Returns("-1,1234,5678"); - var content = contentMock.Object; + IContent content = contentMock.Object; var contentServiceMock = new Mock(); contentServiceMock.Setup(x => x.GetById(1234)).Returns(content); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var permissions = new EntityPermissionCollection { - new EntityPermission(9876, 1234, new string[]{ "A", "F", "C" }) + new EntityPermission(9876, 1234, new string[] { "A", "F", "C" }) }; var permissionSet = new EntityPermissionSet(1234, permissions); var userServiceMock = new Mock(); userServiceMock.Setup(x => x.GetPermissionsForPath(user, "-1,1234,5678")).Returns(permissionSet); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent, new[] { 'F' }); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(1234, user, out IContent foundContent, new[] { 'F' }); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Granted, result); } [Test] public void Access_To_Root_By_Path() { - //arrange - var user = CreateUser(); + // Arrange + IUser user = CreateUser(); var contentServiceMock = new Mock(); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var userServiceMock = new Mock(); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(-1, user, out IContent _); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(-1, user, out IContent _); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Granted, result); } [Test] public void Access_To_Recycle_Bin_By_Path() { - //arrange - var user = CreateUser(); + // Arrange + IUser user = CreateUser(); var contentServiceMock = new Mock(); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var userServiceMock = new Mock(); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(-20, user, out IContent _); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(-20, user, out IContent _); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Granted, result); } [Test] public void No_Access_To_Recycle_Bin_By_Path() { - //arrange - var user = CreateUser(startContentId: 1234); + // Arrange + IUser user = CreateUser(startContentId: 1234); var contentServiceMock = new Mock(); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var userServiceMock = new Mock(); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); entityServiceMock.Setup(x => x.GetAllPaths(It.IsAny(), It.IsAny())) .Returns(new[] { Mock.Of(entity => entity.Id == 1234 && entity.Path == "-1,1234") }); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(-20, user, out IContent foundContent); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(-20, user, out IContent foundContent); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Denied, result); } [Test] public void No_Access_To_Root_By_Path() { - //arrange - var user = CreateUser(startContentId: 1234); + // Arrange + IUser user = CreateUser(startContentId: 1234); var contentServiceMock = new Mock(); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var userServiceMock = new Mock(); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); entityServiceMock.Setup(x => x.GetAllPaths(It.IsAny(), It.IsAny())) .Returns(new[] { Mock.Of(entity => entity.Id == 1234 && entity.Path == "-1,1234") }); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(-1, user, out IContent foundContent); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(-1, user, out IContent foundContent); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Denied, result); } [Test] public void Access_To_Root_By_Permission() { - //arrange - var user = CreateUser(); + // Arrange + IUser user = CreateUser(); var userServiceMock = new Mock(); var permissions = new EntityPermissionCollection { - new EntityPermission(9876, 1234, new string[]{ "A" }) + new EntityPermission(9876, 1234, new string[] { "A" }) }; var permissionSet = new EntityPermissionSet(1234, permissions); userServiceMock.Setup(x => x.GetPermissionsForPath(user, "-1")).Returns(permissionSet); var contentServiceMock = new Mock(); - var contentService = contentServiceMock.Object; - var userService = userServiceMock.Object; + IContentService contentService = contentServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(-1, user, out IContent foundContent, new[] { 'A' }); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(-1, user, out IContent foundContent, new[] { 'A' }); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Granted, result); } [Test] public void No_Access_To_Root_By_Permission() { - //arrange - var user = CreateUser(withUserGroup: false); + // Arrange + IUser user = CreateUser(withUserGroup: false); var userServiceMock = new Mock(); var permissions = new EntityPermissionCollection { - new EntityPermission(9876, 1234, new string[]{ "A" }) + new EntityPermission(9876, 1234, new string[] { "A" }) }; var permissionSet = new EntityPermissionSet(1234, permissions); userServiceMock.Setup(x => x.GetPermissionsForPath(user, "-1")).Returns(permissionSet); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentServiceMock = new Mock(); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(-1, user, out IContent foundContent, new[] { 'B' }); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(-1, user, out IContent foundContent, new[] { 'B' }); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Denied, result); } [Test] public void Access_To_Recycle_Bin_By_Permission() { - //arrange - var user = CreateUser(); + // Arrange + IUser user = CreateUser(); var userServiceMock = new Mock(); var permissions = new EntityPermissionCollection { - new EntityPermission(9876, 1234, new string[]{ "A" }) + new EntityPermission(9876, 1234, new string[] { "A" }) }; var permissionSet = new EntityPermissionSet(-20, permissions); userServiceMock.Setup(x => x.GetPermissionsForPath(user, "-20")).Returns(permissionSet); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentServiceMock = new Mock(); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(-20, user, out IContent foundContent, new[] { 'A' }); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(-20, user, out IContent foundContent, new[] { 'A' }); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Granted, result); } [Test] public void No_Access_To_Recycle_Bin_By_Permission() { - //arrange - var user = CreateUser(withUserGroup: false); + // Arrange + IUser user = CreateUser(withUserGroup: false); var userServiceMock = new Mock(); var permissions = new EntityPermissionCollection { - new EntityPermission(9876, 1234, new string[]{ "A" }) + new EntityPermission(9876, 1234, new string[] { "A" }) }; var permissionSet = new EntityPermissionSet(1234, permissions); userServiceMock.Setup(x => x.GetPermissionsForPath(user, "-20")).Returns(permissionSet); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var contentServiceMock = new Mock(); - var contentService = contentServiceMock.Object; + IContentService contentService = contentServiceMock.Object; var contentPermissions = new ContentPermissions(userService, contentService, entityService); - //act - var result = contentPermissions.CheckPermissions(-20, user, out IContent foundContent, new[] { 'B' }); + // Act + ContentPermissions.ContentAccess result = contentPermissions.CheckPermissions(-20, user, out IContent foundContent, new[] { 'B' }); - //assert + // Assert Assert.AreEqual(ContentPermissions.ContentAccess.Denied, result); } private IUser CreateUser(int id = 0, int? startContentId = null, bool withUserGroup = true) { - var builder = new UserBuilder() + UserBuilder builder = new UserBuilder() .WithId(id) .WithStartContentIds(startContentId.HasValue ? new[] { startContentId.Value } : new int[0]); if (withUserGroup) + { builder = builder .AddUserGroup() .WithId(1) .WithName("admin") .WithAlias("admin") .Done(); + } return builder.Build(); } } - } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/LegacyPasswordSecurityTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/LegacyPasswordSecurityTests.cs index c070657dd5..c41b2b60a0 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/LegacyPasswordSecurityTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/LegacyPasswordSecurityTests.cs @@ -1,4 +1,7 @@ -using Moq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Configuration; @@ -9,16 +12,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Security [TestFixture] public class LegacyPasswordSecurityTests { - [Test] public void Check_Password_Hashed_Non_KeyedHashAlgorithm() { - var passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == "SHA256"); + IPasswordConfiguration passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == "SHA256"); var passwordSecurity = new LegacyPasswordSecurity(); - string salt; var pass = "ThisIsAHashedPassword"; - var hashed = passwordSecurity.HashNewPassword(passwordConfiguration.HashAlgorithmType, pass, out salt); + var hashed = passwordSecurity.HashNewPassword(passwordConfiguration.HashAlgorithmType, pass, out string salt); var storedPassword = passwordSecurity.FormatPasswordForStorage(passwordConfiguration.HashAlgorithmType, hashed, salt); var result = passwordSecurity.VerifyPassword(passwordConfiguration.HashAlgorithmType, "ThisIsAHashedPassword", storedPassword); @@ -29,12 +30,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Security [Test] public void Check_Password_Hashed_KeyedHashAlgorithm() { - var passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName); + IPasswordConfiguration passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName); var passwordSecurity = new LegacyPasswordSecurity(); - string salt; var pass = "ThisIsAHashedPassword"; - var hashed = passwordSecurity.HashNewPassword(passwordConfiguration.HashAlgorithmType, pass, out salt); + var hashed = passwordSecurity.HashNewPassword(passwordConfiguration.HashAlgorithmType, pass, out string salt); var storedPassword = passwordSecurity.FormatPasswordForStorage(passwordConfiguration.HashAlgorithmType, hashed, salt); var result = passwordSecurity.VerifyPassword(passwordConfiguration.HashAlgorithmType, "ThisIsAHashedPassword", storedPassword); @@ -45,12 +45,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Security [Test] public void Check_Password_Legacy_v4_SHA1() { - var passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == Constants.Security.AspNetUmbraco4PasswordHashAlgorithmName); + IPasswordConfiguration passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == Constants.Security.AspNetUmbraco4PasswordHashAlgorithmName); var passwordSecurity = new LegacyPasswordSecurity(); - string salt; var pass = "ThisIsAHashedPassword"; - var hashed = passwordSecurity.HashNewPassword(passwordConfiguration.HashAlgorithmType, pass, out salt); + var hashed = passwordSecurity.HashNewPassword(passwordConfiguration.HashAlgorithmType, pass, out string salt); var storedPassword = passwordSecurity.FormatPasswordForStorage(passwordConfiguration.HashAlgorithmType, hashed, salt); var result = passwordSecurity.VerifyPassword(passwordConfiguration.HashAlgorithmType, "ThisIsAHashedPassword", storedPassword); @@ -61,7 +60,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Security [Test] public void Format_Pass_For_Storage_Hashed() { - var passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName); + IPasswordConfiguration passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName); var passwordSecurity = new LegacyPasswordSecurity(); var salt = LegacyPasswordSecurity.GenerateSalt(); @@ -75,14 +74,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Security [Test] public void Get_Stored_Password_Hashed() { - var passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName); + IPasswordConfiguration passwordConfiguration = Mock.Of(x => x.HashAlgorithmType == Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName); var passwordSecurity = new LegacyPasswordSecurity(); var salt = LegacyPasswordSecurity.GenerateSalt(); var stored = salt + "ThisIsAHashedPassword"; - string initSalt; - var result = passwordSecurity.ParseStoredHashPassword(passwordConfiguration.HashAlgorithmType, stored, out initSalt); + var result = passwordSecurity.ParseStoredHashPassword(passwordConfiguration.HashAlgorithmType, stored, out string initSalt); Assert.AreEqual("ThisIsAHashedPassword", result); } @@ -99,11 +97,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Security var result = LegacyPasswordSecurity.GenerateSalt(); if (i > 0) + { Assert.AreEqual(lastLength, result.Length); + } lastLength = result.Length; } } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/MediaPermissionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/MediaPermissionsTests.cs index c9b0324f06..52c37717d9 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/MediaPermissionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Security/MediaPermissionsTests.cs @@ -1,4 +1,7 @@ -using Moq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Moq; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; @@ -16,148 +19,147 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Security [Test] public void Access_Allowed_By_Path() { - //arrange - var user = CreateUser(id: 9); + // Arrange + IUser user = CreateUser(id: 9); var mediaMock = new Mock(); mediaMock.Setup(m => m.Path).Returns("-1,1234,5678"); - var media = mediaMock.Object; + IMedia media = mediaMock.Object; var mediaServiceMock = new Mock(); mediaServiceMock.Setup(x => x.GetById(1234)).Returns(media); - var mediaService = mediaServiceMock.Object; + IMediaService mediaService = mediaServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var mediaPermissions = new MediaPermissions(mediaService, entityService); - //act - var result = mediaPermissions.CheckPermissions(user, 1234, out _); + // Act + MediaPermissions.MediaAccess result = mediaPermissions.CheckPermissions(user, 1234, out _); - //assert + // Assert Assert.AreEqual(MediaPermissions.MediaAccess.Granted, result); } [Test] public void Returns_Not_Found_When_No_Media_Found() { - //arrange - var user = CreateUser(id: 9); + // Arrange + IUser user = CreateUser(id: 9); var mediaMock = new Mock(); mediaMock.Setup(m => m.Path).Returns("-1,1234,5678"); - var media = mediaMock.Object; + IMedia media = mediaMock.Object; var mediaServiceMock = new Mock(); mediaServiceMock.Setup(x => x.GetById(0)).Returns(media); - var mediaService = mediaServiceMock.Object; + IMediaService mediaService = mediaServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var mediaPermissions = new MediaPermissions(mediaService, entityService); - //act/assert - var result = mediaPermissions.CheckPermissions(user, 1234, out _); + // Act/assert + MediaPermissions.MediaAccess result = mediaPermissions.CheckPermissions(user, 1234, out _); Assert.AreEqual(MediaPermissions.MediaAccess.NotFound, result); } [Test] public void No_Access_By_Path() { - //arrange - var user = CreateUser(id: 9, startMediaId: 9876); + // Arrange + IUser user = CreateUser(id: 9, startMediaId: 9876); var mediaMock = new Mock(); mediaMock.Setup(m => m.Path).Returns("-1,1234,5678"); - var media = mediaMock.Object; + IMedia media = mediaMock.Object; var mediaServiceMock = new Mock(); mediaServiceMock.Setup(x => x.GetById(1234)).Returns(media); - var mediaService = mediaServiceMock.Object; + IMediaService mediaService = mediaServiceMock.Object; var entityServiceMock = new Mock(); entityServiceMock.Setup(x => x.GetAllPaths(It.IsAny(), It.IsAny())) .Returns(new[] { Mock.Of(entity => entity.Id == 9876 && entity.Path == "-1,9876") }); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var mediaPermissions = new MediaPermissions(mediaService, entityService); - //act - var result = mediaPermissions.CheckPermissions(user, 1234, out _); + // Act + MediaPermissions.MediaAccess result = mediaPermissions.CheckPermissions(user, 1234, out _); - //assert + // Assert Assert.AreEqual(MediaPermissions.MediaAccess.Denied, result); } [Test] public void Access_To_Root_By_Path() { - //arrange - var user = CreateUser(); + // Arrange + IUser user = CreateUser(); var mediaServiceMock = new Mock(); - var mediaService = mediaServiceMock.Object; + IMediaService mediaService = mediaServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var mediaPermissions = new MediaPermissions(mediaService, entityService); - //act - var result = mediaPermissions.CheckPermissions(user, -1, out _); + // Act + MediaPermissions.MediaAccess result = mediaPermissions.CheckPermissions(user, -1, out _); - //assert + // Assert Assert.AreEqual(MediaPermissions.MediaAccess.Granted, result); } [Test] public void No_Access_To_Root_By_Path() { - //arrange - var user = CreateUser(startMediaId: 1234); + // Arrange + IUser user = CreateUser(startMediaId: 1234); var mediaServiceMock = new Mock(); - var mediaService = mediaServiceMock.Object; + IMediaService mediaService = mediaServiceMock.Object; var entityServiceMock = new Mock(); entityServiceMock.Setup(x => x.GetAllPaths(It.IsAny(), It.IsAny())) .Returns(new[] { Mock.Of(entity => entity.Id == 1234 && entity.Path == "-1,1234") }); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var mediaPermissions = new MediaPermissions(mediaService, entityService); - //act - var result = mediaPermissions.CheckPermissions(user, -1, out _); + // Act + MediaPermissions.MediaAccess result = mediaPermissions.CheckPermissions(user, -1, out _); - //assert + // Assert Assert.AreEqual(MediaPermissions.MediaAccess.Denied, result); } [Test] public void Access_To_Recycle_Bin_By_Path() { - //arrange - var user = CreateUser(); + // Arrange + IUser user = CreateUser(); var mediaServiceMock = new Mock(); - var mediaService = mediaServiceMock.Object; + IMediaService mediaService = mediaServiceMock.Object; var entityServiceMock = new Mock(); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var mediaPermissions = new MediaPermissions(mediaService, entityService); - //act - var result = mediaPermissions.CheckPermissions(user, -21, out _); + // Act + MediaPermissions.MediaAccess result = mediaPermissions.CheckPermissions(user, -21, out _); - //assert + // Assert Assert.AreEqual(MediaPermissions.MediaAccess.Granted, result); } [Test] public void No_Access_To_Recycle_Bin_By_Path() { - //arrange - var user = CreateUser(startMediaId: 1234); + // Arrange + IUser user = CreateUser(startMediaId: 1234); var mediaServiceMock = new Mock(); - var mediaService = mediaServiceMock.Object; + IMediaService mediaService = mediaServiceMock.Object; var entityServiceMock = new Mock(); entityServiceMock.Setup(x => x.GetAllPaths(It.IsAny(), It.IsAny())) .Returns(new[] { Mock.Of(entity => entity.Id == 1234 && entity.Path == "-1,1234") }); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var mediaPermissions = new MediaPermissions(mediaService, entityService); - //act - var result = mediaPermissions.CheckPermissions(user, -21, out _); + // Act + MediaPermissions.MediaAccess result = mediaPermissions.CheckPermissions(user, -21, out _); - //assert + // Assert Assert.AreEqual(MediaPermissions.MediaAccess.Denied, result); } - private IUser CreateUser(int id = 0, int? startMediaId = null) - { - return new UserBuilder() + private IUser CreateUser(int id = 0, int? startMediaId = null) => + new UserBuilder() .WithId(id) .WithStartMediaIds(startMediaId.HasValue ? new[] { startMediaId.Value } : new int[0]) .AddUserGroup() @@ -166,6 +168,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Security .WithAlias("admin") .Done() .Build(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Services/ContentTypeServiceExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Services/ContentTypeServiceExtensionsTests.cs index 171a71b114..af91e78afa 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Services/ContentTypeServiceExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Services/ContentTypeServiceExtensionsTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using Moq; using NUnit.Framework; @@ -7,7 +10,6 @@ using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Tests.Common.Builders; -using Umbraco.Tests.TestHelpers.Entities; namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services { @@ -19,24 +21,24 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services [Test] public void GetAvailableCompositeContentTypes_No_Overlap_By_Content_Type_And_Property_Type_Alias() { - Action addPropType = (alias, ct) => + void AddPropType(string alias, IContentType ct) { var contentCollection = new PropertyTypeCollection(true) { - new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) {Alias = alias, Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88} + new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = alias, Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 } }; var pg = new PropertyGroup(contentCollection) { Name = "test", SortOrder = 1 }; ct.PropertyGroups.Add(pg); - }; + } - var ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1", null); - var ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", null); - addPropType("title", ct2); - var ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3", null); - addPropType("title", ct3); - var ct4 = ContentTypeBuilder.CreateBasicContentType("ct4", "CT4", null); - var ct5 = ContentTypeBuilder.CreateBasicContentType("ct5", "CT5", null); - addPropType("blah", ct5); + ContentType ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1", null); + ContentType ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", null); + AddPropType("title", ct2); + ContentType ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3", null); + AddPropType("title", ct3); + ContentType ct4 = ContentTypeBuilder.CreateBasicContentType("ct4", "CT4", null); + ContentType ct5 = ContentTypeBuilder.CreateBasicContentType("ct5", "CT5", null); + AddPropType("blah", ct5); ct1.Id = 1; ct2.Id = 2; ct3.Id = 3; @@ -45,7 +47,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services var service = new Mock(); - var availableTypes = service.Object.GetAvailableCompositeContentTypes( + IContentTypeComposition[] availableTypes = service.Object.GetAvailableCompositeContentTypes( ct1, new[] { ct1, ct2, ct3, ct4, ct5 }, new[] { ct2.Alias }, @@ -59,22 +61,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services [Test] public void GetAvailableCompositeContentTypes_No_Overlap_By_Property_Type_Alias() { - Action addPropType = ct => + void AddPropType(IContentType ct) { var contentCollection = new PropertyTypeCollection(true) { - new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) {Alias = "title", Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88} + new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "title", Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 } }; var pg = new PropertyGroup(contentCollection) { Name = "test", SortOrder = 1 }; ct.PropertyGroups.Add(pg); - }; + } - var ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1", null); - var ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", null); - addPropType(ct2); - var ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3", null); - addPropType(ct3); - var ct4 = ContentTypeBuilder.CreateBasicContentType("ct4", "CT4", null); + ContentType ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1", null); + ContentType ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", null); + AddPropType(ct2); + ContentType ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3", null); + AddPropType(ct3); + ContentType ct4 = ContentTypeBuilder.CreateBasicContentType("ct4", "CT4", null); ct1.Id = 1; ct2.Id = 2; ct3.Id = 3; @@ -82,7 +84,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services var service = new Mock(); - var availableTypes = service.Object.GetAvailableCompositeContentTypes( + IContentTypeComposition[] availableTypes = service.Object.GetAvailableCompositeContentTypes( ct1, new[] { ct1, ct2, ct3, ct4 }, new string[] { }, @@ -96,22 +98,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services [Test] public void GetAvailableCompositeContentTypes_No_Overlap_By_Content_Type() { - Action addPropType = ct => + void AddPropType(IContentType ct) { var contentCollection = new PropertyTypeCollection(true) { - new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) {Alias = "title", Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88} + new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "title", Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 } }; var pg = new PropertyGroup(contentCollection) { Name = "test", SortOrder = 1 }; ct.PropertyGroups.Add(pg); - }; + } - var ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1", null); - var ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", null); - addPropType(ct2); - var ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3", null); - addPropType(ct3); - var ct4 = ContentTypeBuilder.CreateBasicContentType("ct4", "CT4", null); + ContentType ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1", null); + ContentType ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", null); + AddPropType(ct2); + ContentType ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3", null); + AddPropType(ct3); + ContentType ct4 = ContentTypeBuilder.CreateBasicContentType("ct4", "CT4", null); ct1.Id = 1; ct2.Id = 2; ct3.Id = 3; @@ -119,10 +121,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services var service = new Mock(); - var availableTypes = service.Object.GetAvailableCompositeContentTypes( + IContentTypeComposition[] availableTypes = service.Object.GetAvailableCompositeContentTypes( ct1, new[] { ct1, ct2, ct3, ct4 }, - new [] {ct2.Alias}) + new[] { ct2.Alias }) .Results.Where(x => x.Allowed).Select(x => x.Composition).ToArray(); Assert.AreEqual(1, availableTypes.Count()); @@ -132,18 +134,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services [Test] public void GetAvailableCompositeContentTypes_Not_Itself() { - var ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1", null); - var ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", null); - var ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3", null); + ContentType ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1", null); + ContentType ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", null); + ContentType ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3", null); ct1.Id = 1; ct2.Id = 2; ct3.Id = 3; var service = new Mock(); - var availableTypes = service.Object.GetAvailableCompositeContentTypes( + IContentTypeComposition[] availableTypes = service.Object.GetAvailableCompositeContentTypes( ct1, - new[] {ct1, ct2, ct3}) + new[] { ct1, ct2, ct3 }) .Results.Where(x => x.Allowed).Select(x => x.Composition).ToArray(); Assert.AreEqual(2, availableTypes.Count()); @@ -151,33 +153,33 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services Assert.AreEqual(ct3.Id, availableTypes.ElementAt(1).Id); } - //This shows that a nested comp is not allowed + // This shows that a nested comp is not allowed [Test] public void GetAvailableCompositeContentTypes_No_Results_If_Already_A_Composition_By_Parent() { - var ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); + ContentType ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); ct1.Id = 1; - var ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", ct1); + ContentType ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2", ct1); ct2.Id = 2; - var ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); + ContentType ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); ct3.Id = 3; var service = new Mock(); - var availableTypes = service.Object.GetAvailableCompositeContentTypes( + System.Collections.Generic.IEnumerable availableTypes = service.Object.GetAvailableCompositeContentTypes( ct1, new[] { ct1, ct2, ct3 }).Results; Assert.AreEqual(0, availableTypes.Count()); } - //This shows that a nested comp is not allowed + // This shows that a nested comp is not allowed [Test] public void GetAvailableCompositeContentTypes_No_Results_If_Already_A_Composition() { - var ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); - var ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2"); - var ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); + ContentType ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); + ContentType ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2"); + ContentType ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); ct1.Id = 1; ct2.Id = 2; ct3.Id = 3; @@ -186,7 +188,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services var service = new Mock(); - var availableTypes = service.Object.GetAvailableCompositeContentTypes( + System.Collections.Generic.IEnumerable availableTypes = service.Object.GetAvailableCompositeContentTypes( ct1, new[] { ct1, ct2, ct3 }).Results; @@ -196,9 +198,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services [Test] public void GetAvailableCompositeContentTypes_Do_Not_Include_Other_Composed_Types() { - var ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); - var ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2"); - var ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); + ContentType ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); + ContentType ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2"); + ContentType ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); ct1.Id = 1; ct2.Id = 2; ct3.Id = 3; @@ -207,7 +209,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services var service = new Mock(); - var availableTypes = service.Object.GetAvailableCompositeContentTypes( + IContentTypeComposition[] availableTypes = service.Object.GetAvailableCompositeContentTypes( ct1, new[] { ct1, ct2, ct3 }) .Results.Where(x => x.Allowed).Select(x => x.Composition).ToArray(); @@ -219,9 +221,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services [Test] public void GetAvailableCompositeContentTypes_Include_Direct_Composed_Types() { - var ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); - var ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2"); - var ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); + ContentType ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); + ContentType ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2"); + ContentType ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); ct1.Id = 1; ct2.Id = 2; ct3.Id = 3; @@ -230,7 +232,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services var service = new Mock(); - var availableTypes = service.Object.GetAvailableCompositeContentTypes( + IContentTypeComposition[] availableTypes = service.Object.GetAvailableCompositeContentTypes( ct1, new[] { ct1, ct2, ct3 }) .Results.Where(x => x.Allowed).Select(x => x.Composition).ToArray(); @@ -243,21 +245,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Services [Test] public void GetAvailableCompositeContentTypes_Include_Indirect_Composed_Types() { - var ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); - var ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2"); - var ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); - var ct4 = ContentTypeBuilder.CreateBasicContentType("ct4", "CT4"); + ContentType ct1 = ContentTypeBuilder.CreateBasicContentType("ct1", "CT1"); + ContentType ct2 = ContentTypeBuilder.CreateBasicContentType("ct2", "CT2"); + ContentType ct3 = ContentTypeBuilder.CreateBasicContentType("ct3", "CT3"); + ContentType ct4 = ContentTypeBuilder.CreateBasicContentType("ct4", "CT4"); ct1.Id = 1; ct2.Id = 2; ct3.Id = 3; ct4.Id = 4; - ct1.AddContentType(ct3); //ct3 is direct to ct1 - ct3.AddContentType(ct4); //ct4 is indirect to ct1 + ct1.AddContentType(ct3); // ct3 is direct to ct1 + ct3.AddContentType(ct4); // ct4 is indirect to ct1 var service = new Mock(); - var availableTypes = service.Object.GetAvailableCompositeContentTypes( + IContentTypeComposition[] availableTypes = service.Object.GetAvailableCompositeContentTypes( ct1, new[] { ct1, ct2, ct3 }) .Results.Where(x => x.Allowed).Select(x => x.Composition).ToArray(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/CmsHelperCasingTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/CmsHelperCasingTests.cs index 5be6a58692..9dabbc7f36 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/CmsHelperCasingTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/CmsHelperCasingTests.cs @@ -1,14 +1,11 @@ -using Microsoft.Extensions.Options; -using Moq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.Extensions.Options; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Configuration.Models; -using Umbraco.Core.Configuration.Models; -using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Strings; -using Umbraco.Tests.Common.Builders; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.Testing; namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper { @@ -22,7 +19,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase("t", "t")] [TestCase("thisis", "Thisis")] [TestCase("ThisIsTheEnd", "This Is The End")] - //[TestCase("WhoIsNumber6InTheVillage", "Who Is Number6In The Village")] // note the issue with Number6In + //// [TestCase("WhoIsNumber6InTheVillage", "Who Is Number6In The Village")] // note the issue with Number6In [TestCase("WhoIsNumber6InTheVillage", "Who Is Number6 In The Village")] // now fixed since DefaultShortStringHelper is the default public void SpaceCamelCasing(string input, string expected) { @@ -38,7 +35,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase("WhoIsNumber6InTheVillage", "Who Is Number6 In The Village")] // issue is fixed public void CompatibleDefaultReplacement(string input, string expected) { - var output = input.Length < 2 ? input : ShortStringHelper.SplitPascalCasing(input, ' ').ToFirstUpperInvariant(); Assert.AreEqual(expected, output); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/DefaultShortStringHelperTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/DefaultShortStringHelperTests.cs index 3241285fec..b6380ecfa5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/DefaultShortStringHelperTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/DefaultShortStringHelperTests.cs @@ -1,17 +1,12 @@ -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Text.RegularExpressions; -using Moq; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Composing; using Umbraco.Core.Configuration.Models; -using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Strings; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.Testing; namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper { @@ -21,16 +16,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper private IShortStringHelper ShortStringHelper { get; set; } [SetUp] - public void SetUp() - { + public void SetUp() => // NOTE pre-filters runs _before_ Recode takes place // so there still may be utf8 chars even though you want ascii - ShortStringHelper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(new RequestHandlerSettings()) .WithConfig(CleanStringType.FileName, new DefaultShortStringHelperConfig.Config { - //PreFilter = ClearFileChars, // done in IsTerm + // PreFilter = ClearFileChars, // done in IsTerm IsTerm = (c, leading) => (char.IsLetterOrDigit(c) || c == '_') && DefaultShortStringHelper.IsValidFileNameChar(c), StringType = CleanStringType.LowerCase | CleanStringType.Ascii, Separator = '-' @@ -68,18 +61,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper StringType = CleanStringType.Ascii, BreakTermsOnUpper = true })); - } - private static readonly Regex FrenchElisionsRegex = new Regex("\\b(c|d|j|l|m|n|qu|s|t)('|\u8217)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private static readonly Regex s_frenchElisionsRegex = new Regex("\\b(c|d|j|l|m|n|qu|s|t)('|\u8217)", RegexOptions.Compiled | RegexOptions.IgnoreCase); - private static string FilterFrenchElisions(string s) - { - return FrenchElisionsRegex.Replace(s, ""); - } + private static string FilterFrenchElisions(string s) => s_frenchElisionsRegex.Replace(s, string.Empty); private static string StripQuotes(string s) { - s = s.ReplaceMany(new Dictionary {{"'", ""}, {"\u8217", ""}}); + s = s.ReplaceMany(new Dictionary { { "'", string.Empty }, { "\u8217", string.Empty } }); return s; } @@ -89,7 +78,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper return s; } - #region Cases [TestCase("foo", "foo")] [TestCase(" foo ", "foo")] [TestCase("Foo", "Foo")] @@ -121,14 +109,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase("whatIfWeDoItAgain", "whatIfWeDoItAgain")] [TestCase("WhatIfWEDOITAgain", "WhatIfWEDOITAgain")] [TestCase("WhatIfWe doItAgain", "WhatIfWeDoItAgain")] - #endregion public void CleanStringForSafeAlias(string input, string expected) { var output = ShortStringHelper.CleanStringForSafeAlias(input); Assert.AreEqual(expected, output); } - #region Cases [TestCase("Home Page", "home-page")] [TestCase("Shannon's Home Page!", "shannons-home-page")] [TestCase("#Someones's Twitter $h1z%n", "someoness-twitter-h1z-n")] @@ -137,14 +123,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase("汉#字*/漢?字", "")] [TestCase("Réalösk fix bran#lo'sk", "realosk-fix-bran-losk")] [TestCase("200 ways to be happy", "200-ways-to-be-happy")] - #endregion public void CleanStringForUrlSegment(string input, string expected) { var output = ShortStringHelper.CleanStringForUrlSegment(input); Assert.AreEqual(expected, output); } - #region Cases [TestCase("ThisIsTheEndMyFriend", "This Is The End My Friend")] [TestCase("ThisIsTHEEndMyFriend", "This Is THE End My Friend")] [TestCase("THISIsTHEEndMyFriend", "THIS Is THE End My Friend")] @@ -153,7 +137,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase("ThisIsTHEEndMyFriendXYZ", "This Is THE End My Friend XYZ")] [TestCase("ThisIsTHEEndMyFriendXYZt", "This Is THE End My Friend XY Zt")] [TestCase("UneÉlévationÀPartir", "Une Élévation À Partir")] - #endregion public void SplitPascalCasing(string input, string expected) { var output = ShortStringHelper.SplitPascalCasing(input, ' '); @@ -164,13 +147,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper Assert.AreEqual(expected, output); } - #region Cases [TestCase("sauté dans l'espace", "saute-dans-espace", "fr-FR", CleanStringType.UrlSegment | CleanStringType.Ascii | CleanStringType.LowerCase)] [TestCase("sauté dans l'espace", "sauté-dans-espace", "fr-FR", CleanStringType.UrlSegment | CleanStringType.Utf8 | CleanStringType.LowerCase)] [TestCase("sauté dans l'espace", "SauteDansLEspace", "fr-FR", CleanStringType.Alias | CleanStringType.Ascii | CleanStringType.PascalCase)] [TestCase("he doesn't want", "he-doesnt-want", null, CleanStringType.UrlSegment | CleanStringType.Ascii | CleanStringType.LowerCase)] [TestCase("he doesn't want", "heDoesntWant", null, CleanStringType.Alias | CleanStringType.Ascii | CleanStringType.CamelCase)] - #endregion public void CleanStringWithTypeAndCulture(string input, string expected, string culture, CleanStringType stringType) { // picks the proper config per culture @@ -179,7 +160,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper Assert.AreEqual(expected, output); } - #region Cases [TestCase("foo.txt", "foo.txt")] [TestCase("foo", "foo")] [TestCase(".txt", ".txt")] @@ -192,7 +172,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase("yop.Straße Zvöskî", "yop.strasse-zvoski")] [TestCase("yop.Straße Zvös--kî", "yop.strasse-zvos-ki")] [TestCase("ma--ma---ma.ma-----ma", "ma-ma-ma.ma-ma")] - #endregion public void CleanStringForSafeFileName(string input, string expected) { var output = ShortStringHelper.CleanStringForSafeFileName(input); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/DefaultShortStringHelperTestsWithoutSetup.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/DefaultShortStringHelperTestsWithoutSetup.cs index 98e00a69ef..f8b6f258e0 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/DefaultShortStringHelperTestsWithoutSetup.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/DefaultShortStringHelperTestsWithoutSetup.cs @@ -1,7 +1,9 @@ -using System.Diagnostics; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Diagnostics; using System.Linq; using System.Text; -using Moq; using NUnit.Framework; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; @@ -13,7 +15,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestFixture] public class DefaultShortStringHelperTestsWithoutSetup { - [Test] public void U4_4056() { @@ -115,7 +116,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper Assert.AreEqual("foo*bar*543*nil*321", helper.CleanString("0123foo_bar 543 nil 321", CleanStringType.Alias)); Assert.AreEqual("foo*bar*543*nil*321", helper.CleanString("0123 foo_bar 543 nil 321", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(new RequestHandlerSettings() )); + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(new RequestHandlerSettings())); Assert.AreEqual("child2", helper.CleanStringForSafeAlias("1child2")); } @@ -126,6 +127,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, + // uppercase letter means new term BreakTermsOnUpper = true, Separator = '*' @@ -136,6 +138,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, + // uppercase letter is part of term BreakTermsOnUpper = false, Separator = '*' @@ -150,6 +153,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, + // non-uppercase letter means cut acronym CutAcronymOnNonUpper = true, Separator = '*' @@ -163,6 +167,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, + // non-uppercase letter means word CutAcronymOnNonUpper = false, Separator = '*' @@ -287,12 +292,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper var bytes = Encoding.UTF8.GetBytes(str); Assert.AreEqual(10, bytes.Length); Assert.AreEqual('a', bytes[0]); - // then next string element is two chars (surrogate pair) or 4 bytes, 21 bits of code point + + // Then next string element is two chars (surrogate pair) or 4 bytes, 21 bits of code point. Assert.AreEqual('z', bytes[5]); - // then next string element is one char and 3 bytes, 16 bits of code point + + // Then next string element is one char and 3 bytes, 16 bits of code point. Assert.AreEqual('t', bytes[9]); - //foreach (var b in bytes) - // Debug.Print("{0:X}", b); + + //// foreach (var b in bytes) + //// Debug.Print("{0:X}", b); Debug.Print("\U00010B70"); } @@ -323,7 +331,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper StringType = CleanStringType.Ascii | CleanStringType.Unchanged, Separator = '*' })); - Assert.AreEqual("", helper.CleanString("中文测试", CleanStringType.Alias)); + Assert.AreEqual(string.Empty, helper.CleanString("中文测试", CleanStringType.Alias)); Assert.AreEqual("leger*ZORG", helper.CleanString("léger 中文测试 ZÔRG", CleanStringType.Alias)); } @@ -370,7 +378,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper // FIXME: "C" can't be an acronym // FIXME: "DBXreview" = acronym?! - Assert.AreEqual("aaa BBB CCc Ddd E FF", helper.CleanString("aaa BBB CCc Ddd E FF", CleanStringType.Alias)); // unchanged Assert.AreEqual("aaa Bbb Ccc Ddd E FF", helper.CleanString("aaa BBB CCc Ddd E FF", CleanStringType.Alias | CleanStringType.CamelCase)); Assert.AreEqual("Aaa Bbb Ccc Ddd E FF", helper.CleanString("aaa BBB CCc Ddd E FF", CleanStringType.Alias | CleanStringType.PascalCase)); @@ -385,7 +392,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper // eg "XmlWriter (pascal) or "htmlReader" (camel) - "SpecialXmlWriter" (pascal) or "specialHtmlReader" (camel) // - Do not capitalize any of the characters of any acronyms, whatever their length, at the beginning of a camel-cased identifier. // eg "xmlWriter" or "dbWriter" (camel) - Assert.AreEqual("aaa BB Ccc", helper.CleanString("aaa BB ccc", CleanStringType.Alias | CleanStringType.CamelCase)); Assert.AreEqual("aa Bb Ccc", helper.CleanString("AA bb ccc", CleanStringType.Alias | CleanStringType.CamelCase)); Assert.AreEqual("aaa Bb Ccc", helper.CleanString("AAA bb ccc", CleanStringType.Alias | CleanStringType.CamelCase)); @@ -426,6 +432,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper // var output = helper.CleanString(input, CleanStringType.Alias | CleanStringType.Ascii | CleanStringType.CamelCase); // Assert.AreEqual(expected, output); // } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/MockShortStringHelper.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/MockShortStringHelper.cs index 442a655805..ac17cb1199 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/MockShortStringHelper.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/MockShortStringHelper.cs @@ -1,69 +1,36 @@ -using Umbraco.Core.Strings; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Strings; namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper { - class MockShortStringHelper : IShortStringHelper + internal class MockShortStringHelper : IShortStringHelper { - public void Freeze() - { - IsFrozen = true; - } + public void Freeze() => IsFrozen = true; public bool IsFrozen { get; private set; } - public string CleanStringForSafeAlias(string text) - { - return "SAFE-ALIAS::" + text; - } + public string CleanStringForSafeAlias(string text) => "SAFE-ALIAS::" + text; - public string CleanStringForSafeAlias(string text, string culture) - { - return "SAFE-ALIAS-CULTURE::" + text; - } + public string CleanStringForSafeAlias(string text, string culture) => "SAFE-ALIAS-CULTURE::" + text; - public string CleanStringForUrlSegment(string text) - { - return "URL-SEGMENT::" + text; - } + public string CleanStringForUrlSegment(string text) => "URL-SEGMENT::" + text; - public string CleanStringForUrlSegment(string text, string culture) - { - return "URL-SEGMENT-CULTURE::" + text; - } + public string CleanStringForUrlSegment(string text, string culture) => "URL-SEGMENT-CULTURE::" + text; - public string CleanStringForSafeFileName(string text) - { - return "SAFE-FILE-NAME::" + text; - } + public string CleanStringForSafeFileName(string text) => "SAFE-FILE-NAME::" + text; - public string CleanStringForSafeFileName(string text, string culture) - { - return "SAFE-FILE-NAME-CULTURE::" + text; - } + public string CleanStringForSafeFileName(string text, string culture) => "SAFE-FILE-NAME-CULTURE::" + text; - public string SplitPascalCasing(string text, char separator) - { - return "SPLIT-PASCAL-CASING::" + text; - } + public string SplitPascalCasing(string text, char separator) => "SPLIT-PASCAL-CASING::" + text; - public string CleanString(string text, CleanStringType stringType) - { - return "CLEAN-STRING-A::" + text; - } + public string CleanString(string text, CleanStringType stringType) => "CLEAN-STRING-A::" + text; - public string CleanString(string text, CleanStringType stringType, char separator) - { - return "CLEAN-STRING-B::" + text; - } + public string CleanString(string text, CleanStringType stringType, char separator) => "CLEAN-STRING-B::" + text; - public string CleanString(string text, CleanStringType stringType, string culture) - { - return "CLEAN-STRING-C::" + text; - } + public string CleanString(string text, CleanStringType stringType, string culture) => "CLEAN-STRING-C::" + text; - public string CleanString(string text, CleanStringType stringType, char separator, string culture) - { - return "CLEAN-STRING-D::" + text; - } + public string CleanString(string text, CleanStringType stringType, char separator, string culture) => "CLEAN-STRING-D::" + text; } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringExtensionsTests.cs index 03c84a03b8..19103c2ec6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringExtensionsTests.cs @@ -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.Linq; @@ -19,10 +22,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase("hello-world.png", "Hello World")] [TestCase("hello-world .png", "Hello World")] [TestCase("_hello-world __1.png", "Hello World 1")] - public void To_Friendly_Name(string first, string second) - { - Assert.AreEqual(first.ToFriendlyName(), second); - } + public void To_Friendly_Name(string first, string second) => Assert.AreEqual(first.ToFriendlyName(), second); [TestCase("hello", "world", false)] [TestCase("hello", "hello", true)] @@ -45,7 +45,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase("/Test.js function(){return true;}", false)] public void Detect_Is_JavaScript_Path(string input, bool result) { - var output = input.DetectIsJavaScriptPath(Mock.Of()); + Attempt output = input.DetectIsJavaScriptPath(Mock.Of()); Assert.AreEqual(result, output.Success); } @@ -114,6 +114,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase("Hello this is hello my string", "hello", "replaced", "replaced this is replaced my string", StringComparison.CurrentCultureIgnoreCase)] [TestCase("Hello this is my string", "nonexistent", "replaced", "Hello this is my string", StringComparison.CurrentCultureIgnoreCase)] [TestCase("Hellohello this is my string", "hello", "replaced", "replacedreplaced this is my string", StringComparison.CurrentCultureIgnoreCase)] + // Ensure replacing with the same string doesn't cause infinite loop. [TestCase("Hello this is my string", "hello", "hello", "hello this is my string", StringComparison.CurrentCultureIgnoreCase)] public void ReplaceWithStringComparison(string input, string oldString, string newString, string shouldBe, StringComparison stringComparison) @@ -161,7 +162,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [TestCase(" ", true)] [TestCase("\r\n\r\n", true)] [TestCase("\r\n", true)] - [TestCase(@" + [TestCase( + @" Hello ", false)] [TestCase(null, true)] @@ -300,6 +302,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper var output = input.ReplaceMany(toReplace.ToArray(), replacement); Assert.AreEqual(expected, output); } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringValidationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringValidationTests.cs index cc786413f3..80eaf2df98 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringValidationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringValidationTests.cs @@ -1,7 +1,8 @@ -using System.ComponentModel.DataAnnotations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.ComponentModel.DataAnnotations; using NUnit.Framework; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.Testing; namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper { @@ -30,8 +31,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper // // since Umbraco is now 4.7.2+, the setting is required for the following tests to pass - //[TestCase("fdsa@fdsa", ExpectedResult = false)] - //[TestCase("fdsa@fdsa.", ExpectedResult = false)] + // [TestCase("fdsa@fdsa", ExpectedResult = false)] + // [TestCase("fdsa@fdsa.", ExpectedResult = false)] public bool Validate_Email_Address(string input) { var foo = new EmailAddressAttribute(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StylesheetHelperTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StylesheetHelperTests.cs index 950a103560..8be740a9a0 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StylesheetHelperTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StylesheetHelperTests.cs @@ -1,4 +1,8 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Strings.Css; @@ -11,33 +15,35 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.ShortStringHelper [Test] public void Replace_Rule() { - var css = @"body {font-family:Arial;}/** Umb_Name: Test1 */ p { font-size: 1em; } /** umb_name: Test2 */ li {padding:0px;} table {margin:0;}"; - var results = StylesheetHelper.ParseRules(css); + string css = @"body {font-family:Arial;}/** Umb_Name: Test1 */ p { font-size: 1em; } /** umb_name: Test2 */ li {padding:0px;} table {margin:0;}"; + IEnumerable results = StylesheetHelper.ParseRules(css); - var result = StylesheetHelper.ReplaceRule(css, results.First().Name, new StylesheetRule() + string result = StylesheetHelper.ReplaceRule(css, results.First().Name, new StylesheetRule() { Name = "My new rule", Selector = "p", Styles = "font-size:1em; color:blue;" }); - Assert.AreEqual(@"body {font-family:Arial;}/**umb_name:My new rule*/ + Assert.AreEqual( + @"body {font-family:Arial;}/**umb_name:My new rule*/ p{font-size:1em; color:blue;} /** umb_name: Test2 */ li {padding:0px;} table {margin:0;}".StripWhitespace(), result.StripWhitespace()); } [Test] public void Append_Rule() { - var css = @"body {font-family:Arial;}/** Umb_Name: Test1 */ p { font-size: 1em; } /** umb_name: Test2 */ li {padding:0px;} table {margin:0;}"; + string css = @"body {font-family:Arial;}/** Umb_Name: Test1 */ p { font-size: 1em; } /** umb_name: Test2 */ li {padding:0px;} table {margin:0;}"; - var result = StylesheetHelper.AppendRule(css, new StylesheetRule() + string result = StylesheetHelper.AppendRule(css, new StylesheetRule() { Name = "My new rule", Selector = "p", Styles = "font-size:1em; color:blue;" }); - Assert.AreEqual(@"body {font-family:Arial;}/** Umb_Name: Test1 */ p { font-size: 1em; } /** umb_name: Test2 */ li {padding:0px;} table {margin:0;} + Assert.AreEqual( + @"body {font-family:Arial;}/** Umb_Name: Test1 */ p { font-size: 1em; } /** umb_name: Test2 */ li {padding:0px;} table {margin:0;} /**umb_name:My new rule*/ p{font-size:1em; color:blue;}".StripWhitespace(), result.StripWhitespace()); @@ -46,8 +52,8 @@ p{font-size:1em; color:blue;}".StripWhitespace(), result.StripWhitespace()); [Test] public void Duplicate_Names() { - var css = @"/** Umb_Name: Test */ p { font-size: 1em; } /** umb_name: Test */ li {padding:0px;}"; - var results = StylesheetHelper.ParseRules(css); + string css = @"/** Umb_Name: Test */ p { font-size: 1em; } /** umb_name: Test */ li {padding:0px;}"; + IEnumerable results = StylesheetHelper.ParseRules(css); Assert.AreEqual(1, results.Count()); } @@ -85,14 +91,13 @@ font-size: 1em; }")] public void ParseRules_Parses(string name, string selector, string styles, string css) { - // Act - var results = StylesheetHelper.ParseRules(css); + IEnumerable results = StylesheetHelper.ParseRules(css); // Assert Assert.AreEqual(1, results.Count()); - //Assert.IsTrue(results.First().RuleId.Value.Value.ToString() == file.Id.Value.Value + "/" + name); + // Assert.IsTrue(results.First().RuleId.Value.Value.ToString() == file.Id.Value.Value + "/" + name); Assert.AreEqual(name, results.First().Name); Assert.AreEqual(selector, results.First().Selector); Assert.AreEqual(styles.StripWhitespace(), results.First().Styles.StripWhitespace()); @@ -104,26 +109,29 @@ p { font-size: 1em; }")] + // Has a Name: keyword, but applies to 2 rules, so shouldn't parse [TestCase(@"/** umb_name: Test2 */ p, h2 { font-size: 1em; }")] + // Has it's name wrapping over two lines [TestCase("/** umb_name: Test\r\n2 */ p { font-size: 1em; }")] [TestCase("/** umb_name: Test\n2 */ p { font-size: 1em; }")] - //Only a single asterisk + + // Only a single asterisk [TestCase("/* umb_name: Test */ p { font-size: 1em; }")] + // Has a name with spaces over multiple lines [TestCase(@"/**UMB_NAME:Hello world */p{font-size: 1em;}")] public void ParseRules_DoesntParse(string css) { - // Act - var results = StylesheetHelper.ParseRules(css); + IEnumerable results = StylesheetHelper.ParseRules(css); // Assert Assert.IsTrue(results.Any() == false); @@ -133,12 +141,12 @@ world */p{font-size: 1em;}")] public void AppendRules_IsFormatted() { // base CSS - var css = Tabbed( + string css = Tabbed( @"body { #font-family:Arial; }"); // add a couple of rules - var result = StylesheetHelper.AppendRule(css, new StylesheetRule + string result = StylesheetHelper.AppendRule(css, new StylesheetRule { Name = "Test", Selector = ".test", @@ -152,7 +160,8 @@ world */p{font-size: 1em;}")] }); // verify the CSS formatting including the indents - Assert.AreEqual(Tabbed( + Assert.AreEqual( + Tabbed( @"body { #font-family:Arial; } @@ -166,15 +175,14 @@ world */p{font-size: 1em;}")] /**umb_name:Test2*/ .test2 { #font-color: green; -}"), result - ); +}"), result); } [Test] public void ParseFormattedRules_CanParse() { // base CSS - var css = Tabbed( + string css = Tabbed( @"body { #font-family:Arial; } @@ -189,7 +197,7 @@ world */p{font-size: 1em;}")] .test2 { #font-color: green; }"); - var rules = StylesheetHelper.ParseRules(css); + IEnumerable rules = StylesheetHelper.ParseRules(css); Assert.AreEqual(2, rules.Count()); Assert.AreEqual("Test", rules.First().Name); @@ -206,6 +214,5 @@ margin: 1rem;", rules.First().Styles); // can't put tabs in verbatim strings, so this will replace # with \t to test the CSS indents // - and it's tabs because the editor uses tabs, not spaces... private static string Tabbed(string input) => input.Replace("#", "\t"); - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/HtmlImageSourceParserTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/HtmlImageSourceParserTests.cs index 542d273954..b49a229133 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/HtmlImageSourceParserTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/HtmlImageSourceParserTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Diagnostics; using System.Linq; using Microsoft.Extensions.Options; @@ -10,6 +13,7 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Tests.Common; using Umbraco.Tests.UnitTests.TestHelpers.Objects; +using Umbraco.Web; using Umbraco.Web.Routing; using Umbraco.Web.Templates; @@ -48,7 +52,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates

"); - Assert.AreEqual(@"

+ Assert.AreEqual( + @"

@@ -60,8 +65,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates [Test] public void Ensure_Image_Sources() { - //setup a mock URL provider which we'll use for testing - + // setup a mock URL provider which we'll use for testing var mediaType = new PublishedContentType(Guid.NewGuid(), 777, "image", PublishedItemType.Media, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); var media = new Mock(); media.Setup(x => x.ContentType).Returns(mediaType); @@ -71,17 +75,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates var umbracoContextAccessor = new TestUmbracoContextAccessor(); - var umbracoContextFactory = TestUmbracoContextFactory.Create( + IUmbracoContextFactory umbracoContextFactory = TestUmbracoContextFactory.Create( umbracoContextAccessor: umbracoContextAccessor); var webRoutingSettings = new WebRoutingSettings(); - var publishedUrlProvider = new UrlProvider(umbracoContextAccessor, + var publishedUrlProvider = new UrlProvider( + umbracoContextAccessor, Options.Create(webRoutingSettings), new UrlProviderCollection(Enumerable.Empty()), - new MediaUrlProviderCollection(new []{mediaUrlProvider.Object}), - Mock.Of() - ); - using (var reference = umbracoContextFactory.EnsureUmbracoContext()) + new MediaUrlProviderCollection(new[] { mediaUrlProvider.Object }), + Mock.Of()); + using (UmbracoContextReference reference = umbracoContextFactory.EnsureUmbracoContext()) { var mediaCache = Mock.Get(reference.UmbracoContext.Media); mediaCache.Setup(x => x.GetById(It.IsAny())).Returns(media.Object); @@ -99,7 +103,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates

"); - Assert.AreEqual(@"

+ Assert.AreEqual( + @"

@@ -115,33 +120,27 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates [TestCase( @"
", ExpectedResult = @"
", - TestName = "Empty source is not updated with no data-udi set" - )] + TestName = "Empty source is not updated with no data-udi set")] [TestCase( @"
", ExpectedResult = @"
", - TestName = "Empty source is updated with data-udi set" - )] + TestName = "Empty source is updated with data-udi set")] [TestCase( @"
", ExpectedResult = @"
", - TestName = "Filled source is overwritten with data-udi set" - )] + TestName = "Filled source is overwritten with data-udi set")] [TestCase( @"
", ExpectedResult = @"
", - TestName = "Attributes are persisted" - )] + TestName = "Attributes are persisted")] [TestCase( @"
", ExpectedResult = @"
", - TestName = "Source is trimmed and parameters are prefixed" - )] + TestName = "Source is trimmed and parameters are prefixed")] [TestCase( @"
", ExpectedResult = @"
", - TestName = "Parameters are prefixed" - )] + TestName = "Parameters are prefixed")] [TestCase( @"
@@ -154,8 +153,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates
", - TestName = "Multiple img tags are handled" - )] + TestName = "Multiple img tags are handled")] [Category("Ensure image sources")] public string Ensure_ImageSources_Processing(string sourceHtml) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/HtmlLocalLinkParserTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/HtmlLocalLinkParserTests.cs index 043481b9d0..726741cd1c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/HtmlLocalLinkParserTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/HtmlLocalLinkParserTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using Moq; using NUnit.Framework; @@ -8,6 +11,7 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Tests.Common; using Umbraco.Tests.UnitTests.TestHelpers.Objects; +using Umbraco.Web; using Umbraco.Web.Routing; using Umbraco.Web.Templates; @@ -43,15 +47,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates [TestCase("hello href=\"{localLink:umb://document/9931BDE0-AAC3-4BAB-B838-909A7B47570E}\" world ", "hello href=\"/my-test-url\" world ")] [TestCase("hello href=\"{localLink:umb://document/9931BDE0AAC34BABB838909A7B47570E}\" world ", "hello href=\"/my-test-url\" world ")] [TestCase("hello href=\"{localLink:umb://media/9931BDE0AAC34BABB838909A7B47570E}\" world ", "hello href=\"/media/1001/my-image.jpg\" world ")] - //this one has an invalid char so won't match + + // This one has an invalid char so won't match. [TestCase("hello href=\"{localLink:umb^://document/9931BDE0-AAC3-4BAB-B838-909A7B47570E}\" world ", "hello href=\"{localLink:umb^://document/9931BDE0-AAC3-4BAB-B838-909A7B47570E}\" world ")] [TestCase("hello href=\"{localLink:umb://document-type/9931BDE0-AAC3-4BAB-B838-909A7B47570E}\" world ", "hello href=\"#\" world ")] public void ParseLocalLinks(string input, string result) { - //setup a mock URL provider which we'll use for testing + // setup a mock URL provider which we'll use for testing var contentUrlProvider = new Mock(); contentUrlProvider - .Setup(x => x.GetUrl( It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Setup(x => x.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(UrlInfo.Url("/my-test-url")); var contentType = new PublishedContentType(Guid.NewGuid(), 666, "alias", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Nothing); var publishedContent = new Mock(); @@ -67,17 +72,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates var umbracoContextAccessor = new TestUmbracoContextAccessor(); - var umbracoContextFactory = TestUmbracoContextFactory.Create( + IUmbracoContextFactory umbracoContextFactory = TestUmbracoContextFactory.Create( umbracoContextAccessor: umbracoContextAccessor); var webRoutingSettings = new WebRoutingSettings(); - var publishedUrlProvider = new UrlProvider(umbracoContextAccessor, + var publishedUrlProvider = new UrlProvider( + umbracoContextAccessor, Microsoft.Extensions.Options.Options.Create(webRoutingSettings), - new UrlProviderCollection(new []{contentUrlProvider.Object}), - new MediaUrlProviderCollection(new []{mediaUrlProvider.Object}), - Mock.Of() - ); - using (var reference = umbracoContextFactory.EnsureUmbracoContext()) + new UrlProviderCollection(new[] { contentUrlProvider.Object }), + new MediaUrlProviderCollection(new[] { mediaUrlProvider.Object }), + Mock.Of()); + using (UmbracoContextReference reference = umbracoContextFactory.EnsureUmbracoContext()) { var contentCache = Mock.Get(reference.UmbracoContext.Content); contentCache.Setup(x => x.GetById(It.IsAny())).Returns(publishedContent.Object); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/ViewHelperTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/ViewHelperTests.cs index 27c78d7a68..85c96cf5be 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/ViewHelperTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Templates/ViewHelperTests.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.IO; namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates @@ -10,7 +13,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates public void NoOptions() { var view = ViewHelper.GetDefaultFileContent(); - Assert.AreEqual(FixView(@"@using Umbraco.Web.PublishedModels; + Assert.AreEqual( + FixView(@"@using Umbraco.Web.PublishedModels; @inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage @{ Layout = null; @@ -21,7 +25,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates public void Layout() { var view = ViewHelper.GetDefaultFileContent(layoutPageAlias: "Dharznoik"); - Assert.AreEqual(FixView(@"@using Umbraco.Web.PublishedModels; + Assert.AreEqual( + FixView(@"@using Umbraco.Web.PublishedModels; @inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage @{ Layout = ""Dharznoik.cshtml""; @@ -32,7 +37,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates public void ClassName() { var view = ViewHelper.GetDefaultFileContent(modelClassName: "ClassName"); - Assert.AreEqual(FixView(@"@using Umbraco.Web.PublishedModels; + Assert.AreEqual( + FixView(@"@using Umbraco.Web.PublishedModels; @inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage @{ Layout = null; @@ -43,7 +49,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates public void Namespace() { var view = ViewHelper.GetDefaultFileContent(modelNamespace: "Models"); - Assert.AreEqual(FixView(@"@using Umbraco.Web.PublishedModels; + Assert.AreEqual( + FixView(@"@using Umbraco.Web.PublishedModels; @inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage @{ Layout = null; @@ -54,7 +61,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates public void ClassNameAndNamespace() { var view = ViewHelper.GetDefaultFileContent(modelClassName: "ClassName", modelNamespace: "My.Models"); - Assert.AreEqual(FixView(@"@using Umbraco.Web.PublishedModels; + Assert.AreEqual( + FixView(@"@using Umbraco.Web.PublishedModels; @inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage @using ContentModels = My.Models; @{ @@ -66,7 +74,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates public void ClassNameAndNamespaceAndAlias() { var view = ViewHelper.GetDefaultFileContent(modelClassName: "ClassName", modelNamespace: "My.Models", modelNamespaceAlias: "MyModels"); - Assert.AreEqual(FixView(@"@using Umbraco.Web.PublishedModels; + Assert.AreEqual( + FixView(@"@using Umbraco.Web.PublishedModels; @inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage @using MyModels = My.Models; @{ @@ -78,7 +87,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Templates public void Combined() { var view = ViewHelper.GetDefaultFileContent(layoutPageAlias: "Dharznoik", modelClassName: "ClassName", modelNamespace: "My.Models", modelNamespaceAlias: "MyModels"); - Assert.AreEqual(FixView(@"@using Umbraco.Web.PublishedModels; + Assert.AreEqual( + FixView(@"@using Umbraco.Web.PublishedModels; @inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage @using MyModels = My.Models; @{ diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/VersionExtensionTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/VersionExtensionTests.cs index a4ab15afe7..df80f3b38b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/VersionExtensionTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/VersionExtensionTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; using Umbraco.Core; @@ -22,7 +25,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core { var version = new Version(major, minor, build, rev); - var result = version.SubtractRevision(); + Version result = version.SubtractRevision(); Assert.AreEqual(new Version(outcome), result); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Xml/XmlHelperTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Xml/XmlHelperTests.cs index 495ca0186d..8d4f8aef0f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Xml/XmlHelperTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Xml/XmlHelperTests.cs @@ -1,4 +1,7 @@ -using System.Diagnostics; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Diagnostics; using System.Linq; using System.Xml; using System.Xml.XPath; @@ -15,17 +18,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Xml private XmlDocumentBuilder _builder; [SetUp] - public void SetUp() - { - _builder = new XmlDocumentBuilder(); - } + public void SetUp() => _builder = new XmlDocumentBuilder(); [Ignore("This is a benchmark test so is ignored by default")] [Test] public void Sort_Nodes_Benchmark_Legacy() { - var xml = _builder.Build(); - var original = xml.GetElementById(1173.ToString()); + XmlDocument xml = _builder.Build(); + XmlElement original = xml.GetElementById(1173.ToString()); Assert.IsNotNull(original); long totalTime = 0; @@ -34,26 +34,27 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Xml for (var i = 0; i < iterations; i++) { - //don't measure the time for clone! - var parentNode = original.Clone(); + // don't measure the time for clone! + XmlNode parentNode = original.Clone(); watch.Start(); LegacySortNodes(ref parentNode); watch.Stop(); totalTime += watch.ElapsedMilliseconds; watch.Reset(); - //do assertions just to make sure it is working properly. + // Do assertions just to make sure it is working properly. var currSort = 0; - foreach (var child in parentNode.SelectNodes("./* [@id]").Cast()) + foreach (XmlNode child in parentNode.SelectNodes("./* [@id]").Cast()) { Assert.AreEqual(currSort, int.Parse(child.Attributes["sortOrder"].Value)); currSort++; } - //ensure the parent node's properties still exist first + // Ensure the parent node's properties still exist first. Assert.AreEqual("content", parentNode.ChildNodes[0].Name); Assert.AreEqual("umbracoUrlAlias", parentNode.ChildNodes[1].Name); - //then the child nodes should come straight after + + // Then the child nodes should come straight after. Assert.IsTrue(parentNode.ChildNodes[2].Attributes["id"] != null); } @@ -64,8 +65,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Xml [Test] public void Sort_Nodes_Benchmark_New() { - var xml = _builder.Build(); - var original = xml.GetElementById(1173.ToString()); + XmlDocument xml = _builder.Build(); + XmlElement original = xml.GetElementById(1173.ToString()); Assert.IsNotNull(original); long totalTime = 0; @@ -74,8 +75,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Xml for (var i = 0; i < iterations; i++) { - //don't measure the time for clone! - var parentNode = (XmlElement) original.Clone(); + // don't measure the time for clone! + var parentNode = (XmlElement)original.Clone(); watch.Start(); XmlHelper.SortNodes( parentNode, @@ -85,18 +86,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Xml totalTime += watch.ElapsedMilliseconds; watch.Reset(); - //do assertions just to make sure it is working properly. + // do assertions just to make sure it is working properly. var currSort = 0; - foreach (var child in parentNode.SelectNodes("./* [@id]").Cast()) + foreach (XmlNode child in parentNode.SelectNodes("./* [@id]").Cast()) { Assert.AreEqual(currSort, int.Parse(child.Attributes["sortOrder"].Value)); currSort++; } - //ensure the parent node's properties still exist first + // ensure the parent node's properties still exist first Assert.AreEqual("content", parentNode.ChildNodes[0].Name); Assert.AreEqual("umbracoUrlAlias", parentNode.ChildNodes[1].Name); - //then the child nodes should come straight after + + // then the child nodes should come straight after Assert.IsTrue(parentNode.ChildNodes[2].Attributes["id"] != null); } @@ -106,52 +108,56 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Xml [Test] public void Sort_Nodes() { - var xml = _builder.Build(); - var original = xml.GetElementById(1173.ToString()); + XmlDocument xml = _builder.Build(); + XmlElement original = xml.GetElementById(1173.ToString()); Assert.IsNotNull(original); - var parentNode = (XmlElement) original.Clone(); + var parentNode = (XmlElement)original.Clone(); XmlHelper.SortNodes( parentNode, "./* [@id]", x => x.AttributeValue("sortOrder")); - //do assertions just to make sure it is working properly. + // do assertions just to make sure it is working properly. var currSort = 0; - foreach (var child in parentNode.SelectNodes("./* [@id]").Cast()) + foreach (XmlNode child in parentNode.SelectNodes("./* [@id]").Cast()) { Assert.AreEqual(currSort, int.Parse(child.Attributes["sortOrder"].Value)); currSort++; } - //ensure the parent node's properties still exist first + // ensure the parent node's properties still exist first Assert.AreEqual("content", parentNode.ChildNodes[0].Name); Assert.AreEqual("umbracoUrlAlias", parentNode.ChildNodes[1].Name); - //then the child nodes should come straight after + + // then the child nodes should come straight after Assert.IsTrue(parentNode.ChildNodes[2].Attributes["id"] != null); } /// /// This was the logic to sort before and now lives here just to show the benchmarks tests above. /// - /// private static void LegacySortNodes(ref XmlNode parentNode) { - var n = parentNode.CloneNode(true); + XmlNode n = parentNode.CloneNode(true); // remove all children from original node var xpath = "./* [@id]"; foreach (XmlNode child in parentNode.SelectNodes(xpath)) + { parentNode.RemoveChild(child); + } - var nav = n.CreateNavigator(); - var expr = nav.Compile(xpath); - expr.AddSort("@sortOrder", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number); - var iterator = nav.Select(expr); + XPathNavigator nav = n.CreateNavigator(); + XPathExpression expr = nav.Compile(xpath); + expr.AddSort("@sortOrder", XmlSortOrder.Ascending, XmlCaseOrder.None, string.Empty, XmlDataType.Number); + XPathNodeIterator iterator = nav.Select(expr); while (iterator.MoveNext()) + { parentNode.AppendChild( - ((IHasXmlNode) iterator.Current).GetNode()); + ((IHasXmlNode)iterator.Current).GetNode()); + } } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/XmlExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/XmlExtensionsTests.cs index ae3762ef57..2d2fb9d85b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/XmlExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/XmlExtensionsTests.cs @@ -1,4 +1,7 @@ -using System.Xml; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Xml; using System.Xml.Linq; using NUnit.Framework; using Umbraco.Core; @@ -14,7 +17,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core var cdata = new XElement("test", new XCData("hello world")); var xdoc = new XmlDocument(); - var xmlNode = cdata.GetXmlNode(xdoc); + XmlNode xmlNode = cdata.GetXmlNode(xdoc); Assert.AreEqual("hello world", xmlNode.InnerText); } @@ -25,7 +28,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core var cdata = new XElement("test", new XText("hello world")); var xdoc = new XmlDocument(); - var xmlNode = cdata.GetXmlNode(xdoc); + XmlNode xmlNode = cdata.GetXmlNode(xdoc); Assert.AreEqual("hello world", xmlNode.InnerText); } @@ -39,7 +42,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core var xdoc = new XmlDocument(); xdoc.LoadXml(xml); - var xmlNode = cdata.GetXmlNode(xdoc); + XmlNode xmlNode = cdata.GetXmlNode(xdoc); Assert.AreEqual("hello world", xmlNode.InnerText); Assert.AreEqual(xml, xdoc.OuterXml); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeLookupNormalizerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeLookupNormalizerTests.cs index 8172a712d8..9ce3a8a3c3 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeLookupNormalizerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeLookupNormalizerTests.cs @@ -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.Web.Backoffice Assert.AreEqual(name, normalizedName); } + [Test] [TestCase(null)] [TestCase("")] diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Editors/UserEditorAuthorizationHelperTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Editors/UserEditorAuthorizationHelperTests.cs index 2bf9a541b9..971a378fe8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Editors/UserEditorAuthorizationHelperTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Editors/UserEditorAuthorizationHelperTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Linq; using Moq; using NUnit.Framework; @@ -19,8 +22,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors [Test] public void Admin_Is_Authorized() { - var currentUser = CreateAdminUser(); - var savingUser = CreateUser(); + IUser currentUser = CreateAdminUser(); + IUser savingUser = CreateUser(); var contentService = new Mock(); var mediaService = new Mock(); @@ -32,7 +35,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors mediaService.Object, entityService.Object); - var result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new int[0], new string[0]); + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new int[0], new string[0]); Assert.IsTrue(result.Success); } @@ -40,8 +43,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors [Test] public void Non_Admin_Cannot_Save_Admin() { - var currentUser = CreateUser(); - var savingUser = CreateAdminUser(); + IUser currentUser = CreateUser(); + IUser savingUser = CreateAdminUser(); var contentService = new Mock(); var mediaService = new Mock(); @@ -53,7 +56,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors mediaService.Object, entityService.Object); - var result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new int[0], new string[0]); + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new int[0], new string[0]); Assert.IsFalse(result.Success); } @@ -61,8 +64,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors [Test] public void Cannot_Grant_Group_Membership_Without_Being_A_Member() { - var currentUser = CreateUser(withGroup: true); - var savingUser = CreateUser(); + IUser currentUser = CreateUser(withGroup: true); + IUser savingUser = CreateUser(); var contentService = new Mock(); var mediaService = new Mock(); @@ -74,7 +77,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors mediaService.Object, entityService.Object); - var result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new int[0], new[] {"FunGroup"}); + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new int[0], new[] { "FunGroup" }); Assert.IsFalse(result.Success); } @@ -82,8 +85,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors [Test] public void Can_Grant_Group_Membership_With_Being_A_Member() { - var currentUser = CreateUser(withGroup: true); - var savingUser = CreateUser(); + IUser currentUser = CreateUser(withGroup: true); + IUser savingUser = CreateUser(); var contentService = new Mock(); var mediaService = new Mock(); @@ -95,7 +98,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors mediaService.Object, entityService.Object); - var result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new int[0], new[] { "test" }); + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new int[0], new[] { "test" }); Assert.IsTrue(result.Success); } @@ -105,14 +108,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors { var nodePaths = new Dictionary { - {1234, "-1,1234"}, - {9876, "-1,9876"}, - {5555, "-1,9876,5555"}, - {4567, "-1,4567"}, + { 1234, "-1,1234" }, + { 9876, "-1,9876" }, + { 5555, "-1,9876,5555" }, + { 4567, "-1,4567" }, }; - var currentUser = CreateUser(startContentIds: new[] { 9876 }); - var savingUser = CreateUser(startContentIds: new[] { 1234 }); + IUser currentUser = CreateUser(startContentIds: new[] { 9876 }); + IUser savingUser = CreateUser(startContentIds: new[] { 1234 }); var contentService = new Mock(); contentService.Setup(x => x.GetById(It.IsAny())) @@ -121,18 +124,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors var userService = new Mock(); var entityService = new Mock(); entityService.Setup(service => service.GetAllPaths(It.IsAny(), It.IsAny())) - .Returns((UmbracoObjectTypes objType, int[] ids) => - { - return ids.Select(x => new TreeEntityPath {Path = nodePaths[x], Id = x}); - }); + .Returns((UmbracoObjectTypes objType, int[] ids) => ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x })); var authHelper = new UserEditorAuthorizationHelper( contentService.Object, mediaService.Object, entityService.Object); - //adding 5555 which currentUser has access to since it's a child of 9876 ... adding is still ok even though currentUser doesn't have access to 1234 - var result = authHelper.IsAuthorized(currentUser, savingUser, new[] { 1234, 5555 }, new int[0], new string[0]); + // adding 5555 which currentUser has access to since it's a child of 9876 ... adding is still ok even though currentUser doesn't have access to 1234 + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new[] { 1234, 5555 }, new int[0], new string[0]); Assert.IsTrue(result.Success); } @@ -142,14 +142,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors { var nodePaths = new Dictionary { - {1234, "-1,1234"}, - {9876, "-1,9876"}, - {5555, "-1,9876,5555"}, - {4567, "-1,4567"}, + { 1234, "-1,1234" }, + { 9876, "-1,9876" }, + { 5555, "-1,9876,5555" }, + { 4567, "-1,4567" }, }; - var currentUser = CreateUser(startContentIds: new[] { 9876 }); - var savingUser = CreateUser(startContentIds: new[] { 1234, 4567 }); + IUser currentUser = CreateUser(startContentIds: new[] { 9876 }); + IUser savingUser = CreateUser(startContentIds: new[] { 1234, 4567 }); var contentService = new Mock(); contentService.Setup(x => x.GetById(It.IsAny())) @@ -158,18 +158,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors var userService = new Mock(); var entityService = new Mock(); entityService.Setup(service => service.GetAllPaths(It.IsAny(), It.IsAny())) - .Returns((UmbracoObjectTypes objType, int[] ids) => - { - return ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x }); - }); + .Returns((UmbracoObjectTypes objType, int[] ids) => ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x })); var authHelper = new UserEditorAuthorizationHelper( contentService.Object, mediaService.Object, entityService.Object); - //removing 4567 start node even though currentUser doesn't have acces to it ... removing is ok - var result = authHelper.IsAuthorized(currentUser, savingUser, new[] { 1234 }, new int[0], new string[0]); + // removing 4567 start node even though currentUser doesn't have acces to it ... removing is ok + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new[] { 1234 }, new int[0], new string[0]); Assert.IsTrue(result.Success); } @@ -179,14 +176,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors { var nodePaths = new Dictionary { - {1234, "-1,1234"}, - {9876, "-1,9876"}, - {5555, "-1,9876,5555"}, - {4567, "-1,4567"}, + { 1234, "-1,1234" }, + { 9876, "-1,9876" }, + { 5555, "-1,9876,5555" }, + { 4567, "-1,4567" }, }; - var currentUser = CreateUser(startContentIds: new[] { 9876 }); - var savingUser = CreateUser(); + IUser currentUser = CreateUser(startContentIds: new[] { 9876 }); + IUser savingUser = CreateUser(); var contentService = new Mock(); contentService.Setup(x => x.GetById(It.IsAny())) @@ -195,18 +192,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors var userService = new Mock(); var entityService = new Mock(); entityService.Setup(service => service.GetAllPaths(It.IsAny(), It.IsAny())) - .Returns((UmbracoObjectTypes objType, int[] ids) => - { - return ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x }); - }); + .Returns((UmbracoObjectTypes objType, int[] ids) => ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x })); var authHelper = new UserEditorAuthorizationHelper( contentService.Object, mediaService.Object, entityService.Object); - //adding 1234 but currentUser doesn't have access to it ... nope - var result = authHelper.IsAuthorized(currentUser, savingUser, new []{1234}, new int[0], new string[0]); + // adding 1234 but currentUser doesn't have access to it ... nope + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new[] { 1234 }, new int[0], new string[0]); Assert.IsFalse(result.Success); } @@ -216,14 +210,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors { var nodePaths = new Dictionary { - {1234, "-1,1234"}, - {9876, "-1,9876"}, - {5555, "-1,9876,5555"}, - {4567, "-1,4567"}, + { 1234, "-1,1234" }, + { 9876, "-1,9876" }, + { 5555, "-1,9876,5555" }, + { 4567, "-1,4567" }, }; - var currentUser = CreateUser(startContentIds: new[] { 9876 }); - var savingUser = CreateUser(); + IUser currentUser = CreateUser(startContentIds: new[] { 9876 }); + IUser savingUser = CreateUser(); var contentService = new Mock(); contentService.Setup(x => x.GetById(It.IsAny())) @@ -232,18 +226,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors var userService = new Mock(); var entityService = new Mock(); entityService.Setup(service => service.GetAllPaths(It.IsAny(), It.IsAny())) - .Returns((UmbracoObjectTypes objType, int[] ids) => - { - return ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x }); - }); + .Returns((UmbracoObjectTypes objType, int[] ids) => ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x })); var authHelper = new UserEditorAuthorizationHelper( contentService.Object, mediaService.Object, entityService.Object); - //adding 5555 which currentUser has access to since it's a child of 9876 ... ok - var result = authHelper.IsAuthorized(currentUser, savingUser, new[] { 5555 }, new int[0], new string[0]); + // adding 5555 which currentUser has access to since it's a child of 9876 ... ok + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new[] { 5555 }, new int[0], new string[0]); Assert.IsTrue(result.Success); } @@ -253,15 +244,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors { var nodePaths = new Dictionary { - {1234, "-1,1234"}, - {9876, "-1,9876"}, - {5555, "-1,9876,5555"}, - {4567, "-1,4567"}, + { 1234, "-1,1234" }, + { 9876, "-1,9876" }, + { 5555, "-1,9876,5555" }, + { 4567, "-1,4567" }, }; - - var currentUser = CreateUser(startMediaIds: new[] { 9876 }); - var savingUser = CreateUser(); + IUser currentUser = CreateUser(startMediaIds: new[] { 9876 }); + IUser savingUser = CreateUser(); var contentService = new Mock(); var mediaService = new Mock(); @@ -270,18 +260,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors var userService = new Mock(); var entityService = new Mock(); entityService.Setup(service => service.GetAllPaths(It.IsAny(), It.IsAny())) - .Returns((UmbracoObjectTypes objType, int[] ids) => - { - return ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x }); - }); + .Returns((UmbracoObjectTypes objType, int[] ids) => ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x })); var authHelper = new UserEditorAuthorizationHelper( contentService.Object, mediaService.Object, entityService.Object); - //adding 1234 but currentUser doesn't have access to it ... nope - var result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new[] {1234}, new string[0]); + // adding 1234 but currentUser doesn't have access to it ... nope + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new[] { 1234 }, new string[0]); Assert.IsFalse(result.Success); } @@ -291,14 +278,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors { var nodePaths = new Dictionary { - {1234, "-1,1234"}, - {9876, "-1,9876"}, - {5555, "-1,9876,5555"}, - {4567, "-1,4567"}, + { 1234, "-1,1234" }, + { 9876, "-1,9876" }, + { 5555, "-1,9876,5555" }, + { 4567, "-1,4567" }, }; - var currentUser = CreateUser(startMediaIds: new[] { 9876 }); - var savingUser = CreateUser(); + IUser currentUser = CreateUser(startMediaIds: new[] { 9876 }); + IUser savingUser = CreateUser(); var contentService = new Mock(); var mediaService = new Mock(); @@ -307,18 +294,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors var userService = new Mock(); var entityService = new Mock(); entityService.Setup(service => service.GetAllPaths(It.IsAny(), It.IsAny())) - .Returns((UmbracoObjectTypes objType, int[] ids) => - { - return ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x }); - }); + .Returns((UmbracoObjectTypes objType, int[] ids) => ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x })); var authHelper = new UserEditorAuthorizationHelper( contentService.Object, mediaService.Object, entityService.Object); - //adding 5555 which currentUser has access to since it's a child of 9876 ... ok - var result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new[] { 5555 }, new string[0]); + // adding 5555 which currentUser has access to since it's a child of 9876 ... ok + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new[] { 5555 }, new string[0]); Assert.IsTrue(result.Success); } @@ -328,14 +312,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors { var nodePaths = new Dictionary { - {1234, "-1,1234"}, - {9876, "-1,9876"}, - {5555, "-1,9876,5555"}, - {4567, "-1,4567"}, + { 1234, "-1,1234" }, + { 9876, "-1,9876" }, + { 5555, "-1,9876,5555" }, + { 4567, "-1,4567" }, }; - var currentUser = CreateUser(startMediaIds: new[] { 9876 }); - var savingUser = CreateUser(startMediaIds: new[] { 1234 }); + IUser currentUser = CreateUser(startMediaIds: new[] { 9876 }); + IUser savingUser = CreateUser(startMediaIds: new[] { 1234 }); var contentService = new Mock(); var mediaService = new Mock(); @@ -344,18 +328,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors var userService = new Mock(); var entityService = new Mock(); entityService.Setup(service => service.GetAllPaths(It.IsAny(), It.IsAny())) - .Returns((UmbracoObjectTypes objType, int[] ids) => - { - return ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x }); - }); + .Returns((UmbracoObjectTypes objType, int[] ids) => ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x })); var authHelper = new UserEditorAuthorizationHelper( contentService.Object, mediaService.Object, entityService.Object); - //adding 5555 which currentUser has access to since it's a child of 9876 ... adding is still ok even though currentUser doesn't have access to 1234 - var result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new[] { 1234, 5555 }, new string[0]); + // adding 5555 which currentUser has access to since it's a child of 9876 ... adding is still ok even though currentUser doesn't have access to 1234 + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new[] { 1234, 5555 }, new string[0]); Assert.IsTrue(result.Success); } @@ -365,14 +346,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors { var nodePaths = new Dictionary { - {1234, "-1,1234"}, - {9876, "-1,9876"}, - {5555, "-1,9876,5555"}, - {4567, "-1,4567"}, + { 1234, "-1,1234" }, + { 9876, "-1,9876" }, + { 5555, "-1,9876,5555" }, + { 4567, "-1,4567" }, }; - var currentUser = CreateUser(startMediaIds: new[] { 9876 }); - var savingUser = CreateUser(startMediaIds: new[] { 1234, 4567 }); + IUser currentUser = CreateUser(startMediaIds: new[] { 9876 }); + IUser savingUser = CreateUser(startMediaIds: new[] { 1234, 4567 }); var contentService = new Mock(); var mediaService = new Mock(); @@ -381,27 +362,24 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors var userService = new Mock(); var entityService = new Mock(); entityService.Setup(service => service.GetAllPaths(It.IsAny(), It.IsAny())) - .Returns((UmbracoObjectTypes objType, int[] ids) => - { - return ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x }); - }); + .Returns((UmbracoObjectTypes objType, int[] ids) => ids.Select(x => new TreeEntityPath { Path = nodePaths[x], Id = x })); var authHelper = new UserEditorAuthorizationHelper( contentService.Object, mediaService.Object, entityService.Object); - //removing 4567 start node even though currentUser doesn't have acces to it ... removing is ok - var result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new[] { 1234 }, new string[0]); + // removing 4567 start node even though currentUser doesn't have acces to it ... removing is ok + Attempt result = authHelper.IsAuthorized(currentUser, savingUser, new int[0], new[] { 1234 }, new string[0]); Assert.IsTrue(result.Success); } private static IUser CreateUser(bool withGroup = false, int[] startContentIds = null, int[] startMediaIds = null) { - var builder = new UserBuilder() - .WithStartContentIds(startContentIds != null ? startContentIds : new int[0]) - .WithStartMediaIds(startMediaIds != null ? startMediaIds : new int[0]); + UserBuilder builder = new UserBuilder() + .WithStartContentIds(startContentIds ?? (new int[0])) + .WithStartMediaIds(startMediaIds ?? (new int[0])); if (withGroup) { builder = (UserBuilder)builder @@ -414,15 +392,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Editors return builder.Build(); } - private static IUser CreateAdminUser() - { - return new UserBuilder() + private static IUser CreateAdminUser() => + new UserBuilder() .AddUserGroup() .WithId(1) .WithName("Admin") .WithAlias(Constants.Security.AdminGroupAlias) .Done() .Build(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Examine/UmbracoContentValueSetValidatorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Examine/UmbracoContentValueSetValidatorTests.cs index 449e005220..a1b00c9ab2 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Examine/UmbracoContentValueSetValidatorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Examine/UmbracoContentValueSetValidatorTests.cs @@ -1,13 +1,16 @@ -using Examine; -using NUnit.Framework; -using Umbraco.Examine; -using Moq; -using Umbraco.Core.Services; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; +using System.Linq; +using Examine; +using Moq; +using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; -using System; -using System.Linq; +using Umbraco.Core.Services; +using Umbraco.Examine; namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine { @@ -19,7 +22,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine { var validator = new ContentValueSetValidator(false, true, Mock.Of()); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); result = validator.Validate(ValueSet.FromObject("777", IndexTypes.Media, new { hello = "world", path = "-1,555" })); @@ -27,7 +30,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine result = validator.Validate(ValueSet.FromObject("555", "invalid-category", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); - } [Test] @@ -35,7 +37,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine { var validator = new ContentValueSetValidator(false, true, Mock.Of()); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); @@ -47,7 +49,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine { var validator = new ContentValueSetValidator(false, true, Mock.Of(), 555); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Filtered, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,444" })); @@ -63,12 +65,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine [Test] public void Inclusion_Field_List() { - var validator = new ValueSetValidator(null, null, + var validator = new ValueSetValidator( + null, + null, new[] { "hello", "world" }, null); var valueSet = ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555", world = "your oyster" }); - var result = validator.Validate(valueSet); + ValueSetValidationResult result = validator.Validate(valueSet); Assert.AreEqual(ValueSetValidationResult.Filtered, result); Assert.IsFalse(valueSet.Values.ContainsKey("path")); @@ -79,12 +83,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine [Test] public void Exclusion_Field_List() { - var validator = new ValueSetValidator(null, null, + var validator = new ValueSetValidator( + null, + null, null, new[] { "hello", "world" }); var valueSet = ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555", world = "your oyster" }); - var result = validator.Validate(valueSet); + ValueSetValidationResult result = validator.Validate(valueSet); Assert.AreEqual(ValueSetValidationResult.Filtered, result); Assert.IsTrue(valueSet.Values.ContainsKey("path")); @@ -95,12 +101,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine [Test] public void Inclusion_Exclusion_Field_List() { - var validator = new ValueSetValidator(null, null, + var validator = new ValueSetValidator( + null, + null, new[] { "hello", "world" }, new[] { "world" }); var valueSet = ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555", world = "your oyster" }); - var result = validator.Validate(valueSet); + ValueSetValidationResult result = validator.Validate(valueSet); Assert.AreEqual(ValueSetValidationResult.Filtered, result); Assert.IsFalse(valueSet.Values.ContainsKey("path")); @@ -111,10 +119,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine [Test] public void Inclusion_Type_List() { - var validator = new ContentValueSetValidator(false, true, Mock.Of(), + var validator = new ContentValueSetValidator( + false, + true, + Mock.Of(), includeItemTypes: new List { "include-content" }); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); @@ -127,10 +138,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine [Test] public void Exclusion_Type_List() { - var validator = new ContentValueSetValidator(false, true, Mock.Of(), + var validator = new ContentValueSetValidator( + false, + true, + Mock.Of(), excludeItemTypes: new List { "exclude-content" }); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); @@ -143,11 +157,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine [Test] public void Inclusion_Exclusion_Type_List() { - var validator = new ContentValueSetValidator(false, true, Mock.Of(), + var validator = new ContentValueSetValidator( + false, + true, + Mock.Of(), includeItemTypes: new List { "include-content", "exclude-content" }, excludeItemTypes: new List { "exclude-content" }); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); @@ -165,7 +182,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine { var validator = new ContentValueSetValidator(true, false, Mock.Of()); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,-20,555" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,-20,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,-20,555,777" })); @@ -174,7 +191,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); - result = validator.Validate(new ValueSet("555", IndexTypes.Content, + result = validator.Validate(new ValueSet( + "555", + IndexTypes.Content, new Dictionary { ["hello"] = "world", @@ -189,7 +208,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine { var validator = new ContentValueSetValidator(true, false, Mock.Of()); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Media, new { hello = "world", path = "-1,-21,555" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Media, new { hello = "world", path = "-1,-21,555" })); Assert.AreEqual(ValueSetValidationResult.Filtered, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Media, new { hello = "world", path = "-1,-21,555,777" })); @@ -197,7 +216,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Media, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); - } [Test] @@ -205,10 +223,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine { var validator = new ContentValueSetValidator(true, true, Mock.Of()); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); - result = validator.Validate(new ValueSet("555", IndexTypes.Content, + result = validator.Validate(new ValueSet( + "555", + IndexTypes.Content, new Dictionary { ["hello"] = "world", @@ -217,7 +237,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine })); Assert.AreEqual(ValueSetValidationResult.Failed, result); - result = validator.Validate(new ValueSet("555", IndexTypes.Content, + result = validator.Validate(new ValueSet( + "555", + IndexTypes.Content, new Dictionary { ["hello"] = "world", @@ -232,7 +254,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine { var validator = new ContentValueSetValidator(true, true, Mock.Of()); - var result = validator.Validate(new ValueSet("555", IndexTypes.Content, + ValueSetValidationResult result = validator.Validate(new ValueSet( + "555", + IndexTypes.Content, new Dictionary { ["hello"] = "world", @@ -242,7 +266,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine })); Assert.AreEqual(ValueSetValidationResult.Failed, result); - result = validator.Validate(new ValueSet("555", IndexTypes.Content, + result = validator.Validate(new ValueSet( + "555", + IndexTypes.Content, new Dictionary { ["hello"] = "world", @@ -252,7 +278,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine })); Assert.AreEqual(ValueSetValidationResult.Valid, result); - var valueSet = new ValueSet("555", IndexTypes.Content, + var valueSet = new ValueSet( + "555", + IndexTypes.Content, new Dictionary { ["hello"] = "world", @@ -274,7 +302,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine result = validator.Validate(valueSet); Assert.AreEqual(ValueSetValidationResult.Filtered, result); - Assert.AreEqual(7, valueSet.Values.Count()); //filtered to 7 values (removes es-es values) + Assert.AreEqual(7, valueSet.Values.Count()); // filtered to 7 values (removes es-es values) Assert.IsFalse(valueSet.Values.ContainsKey($"{UmbracoExamineFieldNames.PublishedFieldName}_es-es")); Assert.IsFalse(valueSet.Values.ContainsKey("hello_es-ES")); Assert.IsFalse(valueSet.Values.ContainsKey("title_es-ES")); @@ -290,7 +318,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Examine .Returns(Attempt.Fail()); var validator = new ContentValueSetValidator(false, false, publicAccessService.Object); - var result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); + ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Filtered, result); result = validator.Validate(ValueSet.FromObject("777", IndexTypes.Content, new { hello = "world", path = "-1,777" })); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/HealthChecks/HealthCheckResultsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/HealthChecks/HealthCheckResultsTests.cs index 387d8aff44..10349a4f9e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/HealthChecks/HealthCheckResultsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/HealthChecks/HealthCheckResultsTests.cs @@ -1,18 +1,17 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using NUnit.Framework; using Umbraco.Core.HealthCheck; -using Umbraco.Core.HealthCheck.Checks; using Umbraco.Infrastructure.HealthCheck; -using Umbraco.Web.HealthCheck; namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HealthChecks { [TestFixture] public class HealthCheckResultsTests { - #region Stub checks - [HealthCheck("CFD6FC34-59C9-4402-B55F-C8BC96B628A1", "Stub check")] public abstract class StubHealthCheck : HealthCheck { @@ -25,27 +24,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HealthChecks _message = message; } - public override HealthCheckStatus ExecuteAction(HealthCheckAction action) - { - throw new NotImplementedException(); - } + public override HealthCheckStatus ExecuteAction(HealthCheckAction action) => throw new NotImplementedException(); - public override IEnumerable GetStatus() - { - return new List + public override IEnumerable GetStatus() => + new List { new HealthCheckStatus(_message) { ResultType = _resultType } }; - } } [HealthCheck("CFD6FC34-59C9-4402-B55F-C8BC96B628A1", "Stub check 1")] public class StubHealthCheck1 : StubHealthCheck { - public StubHealthCheck1(StatusResultType resultType, string message) : base(resultType, message) + public StubHealthCheck1(StatusResultType resultType, string message) + : base(resultType, message) { } } @@ -53,7 +48,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HealthChecks [HealthCheck("CFD6FC34-59C9-4402-B55F-C8BC96B628A2", "Stub check 2")] public class StubHealthCheck2 : StubHealthCheck { - public StubHealthCheck2(StatusResultType resultType, string message) : base(resultType, message) + public StubHealthCheck2(StatusResultType resultType, string message) + : base(resultType, message) { } } @@ -61,18 +57,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HealthChecks [HealthCheck("CFD6FC34-59C9-4402-B55F-C8BC96B628A3", "Stub check 3")] public class StubHealthCheck3 : StubHealthCheck { - public StubHealthCheck3(StatusResultType resultType, string message) : base(resultType, message) + public StubHealthCheck3(StatusResultType resultType, string message) + : base(resultType, message) { } - public override IEnumerable GetStatus() - { - throw new Exception("Check threw exception"); - } + public override IEnumerable GetStatus() => throw new Exception("Check threw exception"); } - #endregion - [Test] public void HealthCheckResults_WithSuccessfulChecks_ReturnsCorrectResultDescription() { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Logging/LogviewerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Logging/LogviewerTests.cs index 183e87e5ca..42e4c3e1e6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Logging/LogviewerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Logging/LogviewerTests.cs @@ -1,15 +1,23 @@ -using Moq; -using NUnit.Framework; -using Serilog; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Extensions.Logging; -using StackExchange.Profiling.Internal; +using Moq; +using NUnit.Framework; +using Serilog; using Umbraco.Core; +using Umbraco.Core.Hosting; +using Umbraco.Core.IO; +using Umbraco.Core.Logging; using Umbraco.Core.Logging.Viewer; +using Umbraco.Core.Models; using Umbraco.Tests.TestHelpers; +using File = System.IO.File; namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging { @@ -18,8 +26,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging { private ILogViewer _logViewer; - const string _logfileName = "UmbracoTraceLog.UNITTEST.20181112.json"; - const string _searchfileName = "logviewer.searches.config.js"; + private const string LogfileName = "UmbracoTraceLog.UNITTEST.20181112.json"; + private const string SearchfileName = "logviewer.searches.config.js"; private string _newLogfilePath; private string _newLogfileDirPath; @@ -27,38 +35,39 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging private string _newSearchfilePath; private string _newSearchfileDirPath; - private LogTimePeriod _logTimePeriod = new LogTimePeriod( - new DateTime(year: 2018, month: 11, day: 12, hour:0, minute:0, second:0), - new DateTime(year: 2018, month: 11, day: 13, hour: 0, minute: 0, second: 0) - ); + private readonly LogTimePeriod _logTimePeriod = new LogTimePeriod( + new DateTime(year: 2018, month: 11, day: 12, hour: 0, minute: 0, second: 0), + new DateTime(year: 2018, month: 11, day: 13, hour: 0, minute: 0, second: 0)); + [OneTimeSetUp] public void Setup() { var testRoot = TestContext.CurrentContext.TestDirectory.Split("bin")[0]; - //Create an example JSON log file to check results - //As a one time setup for all tets in this class/fixture - var ioHelper = TestHelper.IOHelper; - var hostingEnv = TestHelper.GetHostingEnvironment(); - var loggingConfiguration = TestHelper.GetLoggingConfiguration(hostingEnv); + // Create an example JSON log file to check results + // As a one time setup for all tets in this class/fixture + IIOHelper ioHelper = TestHelper.IOHelper; + IHostingEnvironment hostingEnv = TestHelper.GetHostingEnvironment(); - var exampleLogfilePath = Path.Combine(testRoot, "TestHelpers","Assets", _logfileName); + ILoggingConfiguration loggingConfiguration = TestHelper.GetLoggingConfiguration(hostingEnv); + + var exampleLogfilePath = Path.Combine(testRoot, "TestHelpers", "Assets", LogfileName); _newLogfileDirPath = loggingConfiguration.LogDirectory; - _newLogfilePath = Path.Combine(_newLogfileDirPath, _logfileName); + _newLogfilePath = Path.Combine(_newLogfileDirPath, LogfileName); - var exampleSearchfilePath = Path.Combine(testRoot, "TestHelpers","Assets", _searchfileName); + var exampleSearchfilePath = Path.Combine(testRoot, "TestHelpers", "Assets", SearchfileName); _newSearchfileDirPath = Path.Combine(hostingEnv.ApplicationPhysicalPath, @"config"); - _newSearchfilePath = Path.Combine(_newSearchfileDirPath, _searchfileName); + _newSearchfilePath = Path.Combine(_newSearchfileDirPath, SearchfileName); - //Create/ensure Directory exists + // Create/ensure Directory exists ioHelper.EnsurePathExists(_newLogfileDirPath); ioHelper.EnsurePathExists(_newSearchfileDirPath); - //Copy the sample files + // Copy the sample files File.Copy(exampleLogfilePath, _newLogfilePath, true); File.Copy(exampleSearchfilePath, _newSearchfilePath, true); - var logger = Mock.Of>(); + ILogger logger = Mock.Of>(); var logViewerConfig = new LogViewerConfig(hostingEnv); _logViewer = new SerilogJsonLogViewer(logger, logViewerConfig, loggingConfiguration, Log.Logger); } @@ -66,13 +75,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging [OneTimeTearDown] public void TearDown() { - //Cleanup & delete the example log & search files off disk - //Once all tests in this class/fixture have run + // Cleanup & delete the example log & search files off disk + // Once all tests in this class/fixture have run if (File.Exists(_newLogfilePath)) + { File.Delete(_newLogfilePath); + } if (File.Exists(_newSearchfilePath)) + { File.Delete(_newSearchfilePath); + } } [Test] @@ -80,14 +93,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging { var numberOfErrors = _logViewer.GetNumberOfErrors(_logTimePeriod); - //Our dummy log should contain 2 errors + // Our dummy log should contain 2 errors Assert.AreEqual(1, numberOfErrors); } [Test] public void Logs_Contain_Correct_Log_Level_Counts() { - var logCounts = _logViewer.GetLogLevelCounts(_logTimePeriod); + LogLevelCounts logCounts = _logViewer.GetLogLevelCounts(_logTimePeriod); Assert.AreEqual(55, logCounts.Debug); Assert.AreEqual(1, logCounts.Error); @@ -99,19 +112,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging [Test] public void Logs_Contains_Correct_Message_Templates() { - var templates = _logViewer.GetMessageTemplates(_logTimePeriod); + IEnumerable templates = _logViewer.GetMessageTemplates(_logTimePeriod); - //Count no of templates + // Count no of templates Assert.AreEqual(25, templates.Count()); - //Verify all templates & counts are unique + // Verify all templates & counts are unique CollectionAssert.AllItemsAreUnique(templates); - //Ensure the collection contains LogTemplate objects + // Ensure the collection contains LogTemplate objects CollectionAssert.AllItemsAreInstancesOfType(templates, typeof(LogTemplate)); - //Get first item & verify its template & count are what we expect - var popularTemplate = templates.FirstOrDefault(); + // Get first item & verify its template & count are what we expect + LogTemplate popularTemplate = templates.FirstOrDefault(); Assert.IsNotNull(popularTemplate); Assert.AreEqual("{EndMessage} ({Duration}ms) [Timing {TimingId}]", popularTemplate.MessageTemplate); @@ -121,8 +134,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging [Test] public void Logs_Can_Open_As_Small_File() { - //We are just testing a return value (as we know the example file is less than 200MB) - //But this test method does not test/check that + // We are just testing a return value (as we know the example file is less than 200MB) + // But this test method does not test/check that var canOpenLogs = _logViewer.CheckCanOpenLogs(_logTimePeriod); Assert.IsTrue(canOpenLogs); } @@ -132,51 +145,49 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging { var sw = new Stopwatch(); sw.Start(); - //Should get me the most 100 recent log entries & using default overloads for remaining params - var allLogs = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1); + + // Should get me the most 100 recent log entries & using default overloads for remaining params + PagedResult allLogs = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1); sw.Stop(); - //Check we get 100 results back for a page & total items all good :) + + // Check we get 100 results back for a page & total items all good :) Assert.AreEqual(100, allLogs.Items.Count()); Assert.AreEqual(102, allLogs.TotalItems); Assert.AreEqual(2, allLogs.TotalPages); - //Check collection all contain same object type + // Check collection all contain same object type CollectionAssert.AllItemsAreInstancesOfType(allLogs.Items, typeof(LogMessage)); - //Check first item is newest - var newestItem = allLogs.Items.First(); - DateTimeOffset newDate; - DateTimeOffset.TryParse("2018-11-12T08:39:18.1971147Z", out newDate); + // Check first item is newest + LogMessage newestItem = allLogs.Items.First(); + DateTimeOffset.TryParse("2018-11-12T08:39:18.1971147Z", out DateTimeOffset newDate); Assert.AreEqual(newDate, newestItem.Timestamp); - - //Check we call method again with a smaller set of results & in ascending - var smallQuery = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, pageSize: 10, orderDirection: Direction.Ascending); + // Check we call method again with a smaller set of results & in ascending + PagedResult smallQuery = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, pageSize: 10, orderDirection: Direction.Ascending); Assert.AreEqual(10, smallQuery.Items.Count()); Assert.AreEqual(11, smallQuery.TotalPages); - //Check first item is oldest - var oldestItem = smallQuery.Items.First(); - DateTimeOffset oldDate; - DateTimeOffset.TryParse("2018-11-12T08:34:45.8371142Z", out oldDate); + // Check first item is oldest + LogMessage oldestItem = smallQuery.Items.First(); + DateTimeOffset.TryParse("2018-11-12T08:34:45.8371142Z", out DateTimeOffset oldDate); Assert.AreEqual(oldDate, oldestItem.Timestamp); - - //Check invalid log levels - //Rather than expect 0 items - get all items back & ignore the invalid levels + // Check invalid log levels + // Rather than expect 0 items - get all items back & ignore the invalid levels string[] invalidLogLevels = { "Invalid", "NotALevel" }; - var queryWithInvalidLevels = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, logLevels: invalidLogLevels); + PagedResult queryWithInvalidLevels = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, logLevels: invalidLogLevels); Assert.AreEqual(102, queryWithInvalidLevels.TotalItems); - //Check we can call method with an array of logLevel (error & warning) - string [] logLevels = { "Warning", "Error" }; - var queryWithLevels = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, logLevels: logLevels); + // Check we can call method with an array of logLevel (error & warning) + string[] logLevels = { "Warning", "Error" }; + PagedResult queryWithLevels = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, logLevels: logLevels); Assert.AreEqual(7, queryWithLevels.TotalItems); - //Query @Level='Warning' BUT we pass in array of LogLevels for Debug & Info (Expect to get 0 results) + // Query @Level='Warning' BUT we pass in array of LogLevels for Debug & Info (Expect to get 0 results) string[] logLevelMismatch = { "Debug", "Information" }; - var filterLevelQuery = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, filterExpression: "@Level='Warning'", logLevels: logLevelMismatch); + PagedResult filterLevelQuery = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, filterExpression: "@Level='Warning'", logLevels: logLevelMismatch); Assert.AreEqual(0, filterLevelQuery.TotalItems); } @@ -191,17 +202,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging [Test] public void Logs_Can_Query_With_Expressions(string queryToVerify, int expectedCount) { - var testQuery = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, filterExpression: queryToVerify); + PagedResult testQuery = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, filterExpression: queryToVerify); Assert.AreEqual(expectedCount, testQuery.TotalItems); } [Test] public void Log_Search_Can_Persist() { - //Add a new search + // Add a new search _logViewer.AddSavedSearch("Unit Test Example", "Has(UnitTest)"); - var searches = _logViewer.GetSavedSearches(); + IReadOnlyList searches = _logViewer.GetSavedSearches(); var savedSearch = new SavedLogSearch { @@ -209,17 +220,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Logging Query = "Has(UnitTest)" }; - //Check if we can find the newly added item from the results we get back - var findItem = searches.Where(x => x.Name == "Unit Test Example" && x.Query == "Has(UnitTest)"); + // Check if we can find the newly added item from the results we get back + IEnumerable findItem = searches.Where(x => x.Name == "Unit Test Example" && x.Query == "Has(UnitTest)"); Assert.IsNotNull(findItem, "We should have found the saved search, but get no results"); Assert.AreEqual(1, findItem.Count(), "Our list of searches should only contain one result"); // TODO: Need someone to help me find out why these don't work - //CollectionAssert.Contains(searches, savedSearch, "Can not find the new search that was saved"); - //Assert.That(searches, Contains.Item(savedSearch)); + // CollectionAssert.Contains(searches, savedSearch, "Can not find the new search that was saved"); + // Assert.That(searches, Contains.Item(savedSearch)); - //Remove the search from above & ensure it no longer exists + // Remove the search from above & ensure it no longer exists _logViewer.DeleteSavedSearch("Unit Test Example", "Has(UnitTest)"); searches = _logViewer.GetSavedSearches(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Macros/MacroParserTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Macros/MacroParserTests.cs deleted file mode 100644 index 5f282702bb..0000000000 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Macros/MacroParserTests.cs +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Manifest/ManifestContentAppTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Manifest/ManifestContentAppTests.cs deleted file mode 100644 index 5f282702bb..0000000000 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Manifest/ManifestContentAppTests.cs +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Manifest/ManifestParserTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Manifest/ManifestParserTests.cs deleted file mode 100644 index 5f282702bb..0000000000 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Manifest/ManifestParserTests.cs +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Mapping/MappingTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Mapping/MappingTests.cs index ba982cd593..ff443cd944 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Mapping/MappingTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Mapping/MappingTests.cs @@ -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.Threading; @@ -22,7 +25,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping var mapper = new UmbracoMapper(definitions); var thing1 = new Thing1 { Value = "value" }; - var thing2 = mapper.Map(thing1); + Thing2 thing2 = mapper.Map(thing1); Assert.IsNotNull(thing2); Assert.AreEqual("value", thing2.Value); @@ -48,7 +51,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping var thing1A = new Thing1 { Value = "valueA" }; var thing1B = new Thing1 { Value = "valueB" }; - var thing1 = new[] { thing1A, thing1B }; + Thing1[] thing1 = new[] { thing1A, thing1B }; var thing2 = mapper.Map, IEnumerable>(thing1).ToList(); Assert.IsNotNull(thing2); @@ -81,7 +84,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping var mapper = new UmbracoMapper(definitions); var thing3 = new Thing3 { Value = "value" }; - var thing2 = mapper.Map(thing3); + Thing2 thing2 = mapper.Map(thing3); Assert.IsNotNull(thing2); Assert.AreEqual("value", thing2.Value); @@ -107,7 +110,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping // can map a PropertyCollection var source = new PropertyCollection(); - var target = mapper.Map>(source); + IEnumerable target = mapper.Map>(source); } [Test] @@ -129,7 +132,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping // if timing is good, and mapper does have non-concurrent dictionaries, it fails // practically, to reproduce, one needs to add a 1s sleep in the mapper's loop // hence, this test is explicit - var thing3 = new Thing3 { Value = "value" }; var thing4 = new Thing4(); Exception caught = null; @@ -138,6 +140,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping { // keep failing at mapping - and looping through the maps for (var i = 0; i < 10; i++) + { try { mapper.Map(thing4); @@ -147,6 +150,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping caught = e; Console.WriteLine($"{e.GetType().Name} {e.Message}"); } + } Console.WriteLine("done"); } @@ -158,7 +162,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping try { Console.WriteLine($"{DateTime.Now:O} mapping"); - var thing2 = mapper.Map(thing3); + Thing2 thing2 = mapper.Map(thing3); Console.WriteLine($"{DateTime.Now:O} mapped"); Assert.IsNotNull(thing2); @@ -186,7 +190,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping Fruit3 = Thing5Enum.Cherry }; - var thing6 = mapper.Map(thing5); + Thing6 thing6 = mapper.Map(thing5); Assert.IsNotNull(thing6); Assert.AreEqual(Thing6Enum.Apple, thing6.Fruit1); @@ -205,20 +209,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping var thing7 = new Thing7(); - var thing8 = mapper.Map(thing7); + Thing8 thing8 = mapper.Map(thing7); Assert.IsNotNull(thing8); Assert.IsNull(thing8.Things); } - private class Thing1 { public string Value { get; set; } } private class Thing3 : Thing1 - { } + { + } private class Thing2 { @@ -226,12 +230,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping } private class Thing4 - { } + { + } private class Thing5 { public Thing5Enum Fruit1 { get; set; } + public Thing5Enum Fruit2 { get; set; } + public Thing5Enum Fruit3 { get; set; } } @@ -245,7 +252,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping private class Thing6 { public Thing6Enum Fruit1 { get; set; } + public Thing6Enum Fruit2 { get; set; } + public Thing6Enum Fruit3 { get; set; } } @@ -268,26 +277,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping private class MapperDefinition1 : IMapDefinition { - public void DefineMaps(UmbracoMapper mapper) - { - mapper.Define((source, context) => new Thing2(), Map); - } + public void DefineMaps(UmbracoMapper mapper) => mapper.Define((source, context) => new Thing2(), Map); - private void Map(Thing1 source, Thing2 target, MapperContext context) - { - target.Value = source.Value; - } + private void Map(Thing1 source, Thing2 target, MapperContext context) => target.Value = source.Value; } private class MapperDefinition2 : IMapDefinition { - public void DefineMaps(UmbracoMapper mapper) - { + public void DefineMaps(UmbracoMapper mapper) => mapper.Define((source, context) => new ContentPropertyDto(), Map); - } private static void Map(IProperty source, ContentPropertyDto target, MapperContext context) - { } + { + } } private class MapperDefinition3 : IMapDefinition @@ -328,15 +330,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Mapping mapper.Define((source, context) => new Thing8(), Map2); } - private void Map1(Thing1 source, Thing2 target, MapperContext context) - { + private void Map1(Thing1 source, Thing2 target, MapperContext context) => target.Value = source.Value; - } - private void Map2(Thing7 source, Thing8 target, MapperContext context) - { + private void Map2(Thing7 source, Thing8 target, MapperContext context) => target.Things = context.Map>(source.Things); - } } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Media/ImageSharpImageUrlGeneratorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Media/ImageSharpImageUrlGeneratorTests.cs index febb36145b..1ced792520 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Media/ImageSharpImageUrlGeneratorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Media/ImageSharpImageUrlGeneratorTests.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Infrastructure.Media; using Umbraco.Web.Models; @@ -9,36 +12,36 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media public class ImageSharpImageUrlGeneratorTests { private const string MediaPath = "/media/1005/img_0671.jpg"; - private static readonly ImageUrlGenerationOptions.CropCoordinates Crop = new ImageUrlGenerationOptions.CropCoordinates(0.58729977382575338m, 0.055768992440203169m, 0m, 0.32457553600198386m); - private static readonly ImageUrlGenerationOptions.FocalPointPosition Focus1 = new ImageUrlGenerationOptions.FocalPointPosition(0.80827067669172936m, 0.96m); - private static readonly ImageUrlGenerationOptions.FocalPointPosition Focus2 = new ImageUrlGenerationOptions.FocalPointPosition(0.41m, 0.4275m); - private static readonly ImageSharpImageUrlGenerator Generator = new ImageSharpImageUrlGenerator(); + private static readonly ImageUrlGenerationOptions.CropCoordinates s_crop = new ImageUrlGenerationOptions.CropCoordinates(0.58729977382575338m, 0.055768992440203169m, 0m, 0.32457553600198386m); + private static readonly ImageUrlGenerationOptions.FocalPointPosition s_focus1 = new ImageUrlGenerationOptions.FocalPointPosition(0.80827067669172936m, 0.96m); + private static readonly ImageUrlGenerationOptions.FocalPointPosition s_focus2 = new ImageUrlGenerationOptions.FocalPointPosition(0.41m, 0.4275m); + private static readonly ImageSharpImageUrlGenerator s_generator = new ImageSharpImageUrlGenerator(); [Test] public void GetCropUrl_CropAliasTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { Crop = Crop, Width = 100, Height = 100 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { Crop = s_crop, Width = 100, Height = 100 }); Assert.AreEqual(MediaPath + "?crop=0.58729977382575338,0.055768992440203169,0,0.32457553600198386&cropmode=percentage&width=100&height=100", urlString); } [Test] public void GetCropUrl_WidthHeightTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = Focus1, Width = 200, Height = 300 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = s_focus1, Width = 200, Height = 300 }); Assert.AreEqual(MediaPath + "?center=0.80827067669172936,0.96&mode=crop&width=200&height=300", urlString); } [Test] public void GetCropUrl_FocalPointTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = Focus1, Width = 100, Height = 100 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = s_focus1, Width = 100, Height = 100 }); Assert.AreEqual(MediaPath + "?center=0.80827067669172936,0.96&mode=crop&width=100&height=100", urlString); } [Test] public void GetCropUrlFurtherOptionsTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = Focus1, Width = 200, Height = 300, FurtherOptions = "&filter=comic&roundedcorners=radius-26|bgcolor-fff" }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = s_focus1, Width = 200, Height = 300, FurtherOptions = "&filter=comic&roundedcorners=radius-26|bgcolor-fff" }); Assert.AreEqual(MediaPath + "?center=0.80827067669172936,0.96&mode=crop&width=200&height=300&filter=comic&roundedcorners=radius-26|bgcolor-fff", urlString); } @@ -48,7 +51,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrlNullTest() { - var urlString = Generator.GetImageUrl(null); + var urlString = s_generator.GetImageUrl(null); Assert.AreEqual(null, urlString); } @@ -58,7 +61,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrlEmptyTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(null)); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(null)); Assert.AreEqual("?mode=crop", urlString); } @@ -68,7 +71,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetBaseCropUrlFromModelTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(null) { Crop = Crop, Width = 100, Height = 100 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(null) { Crop = s_crop, Width = 100, Height = 100 }); Assert.AreEqual("?crop=0.58729977382575338,0.055768992440203169,0,0.32457553600198386&cropmode=percentage&width=100&height=100", urlString); } @@ -78,7 +81,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_CropAliasHeightRatioModeTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { Crop = Crop, Width = 100, HeightRatio = 1 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { Crop = s_crop, Width = 100, HeightRatio = 1 }); Assert.AreEqual(MediaPath + "?crop=0.58729977382575338,0.055768992440203169,0,0.32457553600198386&cropmode=percentage&heightratio=1&width=100", urlString); } @@ -88,7 +91,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_WidthHeightRatioModeTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = Focus1, Width = 300, HeightRatio = 0.5m }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = s_focus1, Width = 300, HeightRatio = 0.5m }); Assert.AreEqual(MediaPath + "?center=0.80827067669172936,0.96&mode=crop&heightratio=0.5&width=300", urlString); } @@ -98,7 +101,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_HeightWidthRatioModeTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = Focus1, Height = 150, WidthRatio = 2 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = s_focus1, Height = 150, WidthRatio = 2 }); Assert.AreEqual(MediaPath + "?center=0.80827067669172936,0.96&mode=crop&widthratio=2&height=150", urlString); } @@ -108,11 +111,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_SpecifiedCropModeTest() { - var urlStringMin = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Min, Width = 300, Height = 150 }); - var urlStringBoxPad = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.BoxPad, Width = 300, Height = 150 }); - var urlStringPad = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Pad, Width = 300, Height = 150 }); - var urlStringMax = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Max, Width = 300, Height = 150 }); - var urlStringStretch = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Stretch, Width = 300, Height = 150 }); + var urlStringMin = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Min, Width = 300, Height = 150 }); + var urlStringBoxPad = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.BoxPad, Width = 300, Height = 150 }); + var urlStringPad = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Pad, Width = 300, Height = 150 }); + var urlStringMax = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Max, Width = 300, Height = 150 }); + var urlStringStretch = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Stretch, Width = 300, Height = 150 }); Assert.AreEqual(MediaPath + "?mode=min&width=300&height=150", urlStringMin); Assert.AreEqual(MediaPath + "?mode=boxpad&width=300&height=150", urlStringBoxPad); @@ -127,7 +130,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_UploadTypeTest() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Crop, ImageCropAnchor = ImageCropAnchor.Center, Width = 100, Height = 270 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Crop, ImageCropAnchor = ImageCropAnchor.Center, Width = 100, Height = 270 }); Assert.AreEqual(MediaPath + "?mode=crop&anchor=center&width=100&height=270", urlString); } @@ -137,7 +140,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_PreferFocalPointCenter() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Width = 300, Height = 150 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Width = 300, Height = 150 }); Assert.AreEqual(MediaPath + "?anchor=center&mode=crop&width=300&height=150", urlString); } @@ -147,7 +150,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_PreDefinedCropNoCoordinatesWithWidth() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Width = 200, HeightRatio = 0.5962962962962962962962962963m }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Width = 200, HeightRatio = 0.5962962962962962962962962963m }); Assert.AreEqual(MediaPath + "?anchor=center&mode=crop&heightratio=0.5962962962962962962962962963&width=200", urlString); } @@ -157,7 +160,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_PreDefinedCropNoCoordinatesWithWidthAndFocalPoint() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = Focus2, Width = 200, HeightRatio = 0.5962962962962962962962962963m }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = s_focus2, Width = 200, HeightRatio = 0.5962962962962962962962962963m }); Assert.AreEqual(MediaPath + "?center=0.41,0.4275&mode=crop&heightratio=0.5962962962962962962962962963&width=200", urlString); } @@ -167,7 +170,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_PreDefinedCropNoCoordinatesWithWidthAndFocalPointIgnore() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = Focus2, Width = 270, Height = 161 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { FocalPoint = s_focus2, Width = 270, Height = 161 }); Assert.AreEqual(MediaPath + "?center=0.41,0.4275&mode=crop&width=270&height=161", urlString); } @@ -177,7 +180,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_PreDefinedCropNoCoordinatesWithHeight() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Height = 200, WidthRatio = 1.6770186335403726708074534161m }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Height = 200, WidthRatio = 1.6770186335403726708074534161m }); Assert.AreEqual(MediaPath + "?anchor=center&mode=crop&widthratio=1.6770186335403726708074534161&height=200", urlString); } @@ -187,7 +190,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_WidthOnlyParameter() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Width = 200 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Width = 200 }); Assert.AreEqual(MediaPath + "?anchor=center&mode=crop&width=200", urlString); } @@ -197,7 +200,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_HeightOnlyParameter() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Height = 200 }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { DefaultCrop = true, Height = 200 }); Assert.AreEqual(MediaPath + "?anchor=center&mode=crop&height=200", urlString); } @@ -207,7 +210,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Media [Test] public void GetCropUrl_BackgroundColorParameter() { - var urlString = Generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Pad, Width = 400, Height = 400, FurtherOptions = "&bgcolor=fff" }); + var urlString = s_generator.GetImageUrl(new ImageUrlGenerationOptions(MediaPath) { ImageCropMode = ImageCropMode.Pad, Width = 400, Height = 400, FurtherOptions = "&bgcolor=fff" }); Assert.AreEqual(MediaPath + "?mode=pad&width=400&height=400&bgcolor=fff", urlString); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/AlterMigrationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/AlterMigrationTests.cs index 23ee3e143a..c09b354bef 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/AlterMigrationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/AlterMigrationTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Diagnostics; using System.Linq; using Microsoft.Extensions.Logging; @@ -15,7 +18,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations { private readonly ILogger _logger = Mock.Of>(); - [Test] public void Drop_Foreign_Key() { @@ -34,7 +36,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations // Assert Assert.That(database.Operations.Count, Is.EqualTo(1)); - Assert.That(database.Operations[0].Sql, + Assert.That( + database.Operations[0].Sql, Is.EqualTo("ALTER TABLE [umbracoUser2app] DROP CONSTRAINT [FK_umbracoUser2app_umbracoUser_id]")); } @@ -53,7 +56,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations } Assert.That(database.Operations.Count, Is.EqualTo(1)); - Assert.That(database.Operations[0].Sql, + Assert.That( + database.Operations[0].Sql, Is.EqualTo("ALTER TABLE [bar] ADD [foo] UniqueIdentifier NOT NULL")); } @@ -82,7 +86,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations } Assert.That(database.Operations.Count, Is.EqualTo(1)); - Assert.That(database.Operations[0].Sql, + Assert.That( + database.Operations[0].Sql, Is.EqualTo("ALTER TABLE [bar] ALTER COLUMN [foo] UniqueIdentifier NOT NULL")); } @@ -94,8 +99,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations } public override void Migrate() => + // bad/good syntax... - //Alter.Column("foo").OnTable("bar").AsGuid().NotNullable(); + //// Alter.Column("foo").OnTable("bar").AsGuid().NotNullable(); Alter.Table("bar").AlterColumn("foo").AsGuid().NotNullable().Do(); } @@ -114,9 +120,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations // Assert Assert.That(database.Operations.Any(), Is.True); - //Console output + // Console output Debug.Print("Number of expressions in context: {0}", database.Operations.Count); - Debug.Print(""); + Debug.Print(string.Empty); foreach (TestDatabase.Operation expression in database.Operations) { Debug.Print(expression.ToString()); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/MigrationPlanTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/MigrationPlanTests.cs index 0511ee6290..a0d0966b99 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/MigrationPlanTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/MigrationPlanTests.cs @@ -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; @@ -32,8 +35,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations .Setup(x => x.Database) .Returns(database); - var sqlContext = new SqlContext(new SqlServerSyntaxProvider(), DatabaseType.SQLCe, - Mock.Of()); + var sqlContext = new SqlContext(new SqlServerSyntaxProvider(), DatabaseType.SQLCe, Mock.Of()); var scopeProvider = new MigrationTests.TestScopeProvider(scope) { SqlContext = sqlContext }; IMigrationBuilder migrationBuilder = Mock.Of(); @@ -68,8 +70,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations var sourceState = kvs.GetValue("Umbraco.Tests.MigrationPlan") ?? string.Empty; // execute plan - state = plan.Execute(s, sourceState, migrationBuilder, loggerFactory.CreateLogger(), - loggerFactory); + state = plan.Execute(s, sourceState, migrationBuilder, loggerFactory.CreateLogger(), loggerFactory); // save new state kvs.SetValue("Umbraco.Tests.MigrationPlan", sourceState, state); @@ -97,10 +98,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations public void CannotTransitionToSameState() { var plan = new MigrationPlan("default"); - Assert.Throws(() => - { - plan.From("aaa").To("aaa"); - }); + Assert.Throws(() => plan.From("aaa").To("aaa")); } [Test] @@ -108,10 +106,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations { var plan = new MigrationPlan("default"); plan.From("aaa").To("bbb"); - Assert.Throws(() => - { - plan.From("aaa").To("ccc"); - }); + Assert.Throws(() => plan.From("aaa").To("ccc")); } [Test] @@ -191,7 +186,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations WritePlanToConsole(plan); plan.Validate(); - AssertList(plan.FollowPath(), "", "aaa", "bbb", "ccc", "*", "*", "fff", "ggg"); + AssertList(plan.FollowPath(), string.Empty, "aaa", "bbb", "ccc", "*", "*", "fff", "ggg"); AssertList(plan.FollowPath("ccc"), "ccc", "*", "*", "fff", "ggg"); AssertList(plan.FollowPath("eee"), "eee", "*", "*", "fff", "ggg"); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/MigrationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/MigrationTests.cs index 34093d0bce..b37338c08b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/MigrationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/MigrationTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Data; using Microsoft.Extensions.Logging; using Moq; @@ -37,7 +40,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations public IScope DetachScope() => throw new NotImplementedException(); - public IScopeContext Context { get; set; } public ISqlContext SqlContext { get; set; } @@ -85,7 +87,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations { } - public override void Migrate() => Execute.Sql("").Do(); + public override void Migrate() => Execute.Sql(string.Empty).Do(); } public class BadMigration1 : MigrationBase diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/PostMigrationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/PostMigrationTests.cs index 2b3e626d03..d1df3a8098 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/PostMigrationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/PostMigrationTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/AlterUserTableMigrationStub.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/AlterUserTableMigrationStub.cs index ee212fa96f..a5c119f995 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/AlterUserTableMigrationStub.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/AlterUserTableMigrationStub.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Migrations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Migrations; namespace Umbraco.Tests.Migrations.Stubs { @@ -6,7 +9,8 @@ namespace Umbraco.Tests.Migrations.Stubs { public AlterUserTableMigrationStub(IMigrationContext context) : base(context) - { } + { + } public override void Migrate() { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/DropForeignKeyMigrationStub.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/DropForeignKeyMigrationStub.cs index 02561fb563..cf3a26c7d3 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/DropForeignKeyMigrationStub.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/DropForeignKeyMigrationStub.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Migrations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Migrations; namespace Umbraco.Tests.Migrations.Stubs { @@ -6,7 +9,8 @@ namespace Umbraco.Tests.Migrations.Stubs { public DropForeignKeyMigrationStub(IMigrationContext context) : base(context) - { } + { + } public override void Migrate() { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/Dummy.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/Dummy.cs index 1a81120a14..f998c4b8a4 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/Dummy.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/Dummy.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Migrations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Migrations; namespace Umbraco.Tests.Migrations.Stubs { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/FiveZeroMigration.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/FiveZeroMigration.cs index f69862610f..d870ef82db 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/FiveZeroMigration.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/FiveZeroMigration.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Migrations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Migrations; namespace Umbraco.Tests.Migrations.Stubs { @@ -6,9 +9,11 @@ namespace Umbraco.Tests.Migrations.Stubs { public FiveZeroMigration(IMigrationContext context) : base(context) - { } + { + } public override void Migrate() - { } + { + } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/FourElevenMigration.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/FourElevenMigration.cs index fb1d905c0b..c168fa1c8f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/FourElevenMigration.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/FourElevenMigration.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Migrations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Migrations; namespace Umbraco.Tests.Migrations.Stubs { @@ -6,8 +9,8 @@ namespace Umbraco.Tests.Migrations.Stubs { public FourElevenMigration(IMigrationContext context) : base(context) - { } - + { + } public override void Migrate() { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/SixZeroMigration1.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/SixZeroMigration1.cs index d3bdc48cbf..1b5c580d5f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/SixZeroMigration1.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/SixZeroMigration1.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Migrations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Migrations; namespace Umbraco.Tests.Migrations.Stubs { @@ -6,8 +9,8 @@ namespace Umbraco.Tests.Migrations.Stubs { public SixZeroMigration1(IMigrationContext context) : base(context) - { } - + { + } public override void Migrate() { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/SixZeroMigration2.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/SixZeroMigration2.cs index ed3f7b29ea..689e770a98 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/SixZeroMigration2.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Migrations/Stubs/SixZeroMigration2.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Migrations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Migrations; namespace Umbraco.Tests.Migrations.Stubs { @@ -6,8 +9,8 @@ namespace Umbraco.Tests.Migrations.Stubs { public SixZeroMigration2(IMigrationContext context) : base(context) - { } - + { + } public override void Migrate() { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Models/DataTypeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Models/DataTypeTests.cs index b94effb907..71087917b0 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Models/DataTypeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Models/DataTypeTests.cs @@ -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.Infrastructure.Models private DataTypeBuilder _builder; [SetUp] - public void SetUp() - { - _builder = new DataTypeBuilder(); - } + public void SetUp() => _builder = new DataTypeBuilder(); [Test] public void Can_Deep_Clone() { - var dtd = _builder - .WithId(3123) - .Build(); + DataType dtd = _builder + .WithId(3123) + .Build(); - var clone = (DataType) dtd.DeepClone(); + var clone = (DataType)dtd.DeepClone(); Assert.AreNotSame(clone, dtd); Assert.AreEqual(clone, dtd); @@ -41,9 +42,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Models Assert.AreEqual(clone.Trashed, dtd.Trashed); Assert.AreEqual(clone.UpdateDate, dtd.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(dtd, null)); } @@ -52,10 +53,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Models [Test] public void Can_Serialize_Without_Error() { - var item = _builder.Build(); + DataType item = _builder.Build(); Assert.DoesNotThrow(() => JsonConvert.SerializeObject(item)); } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Models/PathValidationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Models/PathValidationTests.cs index 117b9d87cc..8a341687f5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Models/PathValidationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Models/PathValidationTests.cs @@ -1,7 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; -using Microsoft.Extensions.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; using Umbraco.Tests.Common.Builders; @@ -15,114 +18,111 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Models private EntitySlimBuilder _builder; [SetUp] - public void SetUp() - { - _builder = new EntitySlimBuilder(); - } + public void SetUp() => _builder = new EntitySlimBuilder(); [Test] public void Validate_Path() { - var entity = _builder + EntitySlim entity = _builder .WithoutIdentity() .Build(); - //it's empty with no id so we need to allow it + // it's empty with no id so we need to allow it Assert.IsTrue(entity.ValidatePath()); entity.Id = 1234; - //it has an id but no path, so we can't allow it + // it has an id but no path, so we can't allow it Assert.IsFalse(entity.ValidatePath()); entity.Path = "-1"; - //invalid path + // invalid path Assert.IsFalse(entity.ValidatePath()); entity.Path = string.Concat("-1,", entity.Id); - //valid path + // valid path Assert.IsTrue(entity.ValidatePath()); } [Test] public void Ensure_Path_Throws_Without_Id() { - var entity = _builder + EntitySlim entity = _builder .WithoutIdentity() .Build(); - //no id assigned + // no id assigned Assert.Throws(() => entity.EnsureValidPath(Mock.Of>(), umbracoEntity => new EntitySlim(), umbracoEntity => { })); } [Test] public void Ensure_Path_Throws_Without_Parent() { - var entity = _builder + EntitySlim entity = _builder .WithId(1234) .WithNoParentId() .Build(); - //no parent found + // no parent found Assert.Throws(() => entity.EnsureValidPath(Mock.Of>(), umbracoEntity => null, umbracoEntity => { })); } [Test] public void Ensure_Path_Entity_At_Root() { - var entity = _builder + EntitySlim entity = _builder .WithId(1234) .Build(); entity.EnsureValidPath(Mock.Of>(), umbracoEntity => null, umbracoEntity => { }); - //works because it's under the root + // works because it's under the root Assert.AreEqual("-1,1234", entity.Path); } [Test] public void Ensure_Path_Entity_Valid_Parent() { - var entity = _builder + EntitySlim entity = _builder .WithId(1234) .WithParentId(888) .Build(); entity.EnsureValidPath(Mock.Of>(), umbracoEntity => umbracoEntity.ParentId == 888 ? new EntitySlim { Id = 888, Path = "-1,888" } : null, umbracoEntity => { }); - //works because the parent was found + // works because the parent was found Assert.AreEqual("-1,888,1234", entity.Path); } [Test] public void Ensure_Path_Entity_Valid_Recursive_Parent() { - var parentA = _builder + EntitySlim parentA = _builder .WithId(999) .Build(); // Re-creating the class-level builder as we need to reset before usage when creating multiple entities. _builder = new EntitySlimBuilder(); - var parentB = _builder + EntitySlim parentB = _builder .WithId(888) .WithParentId(999) .Build(); _builder = new EntitySlimBuilder(); - var parentC = _builder + EntitySlim parentC = _builder .WithId(777) .WithParentId(888) .Build(); _builder = new EntitySlimBuilder(); - var entity = _builder + EntitySlim entity = _builder .WithId(1234) .WithParentId(777) .Build(); - Func getParent = umbracoEntity => + IUmbracoEntity GetParent(IUmbracoEntity umbracoEntity) { switch (umbracoEntity.ParentId) { @@ -137,10 +137,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Models default: return null; } - }; + } - //this will recursively fix all paths - entity.EnsureValidPath(Mock.Of>(), getParent, umbracoEntity => { }); + // this will recursively fix all paths + entity.EnsureValidPath(Mock.Of>(), GetParent, umbracoEntity => { }); Assert.AreEqual("-1,999", parentA.Path); Assert.AreEqual("-1,999,888", parentB.Path); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/BulkDataReaderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/BulkDataReaderTests.cs index 10926ef20a..e01f071f3c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/BulkDataReaderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/BulkDataReaderTests.cs @@ -1,8 +1,12 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Data.Common; +using System.Data.SqlClient; using NUnit.Framework; using Umbraco.Core.Persistence; @@ -16,11 +20,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence /// See: https://blogs.msdn.microsoft.com/anthonybloesch/2013/01/23/bulk-loading-data-with-idatareader-and-sqlbulkcopy/ /// [TestFixture] - public class BulkDataReaderTest + public class BulkDataReaderTests { - - #region Test constants - /// /// The schema name. /// @@ -56,10 +57,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence /// private const string TestXmlSchemaCollectionName = "Xml"; - #endregion - - #region Schema tests - /// /// Test that is functioning correctly. /// @@ -69,12 +66,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence { using (var testReader = new BulkDataReaderSubclass()) { - var columnMappings = testReader.ColumnMappings; + ReadOnlyCollection columnMappings = testReader.ColumnMappings; Assert.IsTrue(columnMappings.Count > 0); Assert.AreEqual(columnMappings.Count, testReader.FieldCount); - foreach (var columnMapping in columnMappings) + foreach (SqlBulkCopyColumnMapping columnMapping in columnMappings) { Assert.AreEqual(columnMapping.SourceColumn, columnMapping.DestinationColumn); } @@ -82,9 +79,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence } /// - /// Test that is functioning correctly. + /// Test that is functioning correctly. /// - /// + /// [Test] public void GetDataTypeNameTest() { @@ -92,19 +89,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence { Assert.IsTrue(testReader.FieldCount > 0); - for (var currentColumn = 0; currentColumn < testReader.FieldCount; currentColumn++) + for (int currentColumn = 0; currentColumn < testReader.FieldCount; currentColumn++) { - var schemaTable = testReader.GetSchemaTable(); + DataTable schemaTable = testReader.GetSchemaTable(); Assert.IsNotNull(schemaTable); - Assert.AreEqual(testReader.GetDataTypeName(currentColumn), ((Type) schemaTable.Rows[currentColumn][SchemaTableColumn.DataType]).Name); + Assert.AreEqual(testReader.GetDataTypeName(currentColumn), ((Type)schemaTable.Rows[currentColumn][SchemaTableColumn.DataType]).Name); } } } /// - /// Test that is functioning correctly. + /// Test that is functioning correctly. /// - /// + /// [Test] public void GetFieldTypeTest() { @@ -112,9 +109,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence { Assert.IsTrue(testReader.FieldCount > 0); - for (var currentColumn = 0; currentColumn < testReader.FieldCount; currentColumn++) + for (int currentColumn = 0; currentColumn < testReader.FieldCount; currentColumn++) { - var schemaTable = testReader.GetSchemaTable(); + DataTable schemaTable = testReader.GetSchemaTable(); Assert.IsNotNull(schemaTable); Assert.AreEqual(testReader.GetFieldType(currentColumn), schemaTable.Rows[currentColumn][SchemaTableColumn.DataType]); } @@ -122,9 +119,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence } /// - /// Test that is functioning correctly. + /// Test that is functioning correctly. /// - /// + /// [Test] public void GetOrdinalTest() { @@ -132,7 +129,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence { Assert.IsTrue(testReader.FieldCount > 0); - for (var currentColumn = 0; currentColumn < testReader.FieldCount; currentColumn++) + for (int currentColumn = 0; currentColumn < testReader.FieldCount; currentColumn++) { Assert.AreEqual(testReader.GetOrdinal(testReader.GetName(currentColumn)), currentColumn); Assert.AreEqual(testReader.GetOrdinal(testReader.GetName(currentColumn).ToUpperInvariant()), currentColumn); @@ -152,7 +149,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence { using (var testReader = new BulkDataReaderSubclass()) { - var schemaTable = testReader.GetSchemaTable(); + DataTable schemaTable = testReader.GetSchemaTable(); Assert.IsNotNull(schemaTable); Assert.IsTrue(schemaTable.Rows.Count > 0); @@ -161,13 +158,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence } /// - /// Test that + /// Test that /// throws a for null column names. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowNullColumnNameTest() { @@ -189,19 +186,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for empty column names. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowEmptyColumnNameTest() { @@ -223,19 +220,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for nonpositive column sizes. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowNonpositiveColumnSizeTest() { @@ -257,19 +254,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for nonpositive numeric precision. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowNonpositiveNumericPrecisionTest() { @@ -291,19 +288,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for negative numeric scale. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowNegativeNumericScaleTest() { @@ -325,19 +322,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for binary column without a column size. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowBinaryWithoutSizeTest() { @@ -359,19 +356,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for binary column with a column size that is too large (>8000). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowBinaryWithTooLargeSizeTest() { @@ -393,19 +390,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for char column without a column size. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowCharWithoutSizeTest() { @@ -427,19 +424,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for char column with a column size that is too large (>8000). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowCharWithTooLargeSizeTest() { @@ -461,19 +458,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for decimal column without a column precision. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowDecimalWithoutPrecisionTest() { @@ -495,19 +492,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for decimal column without a column scale. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowDecimalWithoutScaleTest() { @@ -529,19 +526,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for decimal column with a column precision that is too large (>38). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowDecimalWithTooLargePrecisionTest() { @@ -563,19 +560,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for decimal column with a column scale that is larger than the column precision. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowDecimalWithTooLargeScaleTest() { @@ -597,19 +594,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for datetime2 column with a column size that has a precision that is too large (>7). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowDateTime2WithTooLargePrecisionTest() { @@ -631,19 +628,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for datetimeoffset column with a column size that has a precision that is too large (>7). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowDateTimeOffsetWithTooLargePrecisionTest() { @@ -665,19 +662,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for nchar column without a precision. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowFloatWithoutPrecisionTest() { @@ -699,19 +696,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for float column with a column precision that is too large (>53). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowFloatWithTooLargePrecisionTest() { @@ -733,19 +730,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for nchar column without a column size. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowNCharWithoutSizeTest() { @@ -767,19 +764,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for nchar column with a column size that is too large (>4000). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowNCharWithTooLargeSizeTest() { @@ -801,19 +798,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for nvarchar column with a column size that is too large (>4000). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowNVarCharWithTooLargeSizeTest() { @@ -835,19 +832,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for time column with a column precision that is too large (>7). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowTimeWithTooLargePrecisionTest() { @@ -869,19 +866,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for missing UDT schema name. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowUdtMissingSchemaNameTest() { @@ -903,19 +900,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for empty UDT schema name. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowUdtEmptySchemaNameTest() { @@ -937,19 +934,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for missing UDT name. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowUdtMissingNameTest() { @@ -971,19 +968,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for empty UDT name. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowUdtEmptyNameTest() { @@ -1005,19 +1002,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for varbinary column with a column size that is too large (>8000). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowVarBinaryWithTooLargeSizeTest() { @@ -1039,19 +1036,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for varchar column with a column size that is too large (>8000). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowVarCharWithTooLargeSizeTest() { @@ -1073,19 +1070,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for null xml collection name but with a name for the database. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowXmlNullNameWithDatabaseNameTest() { @@ -1107,19 +1104,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for null xml collection name. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowXmlNullNameWithOwningSchemaNameTest() { @@ -1141,19 +1138,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for empty xml collection database name. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowXmlEmptyDatabaseNameTest() { @@ -1175,19 +1172,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for empty xml collection owning schema name. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowXmlEmptyOwningSchemaNameTest() { @@ -1209,19 +1206,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for empty xml collection name. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowXmlEmptyNameTest() { @@ -1243,19 +1240,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for a structured column (which is illegal). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowStructuredTypeTest() { @@ -1277,19 +1274,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws a for a timestamp column (which is illegal). /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowTimestampTypeTest() { @@ -1311,23 +1308,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); }); } } /// - /// Test that + /// Test that /// throws an for a column with an unallowed optional column set. /// /// /// Uses to test the illegal schema combination. /// - /// + /// [Test] public void AddSchemaTableRowUnallowedOptionalColumnTest() { - // Column size set using (var testReader = new BulkDataReaderSchemaTest()) { @@ -1344,17 +1340,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence testReader.XmlSchemaCollectionOwningSchema = null; testReader.XmlSchemaCollectionName = null; - foreach (var dbtype in new List { SqlDbType.BigInt, SqlDbType.Bit, SqlDbType.Date, SqlDbType.DateTime, SqlDbType.DateTime2, - SqlDbType.DateTimeOffset, SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.Real, - SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, SqlDbType.Structured, SqlDbType.Text, - SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, SqlDbType.Udt, SqlDbType.UniqueIdentifier, - SqlDbType.Variant, SqlDbType.Xml }) + foreach (SqlDbType dbtype in new List + { + SqlDbType.BigInt, SqlDbType.Bit, SqlDbType.Date, SqlDbType.DateTime, SqlDbType.DateTime2, + SqlDbType.DateTimeOffset, SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.Real, + SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, SqlDbType.Structured, SqlDbType.Text, + SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, SqlDbType.Udt, SqlDbType.UniqueIdentifier, + SqlDbType.Variant, SqlDbType.Xml + }) { testReader.ProviderType = dbtype; try { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); Assert.Fail(); } @@ -1380,18 +1379,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence testReader.XmlSchemaCollectionOwningSchema = null; testReader.XmlSchemaCollectionName = null; - foreach (var dbtype in new List { SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, - SqlDbType.DateTime, SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, - SqlDbType.NText, SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, - SqlDbType.SmallMoney, SqlDbType.Structured, SqlDbType.Text, SqlDbType.Timestamp, SqlDbType.TinyInt, - SqlDbType.Udt, SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, - SqlDbType.Xml }) + foreach (SqlDbType dbtype in new List + { + SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, + SqlDbType.DateTime, SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, + SqlDbType.NText, SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, + SqlDbType.SmallMoney, SqlDbType.Structured, SqlDbType.Text, SqlDbType.Timestamp, SqlDbType.TinyInt, + SqlDbType.Udt, SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, + SqlDbType.Xml + }) { testReader.ProviderType = dbtype; try { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); Assert.Fail(); } @@ -1417,18 +1419,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence testReader.XmlSchemaCollectionOwningSchema = null; testReader.XmlSchemaCollectionName = null; - foreach (var dbtype in new List { SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, - SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Image, SqlDbType.Int, - SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, SqlDbType.NVarChar, SqlDbType.Real, - SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, SqlDbType.Structured, SqlDbType.Text, - SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, SqlDbType.Udt, SqlDbType.UniqueIdentifier, - SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Xml }) + foreach (SqlDbType dbtype in new List + { + SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, + SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Image, SqlDbType.Int, + SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, SqlDbType.NVarChar, SqlDbType.Real, + SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, SqlDbType.Structured, SqlDbType.Text, + SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, SqlDbType.Udt, SqlDbType.UniqueIdentifier, + SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Xml + }) { testReader.ProviderType = dbtype; try { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); Assert.Fail(); } @@ -1454,18 +1459,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence testReader.XmlSchemaCollectionOwningSchema = null; testReader.XmlSchemaCollectionName = null; - foreach (var dbtype in new List { SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, - SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Image, SqlDbType.Int, - SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, SqlDbType.NVarChar, SqlDbType.Real, - SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, SqlDbType.Structured, SqlDbType.Text, - SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, SqlDbType.Udt, SqlDbType.UniqueIdentifier, - SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Xml }) + foreach (SqlDbType dbtype in new List + { + SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, + SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Image, SqlDbType.Int, + SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, SqlDbType.NVarChar, SqlDbType.Real, + SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, SqlDbType.Structured, SqlDbType.Text, + SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, SqlDbType.Udt, SqlDbType.UniqueIdentifier, + SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Xml + }) { testReader.ProviderType = dbtype; try { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); Assert.Fail(); } @@ -1491,18 +1499,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence testReader.XmlSchemaCollectionOwningSchema = null; testReader.XmlSchemaCollectionName = null; - foreach (var dbtype in new List { SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, - SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, - SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, - SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, - SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, - SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Xml }) + foreach (SqlDbType dbtype in new List + { + SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, + SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, + SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, + SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, + SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, + SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Xml + }) { testReader.ProviderType = dbtype; try { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); Assert.Fail(); } @@ -1528,18 +1539,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence testReader.XmlSchemaCollectionOwningSchema = null; testReader.XmlSchemaCollectionName = null; - foreach (var dbtype in new List { SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, - SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, - SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, - SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, - SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, - SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Xml }) + foreach (SqlDbType dbtype in new List + { + SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, + SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, + SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, + SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, + SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, + SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Xml + }) { testReader.ProviderType = dbtype; try { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); Assert.Fail(); } @@ -1565,18 +1579,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence testReader.XmlSchemaCollectionOwningSchema = null; testReader.XmlSchemaCollectionName = "Name"; - foreach (var dbtype in new List { SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, - SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, - SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, - SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, - SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, - SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Udt }) + foreach (SqlDbType dbtype in new List + { + SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, + SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, + SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, + SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, + SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, + SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Udt + }) { testReader.ProviderType = dbtype; try { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); Assert.Fail(); } @@ -1602,18 +1619,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence testReader.XmlSchemaCollectionOwningSchema = "Schema"; testReader.XmlSchemaCollectionName = "Name"; - foreach (var dbtype in new List { SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, - SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, - SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, - SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, - SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, - SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Udt }) + foreach (SqlDbType dbtype in new List + { + SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, + SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, + SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, + SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, + SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, + SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Udt + }) { testReader.ProviderType = dbtype; try { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); Assert.Fail(); } @@ -1639,18 +1659,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence testReader.XmlSchemaCollectionOwningSchema = "Schema"; testReader.XmlSchemaCollectionName = "Name"; - foreach (var dbtype in new List { SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, - SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, - SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, - SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, - SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, - SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Udt }) + foreach (SqlDbType dbtype in new List + { + SqlDbType.BigInt, SqlDbType.Binary, SqlDbType.Bit, SqlDbType.Char, SqlDbType.Date, + SqlDbType.DateTime, SqlDbType.DateTime2, SqlDbType.DateTimeOffset, SqlDbType.Decimal, SqlDbType.Float, + SqlDbType.Image, SqlDbType.Int, SqlDbType.Money, SqlDbType.NChar, SqlDbType.NText, + SqlDbType.NVarChar, SqlDbType.Real, SqlDbType.SmallDateTime, SqlDbType.SmallInt, SqlDbType.SmallMoney, + SqlDbType.Structured, SqlDbType.Text, SqlDbType.Time, SqlDbType.Timestamp, SqlDbType.TinyInt, + SqlDbType.UniqueIdentifier, SqlDbType.VarBinary, SqlDbType.VarChar, SqlDbType.Variant, SqlDbType.Udt + }) { testReader.ProviderType = dbtype; try { - var unused = testReader.GetSchemaTable(); + DataTable unused = testReader.GetSchemaTable(); Assert.Fail(); } @@ -1661,10 +1684,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence } } - #endregion; - - #region Rowset tests - /// /// Test that is functioning correctly. /// @@ -1698,12 +1717,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence } /// - /// Test that is functioning correctly. + /// Test that is functioning correctly. /// /// /// Because nested row sets are not supported, this should always return null; /// - /// + /// [Test] public void GetDataTest() { @@ -1718,7 +1737,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence } /// - /// Test and related functions. + /// Test and related functions. /// /// /// Uses to test legal schema combinations. @@ -1731,13 +1750,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.IsTrue(testReader.Read()); // this[int] - for (var column = 0; column < BulkDataReaderSubclass.ExpectedResultSet.Count; column++) + for (int column = 0; column < BulkDataReaderSubclass.ExpectedResultSet.Count; column++) { Assert.AreEqual(testReader[column], BulkDataReaderSubclass.ExpectedResultSet[column]); } // this[string] - for (var column = 0; column < BulkDataReaderSubclass.ExpectedResultSet.Count; column++) + for (int column = 0; column < BulkDataReaderSubclass.ExpectedResultSet.Count; column++) { Assert.AreEqual(testReader[testReader.GetName(column)], BulkDataReaderSubclass.ExpectedResultSet[column]); @@ -1746,8 +1765,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence // GetValues { - var values = new object[BulkDataReaderSubclass.ExpectedResultSet.Count]; - var expectedValues = new object[BulkDataReaderSubclass.ExpectedResultSet.Count]; + object[] values = new object[BulkDataReaderSubclass.ExpectedResultSet.Count]; + object[] expectedValues = new object[BulkDataReaderSubclass.ExpectedResultSet.Count]; Assert.AreEqual(testReader.GetValues(values), values.Length); @@ -1758,20 +1777,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence // Typed getters { - var currentColumn = 0; + int currentColumn = 0; Assert.AreEqual(testReader.GetInt64(currentColumn), BulkDataReaderSubclass.ExpectedResultSet[currentColumn]); currentColumn++; - { - var expectedResult = (byte[])BulkDataReaderSubclass.ExpectedResultSet[currentColumn]; - var expectedLength = expectedResult.Length; - var buffer = new byte[expectedLength]; + byte[] expectedResult = (byte[])BulkDataReaderSubclass.ExpectedResultSet[currentColumn]; + int expectedLength = expectedResult.Length; + byte[] buffer = new byte[expectedLength]; Assert.AreEqual(testReader.GetBytes(currentColumn, 0, buffer, 0, expectedLength), expectedLength); Assert.IsTrue(ArraysMatch(buffer, expectedResult)); } + currentColumn++; Assert.AreEqual(testReader.GetBoolean(currentColumn), BulkDataReaderSubclass.ExpectedResultSet[currentColumn]); @@ -1790,11 +1809,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence currentColumn++; Assert.AreEqual(testReader.GetString(currentColumn), BulkDataReaderSubclass.ExpectedResultSet[currentColumn]); - { - var expectedResult = ((string)BulkDataReaderSubclass.ExpectedResultSet[currentColumn]).ToCharArray(); - var expectedLength = expectedResult.Length; - var buffer = new char[expectedLength]; + char[] expectedResult = ((string)BulkDataReaderSubclass.ExpectedResultSet[currentColumn]).ToCharArray(); + int expectedLength = expectedResult.Length; + char[] buffer = new char[expectedLength]; Assert.AreEqual(testReader.GetChars(currentColumn, 0, buffer, 0, expectedLength), expectedLength); @@ -1826,7 +1844,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.AreEqual(testReader.GetDouble(currentColumn), BulkDataReaderSubclass.ExpectedResultSet[currentColumn]); currentColumn++; - { byte[] expectedResult = (byte[])BulkDataReaderSubclass.ExpectedResultSet[currentColumn]; int expectedLength = expectedResult.Length; @@ -1836,6 +1853,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.IsTrue(ArraysMatch(buffer, expectedResult)); } + currentColumn++; Assert.AreEqual(testReader.GetInt32(currentColumn), BulkDataReaderSubclass.ExpectedResultSet[currentColumn]); @@ -1885,20 +1903,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.AreEqual(testReader.GetGuid(currentColumn), BulkDataReaderSubclass.ExpectedResultSet[currentColumn]); currentColumn++; - { - var expectedResult = (byte[])BulkDataReaderSubclass.ExpectedResultSet[currentColumn]; - var expectedLength = expectedResult.Length; - var buffer = new byte[expectedLength]; - - Assert.AreEqual(testReader.GetBytes(currentColumn, 0, buffer, 0, expectedLength), expectedLength); - - Assert.IsTrue(ArraysMatch(buffer, expectedResult)); - } - currentColumn++; - - { - var expectedResult = (byte[])BulkDataReaderSubclass.ExpectedResultSet[currentColumn]; + byte[] expectedResult = (byte[])BulkDataReaderSubclass.ExpectedResultSet[currentColumn]; int expectedLength = expectedResult.Length; byte[] buffer = new byte[expectedLength]; @@ -1906,6 +1912,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.IsTrue(ArraysMatch(buffer, expectedResult)); } + + currentColumn++; + { + byte[] expectedResult = (byte[])BulkDataReaderSubclass.ExpectedResultSet[currentColumn]; + int expectedLength = expectedResult.Length; + byte[] buffer = new byte[expectedLength]; + + Assert.AreEqual(testReader.GetBytes(currentColumn, 0, buffer, 0, expectedLength), expectedLength); + + Assert.IsTrue(ArraysMatch(buffer, expectedResult)); + } + currentColumn++; Assert.AreEqual(testReader.GetString(currentColumn), BulkDataReaderSubclass.ExpectedResultSet[currentColumn]); @@ -1935,13 +1953,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence } /// - /// Test throws a when + /// Test throws a when /// the index is too small. /// /// /// Uses to test the method. /// - /// + /// [Test] public void GetValueIndexTooSmallTest() { @@ -1951,19 +1969,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetValue(-1); + object unused = testReader.GetValue(-1); }); } } /// - /// Test throws a when + /// Test throws a when /// the index is too large. /// /// /// Uses to test the method. /// - /// + /// [Test] public void GetValueIndexTooLargeTest() { @@ -1973,19 +1991,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetValue(testReader.FieldCount); + object unused = testReader.GetValue(testReader.FieldCount); }); } } /// - /// Test throws a when + /// Test throws a when /// the index is too small. /// /// /// Uses to test the method. /// - /// + /// [Test] public void GetDataIndexTooSmallTest() { @@ -1995,13 +2013,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetData(-1); + IDataReader unused = testReader.GetData(-1); }); } } /// - /// Test throws a when + /// Test throws a when /// the index is too large. /// /// @@ -2016,21 +2034,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence Assert.Throws(() => { - var unused = testReader.GetData(testReader.FieldCount); + IDataReader unused = testReader.GetData(testReader.FieldCount); }); } } /// - /// Test that functions correctly. + /// Test that functions correctly. /// - /// + /// [Test] public void IsDbNullTest() { using (var testReader = new BulkDataReaderSubclass()) { - for (var currentColumn = 0; currentColumn < testReader.FieldCount; currentColumn++) + for (int currentColumn = 0; currentColumn < testReader.FieldCount; currentColumn++) { Assert.AreEqual(testReader.IsDBNull(currentColumn), BulkDataReaderSubclass.ExpectedResultSet[currentColumn] == null); } @@ -2071,10 +2089,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence } } - #endregion - - #region Test IDisposable - /// /// Test that the interface is functioning correctly. /// @@ -2104,27 +2118,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence } } - #endregion - - #region Utility - /// - /// Do the two arrays match exactly? + /// Do the two arrays match exactly? /// - /// + /// /// The type of the array elements. /// /// - /// The first array. + /// The first array. /// /// - /// The second array. + /// The second array. /// /// - /// True if the arrays have the same length and contents. + /// True if the arrays have the same length and contents. /// - private static bool ArraysMatch(ElementType[] left, - ElementType[] right) + private static bool ArraysMatch(TElementType[] left, TElementType[] right) { if (left == null) { @@ -2152,18 +2161,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence return result; } - #endregion - - #region Test stubs - /// /// A subclass of used for testing its utility functions. /// private class BulkDataReaderSubclass : BulkDataReader { - - #region Constructors - /// /// Constructor. /// @@ -2171,31 +2173,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence { } - #endregion - - #region BulkDataReader - /// /// See . /// /// - /// Returns . + /// Returns . /// - protected override string SchemaName - { - get { return BulkDataReaderTest.TestSchemaName; } - } + protected override string SchemaName => BulkDataReaderTests.TestSchemaName; /// /// See . /// /// - /// Returns . + /// Returns . /// - protected override string TableName - { - get { return BulkDataReaderTest.TestTableName; } - } + protected override string TableName => BulkDataReaderTests.TestTableName; /// /// See @@ -2236,17 +2228,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence AddSchemaTableRow("Time", null, null, null, false, false, false, SqlDbType.Time, null, null, null, null, null); AddSchemaTableRow("Time_5", null, 5, null, false, false, false, SqlDbType.Time, null, null, null, null, null); AddSchemaTableRow("TinyInt", null, null, null, false, false, false, SqlDbType.TinyInt, null, null, null, null, null); - AddSchemaTableRow("Udt", null, null, null, false, false, false, SqlDbType.Udt, BulkDataReaderTest.TestUdtSchemaName, BulkDataReaderTest.TestUdtName, null, null, null); + AddSchemaTableRow("Udt", null, null, null, false, false, false, SqlDbType.Udt, BulkDataReaderTests.TestUdtSchemaName, BulkDataReaderTests.TestUdtName, null, null, null); AddSchemaTableRow("UniqueIdentifier", null, null, null, false, false, false, SqlDbType.UniqueIdentifier, null, null, null, null, null); AddSchemaTableRow("VarBinary_20", 20, null, null, false, false, false, SqlDbType.VarBinary, null, null, null, null, null); AddSchemaTableRow("VarBinary_Max", null, null, null, false, false, false, SqlDbType.VarBinary, null, null, null, null, null); AddSchemaTableRow("VarChar_20", 20, null, null, false, false, false, SqlDbType.VarChar, null, null, null, null, null); AddSchemaTableRow("VarChar_Max", null, null, null, false, false, false, SqlDbType.VarChar, null, null, null, null, null); AddSchemaTableRow("Variant", null, null, null, false, false, false, SqlDbType.Variant, null, null, null, null, null); - AddSchemaTableRow("Xml_Database", null, null, null, false, false, false, SqlDbType.Xml, null, null, BulkDataReaderTest.TestXmlSchemaCollectionDatabaseName, BulkDataReaderTest.TestXmlSchemaCollectionSchemaName, BulkDataReaderTest.TestXmlSchemaCollectionName); - AddSchemaTableRow("Xml_Database_XML", null, null, null, false, false, false, SqlDbType.Xml, null, null, BulkDataReaderTest.TestXmlSchemaCollectionDatabaseName, BulkDataReaderTest.TestXmlSchemaCollectionSchemaName, BulkDataReaderTest.TestXmlSchemaCollectionName); - AddSchemaTableRow("Xml_Schema", null, null, null, false, false, false, SqlDbType.Xml, null, null, null, BulkDataReaderTest.TestXmlSchemaCollectionSchemaName, BulkDataReaderTest.TestXmlSchemaCollectionName); - AddSchemaTableRow("Xml_Xml", null, null, null, false, false, false, SqlDbType.Xml, null, null, null, null, BulkDataReaderTest.TestXmlSchemaCollectionName); + AddSchemaTableRow("Xml_Database", null, null, null, false, false, false, SqlDbType.Xml, null, null, BulkDataReaderTests.TestXmlSchemaCollectionDatabaseName, BulkDataReaderTests.TestXmlSchemaCollectionSchemaName, BulkDataReaderTests.TestXmlSchemaCollectionName); + AddSchemaTableRow("Xml_Database_XML", null, null, null, false, false, false, SqlDbType.Xml, null, null, BulkDataReaderTests.TestXmlSchemaCollectionDatabaseName, BulkDataReaderTests.TestXmlSchemaCollectionSchemaName, BulkDataReaderTests.TestXmlSchemaCollectionName); + AddSchemaTableRow("Xml_Schema", null, null, null, false, false, false, SqlDbType.Xml, null, null, null, BulkDataReaderTests.TestXmlSchemaCollectionSchemaName, BulkDataReaderTests.TestXmlSchemaCollectionName); + AddSchemaTableRow("Xml_Xml", null, null, null, false, false, false, SqlDbType.Xml, null, null, null, null, BulkDataReaderTests.TestXmlSchemaCollectionName); AddSchemaTableRow("Xml", null, null, null, false, false, false, SqlDbType.Xml, null, null, null, null, null); } @@ -2255,7 +2247,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence /// public static readonly ReadOnlyCollection ExpectedResultSet = new ReadOnlyCollection(new List { - (long)10, + 10L, new byte[20], true, null, @@ -2269,19 +2261,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence DateTime.UtcNow, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, - (decimal)10.5, + 10.5M, (double)10.5, new byte[20], (int)10, - (decimal)10.5, + 10.5M, "nchar 20", "ntext", "nvarchar 20", "nvarchar max", - (float)10.5, + 10.5F, DateTime.UtcNow, (short)10, - (decimal)10.5, + 10.5M, "text", DateTime.UtcNow.TimeOfDay, DateTime.UtcNow.TimeOfDay, @@ -2301,7 +2293,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence }); /// - /// See + /// See /// /// /// The zero-based column ordinal. @@ -2309,16 +2301,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence /// /// The value of the column in . /// - /// - public override object GetValue(int i) - { - return BulkDataReaderSubclass.ExpectedResultSet[i]; - } + /// + public override object GetValue(int i) => BulkDataReaderSubclass.ExpectedResultSet[i]; /// /// The number of rows read. /// - private int readCount = 0; + private int _readCount = 0; /// /// See @@ -2327,89 +2316,76 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence /// True if there are more rows; otherwise, false. /// /// - public override bool Read() - { - return readCount++ < 1; - } - - #endregion - + public override bool Read() => _readCount++ < 1; } private class BulkDataReaderSchemaTest : BulkDataReader { - - #region Properties - /// - /// Is the column nullable (i.e. optional)? + /// Gets or sets a value indicating whether the column is nullable (i.e. optional). /// public bool AllowDBNull { get; set; } /// - /// The name of the column. + /// Gets or sets the name of the column. /// public string ColumnName { get; set; } /// - /// The size of the column which may be null if not applicable. + /// Gets or sets the size of the column which may be null if not applicable. /// public int? ColumnSize { get; set; } /// - /// Is the column part of the primary key? + /// Gets or sets a value indicating whether the column part of the primary key. /// public bool IsKey { get; set; } /// - /// Are the column values unique (i.e. never duplicated)? + /// Gets or sets a value indicating whether the column values are unique (i.e. never duplicated). /// public bool IsUnique { get; set; } /// - /// The precision of the column which may be null if not applicable. + /// Gets or sets the precision of the column which may be null if not applicable. /// public short? NumericPrecision { get; set; } /// - /// The scale of the column which may be null if not applicable. + /// Gets or sets the scale of the column which may be null if not applicable. /// public short? NumericScale { get; set; } /// - /// The corresponding . + /// Gets or sets the corresponding . /// public SqlDbType ProviderType { get; set; } /// - /// The schema name of the UDT. + /// Gets or sets the schema name of the UDT. /// public string UdtSchema { get; set; } /// - /// The type name of the UDT. + /// Gets or sets the type name of the UDT. /// public string UdtType { get; set; } /// - /// For XML columns the schema collection's database name. Otherwise, null. + /// Gets or sets the schema collection's database name for XML columns. Otherwise, null. /// public string XmlSchemaCollectionDatabase { get; set; } /// - /// For XML columns the schema collection's name. Otherwise, null. + /// Gets or sets the schema collection's name for XML columns. Otherwise, null. /// public string XmlSchemaCollectionName { get; set; } /// - /// For XML columns the schema collection's schema name. Otherwise, null. + /// Gets or sets the schema collection's scheme name for XML columns. Otherwise, null. /// public string XmlSchemaCollectionOwningSchema { get; set; } - #endregion - - #region Constructors - /// /// Constructor. /// @@ -2417,31 +2393,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence { } - #endregion - - #region BulkDataReader - /// /// See . /// /// - /// Returns . + /// Returns . /// - protected override string SchemaName - { - get { return BulkDataReaderTest.TestSchemaName; } - } + protected override string SchemaName => BulkDataReaderTests.TestSchemaName; /// /// See . /// /// - /// Returns . + /// Returns . /// - protected override string TableName - { - get { return BulkDataReaderTest.TestTableName; } - } + protected override string TableName => BulkDataReaderTests.TestTableName; /// /// See @@ -2449,25 +2415,24 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence /// /// Creates a schema row for the various values. /// - protected override void AddSchemaTableRows() - { - AddSchemaTableRow(this.ColumnName, - this.ColumnSize, - this.NumericPrecision, - this.NumericScale, - this.IsUnique, - this.IsKey, - this.AllowDBNull, - this.ProviderType, - this.UdtSchema, - this.UdtType, - this.XmlSchemaCollectionDatabase, - this.XmlSchemaCollectionOwningSchema, - this.XmlSchemaCollectionName); - } + protected override void AddSchemaTableRows() => + AddSchemaTableRow( + ColumnName, + ColumnSize, + NumericPrecision, + NumericScale, + IsUnique, + IsKey, + AllowDBNull, + ProviderType, + UdtSchema, + UdtType, + XmlSchemaCollectionDatabase, + XmlSchemaCollectionOwningSchema, + XmlSchemaCollectionName); /// - /// See + /// See /// /// /// The test stub is only for testing schema functionality and behaves as if it has no rows. @@ -2478,12 +2443,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence /// /// Never returns. /// - /// - public override object GetValue(int i) - { - throw new InvalidOperationException("No data."); - } - + /// + public override object GetValue(int i) => throw new InvalidOperationException("No data."); /// /// See @@ -2492,15 +2453,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence /// False. /// /// - public override bool Read() - { - return false; - } - - #endregion - + public override bool Read() => false; } - - #endregion } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/ContentMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/ContentMapperTest.cs index 7c0ea0d642..5db6493858 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/ContentMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/ContentMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Mappers; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/ContentTypeMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/ContentTypeMapperTest.cs index 6666055ed7..923de28f13 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/ContentTypeMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/ContentTypeMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; @@ -20,7 +23,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_Name_Property() { - // Act string column = new ContentTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Name"); @@ -31,7 +33,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_Thumbnail_Property() { - // Act string column = new ContentTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Thumbnail"); @@ -42,7 +43,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_Description_Property() { - // Act string column = new ContentTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Description"); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DataTypeMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DataTypeMapperTest.cs index 0725528254..7fdd2882c4 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DataTypeMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DataTypeMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; @@ -21,7 +24,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_Key_Property() { - // Act string column = new DataTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Key"); @@ -32,7 +34,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_DatabaseType_Property() { - // Act string column = new DataTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("DatabaseType"); @@ -43,7 +44,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_PropertyEditorAlias_Property() { - // Act string column = new DataTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("EditorAlias"); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DictionaryMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DictionaryMapperTest.cs index a27fc89dac..f31110f30a 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DictionaryMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DictionaryMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; @@ -20,7 +23,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_Key_Property() { - // Act string column = new DictionaryMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Key"); @@ -31,7 +33,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_ItemKey_Property() { - // Act string column = new DictionaryMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("ItemKey"); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DictionaryTranslationMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DictionaryTranslationMapperTest.cs index c1fbc6ad61..ebe57e7746 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DictionaryTranslationMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/DictionaryTranslationMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; @@ -10,7 +13,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_Key_Property() { - // Act string column = new DictionaryTranslationMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Key"); @@ -21,7 +23,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_Language_Property() { - // Act string column = new DictionaryTranslationMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Language"); @@ -32,7 +33,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_Value_Property() { - // Act string column = new DictionaryTranslationMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Value"); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/LanguageMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/LanguageMapperTest.cs index 382d8c6826..20a446ad70 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/LanguageMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/LanguageMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; @@ -10,7 +13,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_Id_Property() { - // Act string column = new LanguageMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Id"); @@ -21,7 +23,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_IsoCode_Property() { - // Act string column = new LanguageMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("IsoCode"); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/MediaMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/MediaMapperTest.cs index cc7d528c3c..a94e4cade3 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/MediaMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/MediaMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/PropertyGroupMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/PropertyGroupMapperTest.cs index f5fa18e4ee..40c74f25a5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/PropertyGroupMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/PropertyGroupMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/PropertyTypeMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/PropertyTypeMapperTest.cs index ba2d40feab..72223e952f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/PropertyTypeMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/PropertyTypeMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/RelationMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/RelationMapperTest.cs index 4f1b4a7944..add7cd8b4b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/RelationMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/RelationMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/RelationTypeMapperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/RelationTypeMapperTest.cs index e17d6905ac..310b12c1cf 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/RelationTypeMapperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Mappers/RelationTypeMapperTest.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.Persistence.Mappers; using Umbraco.Tests.TestHelpers; @@ -30,7 +33,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_ChildObjectType_Property() { - // Act string column = new RelationTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("ChildObjectType"); @@ -41,7 +43,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers [Test] public void Can_Map_IsBidirectional_Property() { - // Act string column = new RelationTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("IsBidirectional"); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlExtensionsTests.cs index 9e9b148bb6..4ad1b89bf6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlExtensionsTests.cs @@ -1,9 +1,12 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using NPoco; using NUnit.Framework; -using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Persistence.Querying; using Umbraco.Tests.TestHelpers; using static Umbraco.Core.Persistence.SqlExtensionsStatics; @@ -15,7 +18,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void WhereTest() { - var sql = new Sql(SqlContext) + Sql sql = new Sql(SqlContext) .Select("*") .From() .Where(x => x.LanguageId == null); @@ -45,7 +48,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests // but the above comparison fails if @0 is null // what we want is something similar to: - sql = new Sql(SqlContext) .Select("*") .From() @@ -56,15 +58,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests // 'course it would be nicer if '==' could do it // see note in ExpressionVisitorBase for SqlNullableEquals - //sql = new Sql(SqlContext) + // sql = new Sql(SqlContext) // .Select("*") // .From() // .Where(x => x.LanguageId.SqlNullableEquals(nid)); - //Assert.AreEqual("SELECT *\nFROM [umbracoPropertyData]\nWHERE ((((@0 is null) AND ([umbracoPropertyData].[languageId] is null)) OR ((@0 is not null) AND ([umbracoPropertyData].[languageId] = @0))))", sql.SQL, sql.SQL); + // Assert.AreEqual("SELECT *\nFROM [umbracoPropertyData]\nWHERE ((((@0 is null) AND ([umbracoPropertyData].[languageId] is null)) OR ((@0 is not null) AND ([umbracoPropertyData].[languageId] = @0))))", sql.SQL, sql.SQL); // but, the expression above fails with SQL CE, 'specified argument for the function is not valid' in 'isnull' function // so... compare with fallback values - sql = new Sql(SqlContext) .Select("*") .From() @@ -89,7 +90,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void WhereInValueFieldTest() { - var sql = new Sql(SqlContext) + Sql sql = new Sql(SqlContext) .Select("*") .From() .WhereIn(x => x.NodeId, new[] { 1, 2, 3 }); @@ -101,8 +102,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests { // this test used to fail because x => x.Text was evaluated as a lambda // and returned "[umbracoNode].[text] = @0"... had to fix WhereIn. - - var sql = new Sql(SqlContext) + Sql sql = new Sql(SqlContext) .Select("*") .From() .WhereIn(x => x.Text, new[] { "a", "b", "c" }); @@ -113,7 +113,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests public void SelectTests() { // select the whole DTO - var sql = Sql() + Sql sql = Sql() .Select() .From(); Assert.AreEqual("SELECT [dto1].[id] AS [Id], [dto1].[name] AS [Name], [dto1].[value] AS [Value] FROM [dto1]", sql.SQL.NoCrLf()); @@ -135,7 +135,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests .Select(r => r.Select(x => x.Dto2)) .From() .InnerJoin().On(left => left.Id, right => right.Dto1Id); - Assert.AreEqual(@"SELECT [dto1].[id] AS [Id], [dto1].[name] AS [Name], [dto1].[value] AS [Value] + Assert.AreEqual( + @"SELECT [dto1].[id] AS [Id], [dto1].[name] AS [Name], [dto1].[value] AS [Value] , [dto2].[id] AS [Dto2__Id], [dto2].[dto1id] AS [Dto2__Dto1Id], [dto2].[name] AS [Dto2__Name] FROM [dto1] INNER JOIN [dto2] ON [dto1].[id] = [dto2].[dto1id]".NoCrLf(), sql.SQL.NoCrLf(), sql.SQL); @@ -146,7 +147,8 @@ INNER JOIN [dto2] ON [dto1].[id] = [dto2].[dto1id]".NoCrLf(), sql.SQL.NoCrLf(), .From() .InnerJoin().On(left => left.Id, right => right.Dto1Id) .InnerJoin().On(left => left.Id, right => right.Dto2Id); - Assert.AreEqual(@"SELECT [dto1].[id] AS [Id], [dto1].[name] AS [Name], [dto1].[value] AS [Value] + Assert.AreEqual( + @"SELECT [dto1].[id] AS [Id], [dto1].[name] AS [Name], [dto1].[value] AS [Value] , [dto2].[id] AS [Dto2__Id], [dto2].[dto1id] AS [Dto2__Dto1Id], [dto2].[name] AS [Dto2__Name] , [dto3].[id] AS [Dto2__Dto3__Id], [dto3].[dto2id] AS [Dto2__Dto3__Dto2Id], [dto3].[name] AS [Dto2__Dto3__Name] FROM [dto1] @@ -158,7 +160,8 @@ INNER JOIN [dto3] ON [dto2].[id] = [dto3].[dto2id]".NoCrLf(), sql.SQL.NoCrLf()); .Select(r => r.Select(x => x.Dto2s)) .From() .InnerJoin().On(left => left.Id, right => right.Dto1Id); - Assert.AreEqual(@"SELECT [dto1].[id] AS [Id], [dto1].[name] AS [Name], [dto1].[value] AS [Value] + Assert.AreEqual( + @"SELECT [dto1].[id] AS [Id], [dto1].[name] AS [Name], [dto1].[value] AS [Value] , [dto2].[id] AS [Dto2s__Id], [dto2].[dto1id] AS [Dto2s__Dto1Id], [dto2].[name] AS [Dto2s__Name] FROM [dto1] INNER JOIN [dto2] ON [dto1].[id] = [dto2].[dto1id]".NoCrLf(), sql.SQL.NoCrLf()); @@ -189,7 +192,7 @@ INNER JOIN [dto2] ON [dto1].[id] = [dto2].[dto1id]".NoCrLf(), sql.SQL.NoCrLf()); [Test] public void UpdateTests() { - var sql = Sql() + Sql sql = Sql() .Update(u => u.Set(x => x.EditorAlias, "Umbraco.ColorPicker")) .Where(x => x.EditorAlias == "Umbraco.ColorPickerAlias"); } @@ -201,12 +204,16 @@ INNER JOIN [dto2] ON [dto1].[id] = [dto2].[dto1id]".NoCrLf(), sql.SQL.NoCrLf()); { [Column("id")] public int Id { get; set; } + [Column("name")] public string Name { get; set; } + [Column("value")] public int Value { get; set; } + [Reference] public Dto2 Dto2 { get; set; } + [Reference] public List Dto2s { get; set; } } @@ -218,10 +225,13 @@ INNER JOIN [dto2] ON [dto1].[id] = [dto2].[dto1id]".NoCrLf(), sql.SQL.NoCrLf()); { [Column("id")] public int Id { get; set; } + [Column("dto1id")] public int Dto1Id { get; set; } + [Column("name")] public string Name { get; set; } + [Reference] public Dto3 Dto3 { get; set; } } @@ -233,8 +243,10 @@ INNER JOIN [dto2] ON [dto1].[id] = [dto2].[dto1id]".NoCrLf(), sql.SQL.NoCrLf()); { [Column("id")] public int Id { get; set; } + [Column("dto2id")] public int Dto2Id { get; set; } + [Column("name")] public string Name { get; set; } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlTemplateTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlTemplateTests.cs index 0367571d61..54c9814909 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlTemplateTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlTemplateTests.cs @@ -1,12 +1,14 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Moq; using NPoco; using NUnit.Framework; +using Umbraco.Core; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; -using Umbraco.Core; using Umbraco.Core.Persistence.SqlSyntax; -using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests { @@ -23,14 +25,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests // want to cache as a (static) template for ever, and ever - note // that using a MemoryCache would allow us to set a size limit, or // something equivalent, to reduce risk of memory explosion - var sql = sqlTemplates.Get("xxx", s => s + Sql sql = sqlTemplates.Get("xxx", s => s .SelectAll() .From("zbThing1") .Where("id=@id", new { id = SqlTemplate.Arg("id") })).Sql(new { id = 1 }); - var sql2 = sqlTemplates.Get("xxx", x => throw new InvalidOperationException("Should be cached.")).Sql(1); + Sql sql2 = sqlTemplates.Get("xxx", x => throw new InvalidOperationException("Should be cached.")).Sql(1); - var sql3 = sqlTemplates.Get("xxx", x => throw new InvalidOperationException("Should be cached.")).Sql(new { id = 1 }); + Sql sql3 = sqlTemplates.Get("xxx", x => throw new InvalidOperationException("Should be cached.")).Sql(new { id = 1 }); } [Test] @@ -44,10 +46,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests const string sqlBase = "SELECT [zbThing1].[id] AS [Id], [zbThing1].[name] AS [Name] FROM [zbThing1] WHERE "; - var template = sqlTemplates.Get("sql1", s => s.Select().From() + SqlTemplate template = sqlTemplates.Get("sql1", s => s.Select().From() .Where(x => x.Name == SqlTemplate.Arg("value"))); - var sql = template.Sql("foo"); + Sql sql = template.Sql("foo"); Assert.AreEqual(sqlBase + "(([zbThing1].[name] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual("foo", sql.Arguments[0]); @@ -90,7 +92,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests // but we cannot name them, because the arg name is the value of "i" // so we have to explicitely create the argument - template = sqlTemplates.Get("sql4", s => s.Select().From() .Where(x => x.Id == SqlTemplate.Arg("i"))); @@ -105,7 +106,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests Assert.AreEqual(123, sql.Arguments[0]); // and thanks to a patched visitor, this now works - sql = template.Sql(new { i = "foo" }); Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); @@ -120,7 +120,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests Assert.Throws(() => template.Sql(new { i = 123, j = 456 })); // now with more arguments - template = sqlTemplates.Get("sql4a", s => s.Select().From() .Where(x => x.Id == SqlTemplate.Arg("i") && x.Name == SqlTemplate.Arg("name"))); sql = template.Sql(0, 1); @@ -139,7 +138,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests Assert.AreEqual(1, sql.Arguments[1]); // works, magic - template = sqlTemplates.Get("sql5", s => s.Select().From() .WhereIn(x => x.Id, SqlTemplate.ArgIn("i"))); @@ -178,20 +176,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests // idea to just add the WhereIn to a templated, immutable SQL template // more fun... - template = sqlTemplates.Get("sql6", s => s.Select().From() + // do NOT do this, this is NOT a visited expression - //.Append(" AND whatever=@0", SqlTemplate.Arg("j")) + //// .Append(" AND whatever=@0", SqlTemplate.Arg("j")) // does not work anymore - due to proper TemplateArg //// instead, directly name the argument - //.Append("AND whatever=@0", "j") - //.Append("AND whatever=@0", "k") + ////.Append("AND whatever=@0", "j") + ////.Append("AND whatever=@0", "k") // instead, explicitely create the argument .Append("AND whatever=@0", SqlTemplate.Arg("j")) - .Append("AND whatever=@0", SqlTemplate.Arg("k")) - ); + .Append("AND whatever=@0", SqlTemplate.Arg("k"))); sql = template.Sql(new { j = new[] { 1, 2, 3 }, k = "oops" }); Assert.AreEqual(sqlBase.TrimEnd("WHERE ") + "AND whatever=@0,@1,@2 AND whatever=@3", sql.SQL.NoCrLf()); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlTests.cs index 80408bb211..a3fd28d952 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoSqlTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Diagnostics; using NPoco; using NUnit.Framework; @@ -7,7 +10,6 @@ using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Querying; using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.Testing; namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests { @@ -18,7 +20,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests public void Where_Clause_With_Starts_With_Additional_Parameters() { var content = new NodeDto() { NodeId = 123, Path = "-1,123" }; - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Path.SqlStartsWith(content.Path, TextColumnType.NVarchar)); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (upper([umbracoNode].[path]) LIKE upper(@0))", sql.SQL.Replace("\n", " ")); @@ -29,8 +31,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_With_Starts_With_By_Variable() { - var content = new NodeDto() {NodeId = 123, Path = "-1,123"}; - var sql = Sql().SelectAll().From() + var content = new NodeDto() { NodeId = 123, Path = "-1,123" }; + Sql sql = Sql().SelectAll().From() .Where(x => x.Path.StartsWith(content.Path) && x.NodeId != content.NodeId); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((upper([umbracoNode].[path]) LIKE upper(@0) AND ([umbracoNode].[id] <> @1)))", sql.SQL.Replace("\n", " ")); @@ -43,7 +45,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests public void Where_Clause_With_Not_Starts_With() { const int level = 1; - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Level == level && !x.Path.StartsWith("-20")); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[level] = @0) AND NOT (upper([umbracoNode].[path]) LIKE upper(@1))))", sql.SQL.Replace("\n", " ")); @@ -56,7 +58,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests public void Where_Clause_With_EqualsFalse_Starts_With() { const int level = 1; - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Level == level && x.Path.StartsWith("-20") == false); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[level] = @0) AND NOT (upper([umbracoNode].[path]) LIKE upper(@1))))", sql.SQL.Replace("\n", " ")); @@ -68,7 +70,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_With_Equals_Clause() { - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Text.Equals("Hello@world.com")); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (upper([umbracoNode].[text]) = upper(@0))", sql.SQL.Replace("\n", " ")); @@ -79,7 +81,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_With_False_Boolean() { - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Trashed == false); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (NOT ([umbracoNode].[trashed] = @0))", sql.SQL.Replace("\n", " ")); @@ -90,7 +92,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_With_EqualsFalse_Boolean() { - var sql = Sql().SelectAll().From().Where(x => x.Trashed == false); + Sql sql = Sql().SelectAll().From().Where(x => x.Trashed == false); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (NOT ([umbracoNode].[trashed] = @0))", sql.SQL.Replace("\n", " ")); Assert.AreEqual(1, sql.Arguments.Length); @@ -100,7 +102,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_With_Boolean() { - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Trashed); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ([umbracoNode].[trashed] = @0)", sql.SQL.Replace("\n", " ")); @@ -111,7 +113,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_With_ToUpper() { - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Text.ToUpper() == "hello".ToUpper()); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((upper([umbracoNode].[text]) = upper(@0)))", sql.SQL.Replace("\n", " ")); @@ -122,7 +124,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_With_ToString() { - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Text == 1.ToString()); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (([umbracoNode].[text] = @0))", sql.SQL.Replace("\n", " ")); @@ -133,7 +135,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_With_Wildcard() { - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Text.StartsWith("D")); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (upper([umbracoNode].[text]) LIKE upper(@0))", sql.SQL.Replace("\n", " ")); @@ -144,7 +146,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_Single_Constant() { - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.NodeId == 2); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (([umbracoNode].[id] = @0))", sql.SQL.Replace("\n", " ")); @@ -155,7 +157,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_And_Constant() { - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.NodeId != 2 && x.NodeId != 3); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[id] <> @0) AND ([umbracoNode].[id] <> @1)))", sql.SQL.Replace("\n", " ")); @@ -167,7 +169,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Clause_Or_Constant() { - var sql = Sql().SelectAll().From() + Sql sql = Sql().SelectAll().From() .Where(x => x.Text == "hello" || x.NodeId == 3); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[text] = @0) OR ([umbracoNode].[id] = @1)))", sql.SQL.Replace("\n", " ")); @@ -179,21 +181,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Where_Null() { - var sql = Sql().SelectAll().From().WhereNull(x => x.NodeId); + Sql sql = Sql().SelectAll().From().WhereNull(x => x.NodeId); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (([umbracoNode].[id] IS NULL))", sql.SQL.Replace("\n", " ")); } [Test] public void Where_Not_Null() { - var sql = Sql().SelectAll().From().WhereNotNull(x => x.NodeId); + Sql sql = Sql().SelectAll().From().WhereNotNull(x => x.NodeId); Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (([umbracoNode].[id] IS NOT NULL))", sql.SQL.Replace("\n", " ")); } [Test] public void Where_Any() { - var sql = Sql().SelectAll().From().WhereAny( + Sql sql = Sql().SelectAll().From().WhereAny( s => s.Where(x => x.NodeId == 1), s => s.Where(x => x.NodeId == 2)); @@ -203,10 +205,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Can_Select_From_With_Type() { - var expected = Sql(); + Sql expected = Sql(); expected.SelectAll().From($"[{Constants.DatabaseSchema.Tables.Content}]"); - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll().From(); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); @@ -217,13 +219,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Can_InnerJoin_With_Types() { - var expected = Sql(); + Sql expected = Sql(); expected.SelectAll() .From($"[{Constants.DatabaseSchema.Tables.DocumentVersion}]") .InnerJoin($"[{Constants.DatabaseSchema.Tables.ContentVersion}]") .On($"[{Constants.DatabaseSchema.Tables.DocumentVersion}].[id] = [{Constants.DatabaseSchema.Tables.ContentVersion}].[id]"); - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll().From() .InnerJoin() .On(left => left.Id, right => right.Id); @@ -236,10 +238,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Can_OrderBy_With_Type() { - var expected = Sql(); + Sql expected = Sql(); expected.SelectAll().From($"[{Constants.DatabaseSchema.Tables.Content}]").OrderBy($"([{Constants.DatabaseSchema.Tables.Content}].[contentTypeId])"); - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll().From().OrderBy(x => x.ContentTypeId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); @@ -250,10 +252,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Can_GroupBy_With_Type() { - var expected = Sql(); + Sql expected = Sql(); expected.SelectAll().From($"[{Constants.DatabaseSchema.Tables.Content}]").GroupBy($"[{Constants.DatabaseSchema.Tables.Content}].[contentTypeId]"); - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll().From().GroupBy(x => x.ContentTypeId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); @@ -264,10 +266,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Can_Use_Where_Predicate() { - var expected = Sql(); + Sql expected = Sql(); expected.SelectAll().From($"[{Constants.DatabaseSchema.Tables.Content}]").Where($"([{Constants.DatabaseSchema.Tables.Content}].[nodeId] = @0)", 1045); - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll().From().Where(x => x.NodeId == 1045); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); @@ -278,13 +280,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests [Test] public void Can_Use_Where_And_Predicate() { - var expected = Sql(); + Sql expected = Sql(); expected.SelectAll() .From($"[{Constants.DatabaseSchema.Tables.Content}]") .Where($"([{Constants.DatabaseSchema.Tables.Content}].[nodeId] = @0)", 1045) .Where($"([{Constants.DatabaseSchema.Tables.Content}].[contentTypeId] = @0)", 1050); - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll() .From() .Where(x => x.NodeId == 1045) @@ -300,7 +302,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests { var sessionId = Guid.NewGuid(); - var sql = Sql() + Sql sql = Sql() .SelectAll() .From() .Where(x => x.SessionId == sessionId); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/ContentTypeRepositorySqlClausesTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/ContentTypeRepositorySqlClausesTest.cs index 66253de575..dfd8e5ed12 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/ContentTypeRepositorySqlClausesTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/ContentTypeRepositorySqlClausesTest.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Diagnostics; using NUnit.Framework; using Umbraco.Core; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/DataTypeDefinitionRepositorySqlClausesTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/DataTypeDefinitionRepositorySqlClausesTest.cs index 708e7cac70..b6a389d83d 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/DataTypeDefinitionRepositorySqlClausesTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/DataTypeDefinitionRepositorySqlClausesTest.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Diagnostics; using NPoco; using NUnit.Framework; @@ -15,7 +18,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying [Test] public void Can_Verify_Base_Clause() { - var NodeObjectTypeId = Constants.ObjectTypes.DataType; + var nodeObjectTypeId = Constants.ObjectTypes.DataType; var expected = new Sql(); expected.Select("*") @@ -28,7 +31,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying .From() .InnerJoin() .On(left => left.NodeId, right => right.NodeId) - .Where(x => x.NodeObjectType == NodeObjectTypeId); + .Where(x => x.NodeObjectType == nodeObjectTypeId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/ExpressionTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/ExpressionTests.cs index 5d90d85f81..eed6fcdf59 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/ExpressionTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/ExpressionTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; @@ -25,8 +28,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying [Test] public void Equals_Claus_With_Two_Entity_Values() { - - var dataType = new DataType(new VoidEditor(NullLoggerFactory.Instance, Mock.Of(), Mock.Of(),Mock.Of(), Mock.Of(), new JsonNetSerializer()), new ConfigurationEditorJsonSerializer()) + var dataType = new DataType(new VoidEditor(NullLoggerFactory.Instance, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()), new ConfigurationEditorJsonSerializer()) { Id = 12345 }; @@ -43,7 +45,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying [Test] public void Can_Query_With_Content_Type_Alias() { - //Arrange + // Arrange Expression> predicate = content => content.ContentType.Alias == "Test"; var modelToSqlExpressionHelper = new ModelToSqlExpressionVisitor(SqlContext.SqlSyntax, Mappers); var result = modelToSqlExpressionHelper.Visit(predicate); @@ -57,7 +59,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying [Test] public void Can_Query_With_Content_Type_Aliases_IEnumerable() { - //Arrange - Contains is IEnumerable.Contains extension method + // Arrange - Contains is IEnumerable.Contains extension method var aliases = new[] { "Test1", "Test2" }; Expression> predicate = content => aliases.Contains(content.ContentType.Alias); var modelToSqlExpressionHelper = new ModelToSqlExpressionVisitor(SqlContext.SqlSyntax, Mappers); @@ -73,7 +75,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying [Test] public void Can_Query_With_Content_Type_Aliases_List() { - //Arrange - Contains is List.Contains instance method + // Arrange - Contains is List.Contains instance method var aliases = new System.Collections.Generic.List { "Test1", "Test2" }; Expression> predicate = content => aliases.Contains(content.ContentType.Alias); var modelToSqlExpressionHelper = new ModelToSqlExpressionVisitor(SqlContext.SqlSyntax, Mappers); @@ -89,9 +91,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying [Test] public void CachedExpression_Can_Verify_Path_StartsWith_Predicate_In_Same_Result() { - //Arrange + // Arrange - //use a single cached expression for multiple expressions and ensure the correct output + // use a single cached expression for multiple expressions and ensure the correct output // is done for both of them. var cachedExpression = new CachedExpression(); @@ -108,13 +110,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying var result2 = modelToSqlExpressionHelper2.Visit(cachedExpression); Assert.AreEqual("upper([umbracoNode].[path]) LIKE upper(@0)", result2); Assert.AreEqual("-1,123,97%", modelToSqlExpressionHelper2.GetSqlParameters()[0]); - } [Test] public void Can_Verify_Path_StartsWith_Predicate_In_Same_Result() { - //Arrange + // Arrange Expression> predicate = content => content.Path.StartsWith("-1"); var modelToSqlExpressionHelper = new ModelToSqlExpressionVisitor(SqlContext.SqlSyntax, Mappers); var result = modelToSqlExpressionHelper.Visit(predicate); @@ -126,7 +127,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying [Test] public void Can_Verify_ParentId_StartsWith_Predicate_In_Same_Result() { - //Arrange + // Arrange Expression> predicate = content => content.ParentId == -1; var modelToSqlExpressionHelper = new ModelToSqlExpressionVisitor(SqlContext.SqlSyntax, Mappers); var result = modelToSqlExpressionHelper.Visit(predicate); @@ -195,10 +196,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying Assert.AreEqual("blah@blah.com", modelToSqlExpressionHelper.GetSqlParameters()[2]); } - private string GetSomeValue(string s) - { - return "xx" + s + "xx"; - } + private string GetSomeValue(string s) => "xx" + s + "xx"; private class Foo { @@ -242,12 +240,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying // and how would we get the comma there? we'd have to parse .StartsWith(group.Name + ',') // which is going to be quite complicated => no - //// how can we do user.Login.StartsWith(other.Value) ?? to use in WHERE or JOIN.ON clauses ?? - //Expression> predicate2 = (user, group) => user.Login.StartsWith(group.Name); - //var modelToSqlExpressionHelper2 = new PocoToSqlExpressionVisitor(SqlContext, null, null); - //var result2 = modelToSqlExpressionHelper2.Visit(predicate2); // fails, for now + // how can we do user.Login.StartsWith(other.Value) ?? to use in WHERE or JOIN.ON clauses ?? + //// Expression> predicate2 = (user, group) => user.Login.StartsWith(group.Name); + //// var modelToSqlExpressionHelper2 = new PocoToSqlExpressionVisitor(SqlContext, null, null); + //// var result2 = modelToSqlExpressionHelper2.Visit(predicate2); // fails, for now - //Console.WriteLine(result2); + //// Console.WriteLine(result2); Expression> predicate3 = (user, group) => SqlExtensionsStatics.SqlText(user.Login, group.Name, (n1, n2) => $"({n1} LIKE concat({n2}, ',%'))"); var modelToSqlExpressionHelper3 = new PocoToSqlExpressionVisitor(SqlContext, null, null); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/MediaRepositorySqlClausesTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/MediaRepositorySqlClausesTest.cs index 8c26f6a06b..09958a73b0 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/MediaRepositorySqlClausesTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/MediaRepositorySqlClausesTest.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Diagnostics; using NPoco; using NUnit.Framework; @@ -15,7 +18,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying [Test] public void Can_Verify_Base_Clause() { - var nodeObjectTypeId = Constants.ObjectTypes.Media; + Guid nodeObjectTypeId = Constants.ObjectTypes.Media; var expected = new Sql(); expected.Select("*") @@ -24,7 +27,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying .InnerJoin("[umbracoNode]").On($"[{Constants.DatabaseSchema.Tables.Content}].[nodeId] = [umbracoNode].[id]") .Where("([umbracoNode].[nodeObjectType] = @0)", new Guid("b796f64c-1f99-4ffb-b886-4bf4bc011a9c")); - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll() .From() .InnerJoin() diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/MediaTypeRepositorySqlClausesTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/MediaTypeRepositorySqlClausesTest.cs index f28540454d..4187ecf1df 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/MediaTypeRepositorySqlClausesTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/MediaTypeRepositorySqlClausesTest.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Diagnostics; using NPoco; using NUnit.Framework; @@ -15,7 +18,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying [Test] public void Can_Verify_Base_Clause() { - var NodeObjectTypeId = Constants.ObjectTypes.MediaType; + Guid nodeObjectTypeId = Constants.ObjectTypes.MediaType; var expected = new Sql(); expected.Select("*") @@ -23,12 +26,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying .InnerJoin("[umbracoNode]").On("[cmsContentType].[nodeId] = [umbracoNode].[id]") .Where("([umbracoNode].[nodeObjectType] = @0)", new Guid("4ea4382b-2f5a-4c2b-9587-ae9b3cf3602e")); - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll() .From() .InnerJoin() .On(left => left.NodeId, right => right.NodeId) - .Where(x => x.NodeObjectType == NodeObjectTypeId); + .Where(x => x.NodeObjectType == nodeObjectTypeId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/QueryBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/QueryBuilderTests.cs index f4b8c2b250..00500c9094 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/QueryBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Persistence/Querying/QueryBuilderTests.cs @@ -1,6 +1,9 @@ -using System.Diagnostics; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Diagnostics; +using NPoco; using NUnit.Framework; -using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; @@ -16,16 +19,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying public void Can_Build_StartsWith_Query_For_IContent() { // Arrange - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll(); sql.From("umbracoNode"); - var query = new Query(SqlContext).Where(x => x.Path.StartsWith("-1")); + IQuery query = new Query(SqlContext).Where(x => x.Path.StartsWith("-1")); // Act var translator = new SqlTranslator(sql, query); - var result = translator.Translate(); - var strResult = result.SQL; + Sql result = translator.Translate(); + string strResult = result.SQL; string expectedResult = "SELECT *\nFROM umbracoNode\nWHERE (upper([umbracoNode].[path]) LIKE upper(@0))"; @@ -43,16 +46,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying public void Can_Build_ParentId_Query_For_IContent() { // Arrange - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll(); sql.From("umbracoNode"); - var query = new Query(SqlContext).Where(x => x.ParentId == -1); + IQuery query = new Query(SqlContext).Where(x => x.ParentId == -1); // Act var translator = new SqlTranslator(sql, query); - var result = translator.Translate(); - var strResult = result.SQL; + Sql result = translator.Translate(); + string strResult = result.SQL; string expectedResult = "SELECT *\nFROM umbracoNode\nWHERE (([umbracoNode].[parentId] = @0))"; @@ -70,16 +73,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying public void Can_Build_ContentTypeAlias_Query_For_IContentType() { // Arrange - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll(); sql.From("umbracoNode"); - var query = new Query(SqlContext).Where(x => x.Alias == "umbTextpage"); + IQuery query = new Query(SqlContext).Where(x => x.Alias == "umbTextpage"); // Act var translator = new SqlTranslator(sql, query); - var result = translator.Translate(); - var strResult = result.SQL; + Sql result = translator.Translate(); + string strResult = result.SQL; string expectedResult = "SELECT *\nFROM umbracoNode\nWHERE (([cmsContentType].[alias] = @0))"; @@ -98,14 +101,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Querying const string path = "-1,1046,1076,1089"; const int id = 1046; - var sql = Sql(); + Sql sql = Sql(); sql.SelectAll() .From(); // the actual SELECT really does not matter - var query = SqlContext.Query().Where(x => x.Path.StartsWith(path) && x.Id != id && x.Published && x.Trashed == false); + IQuery query = SqlContext.Query().Where(x => x.Path.StartsWith(path) && x.Id != id && x.Published && x.Trashed == false); var translator = new SqlTranslator(sql, query); - var result = translator.Translate(); + Sql result = translator.Translate(); Assert.AreEqual("-1,1046,1076,1089%", result.Arguments[0]); Assert.AreEqual(1046, result.Arguments[1]); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Serialization/JsonNetSerializerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Serialization/JsonNetSerializerTests.cs index 40a932181c..cbf3e7daaa 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Serialization/JsonNetSerializerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Serialization/JsonNetSerializerTests.cs @@ -1,4 +1,7 @@ -using Newtonsoft.Json; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Newtonsoft.Json; using NUnit.Framework; using Umbraco.Core.Serialization; @@ -49,7 +52,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Serialization [Test] public void DeserializeSubset__Subset_value_as_object() { - var expected = new MyStruct() { Key = "Test" @@ -65,7 +67,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Serialization [Test] public void DeserializeSubset__Subset_value_as_array() { - var expected = new []{"test"}; + var expected = new[] { "test" }; var key = "text"; var full = $"{{\"{key}\": {JsonConvert.SerializeObject(expected)}"; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/AmbiguousEventTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/AmbiguousEventTests.cs index 6eebf5d237..63331762b6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/AmbiguousEventTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/AmbiguousEventTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Reflection; using System.Text; using NUnit.Framework; @@ -23,7 +26,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services string TypeName(Type type) { if (!type.IsGenericType) + { return type.Name; + } + var sb = new StringBuilder(); TypeNameSb(type, sb); return sb.ToString(); @@ -36,24 +42,42 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services name = pos > 0 ? name.Substring(0, pos) : name; sb.Append(name); if (!type.IsGenericType) + { return; + } + sb.Append("<"); var first = true; foreach (var arg in type.GetGenericArguments()) { - if (first) first = false; - else sb.Append(", "); + if (first) + { + first = false; + } + else + { + sb.Append(", "); + } + TypeNameSb(arg, sb); } + sb.Append(">"); } foreach (var e in events) { // only continue if this is a TypedEventHandler - if (!e.EventHandlerType.IsGenericType) continue; + if (!e.EventHandlerType.IsGenericType) + { + continue; + } + var typeDef = e.EventHandlerType.GetGenericTypeDefinition(); - if (typedEventHandler != typeDef) continue; + if (typedEventHandler != typeDef) + { + continue; + } // get the event args type var eventArgsType = e.EventHandlerType.GenericTypeArguments[1]; @@ -62,7 +86,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services // exclude -ing (eg Saving) events, we don't deal with them in EventDefinitionBase (they always trigger) var found = EventNameExtractor.FindEvents(serviceType, eventArgsType, EventNameExtractor.MatchIngNames); - if (found.Length == 1) continue; + if (found.Length == 1) + { + continue; + } if (found.Length == 0) { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/LocalizedTextServiceTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/LocalizedTextServiceTests.cs index dc857d2d5d..6bfc252574 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/LocalizedTextServiceTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/LocalizedTextServiceTests.cs @@ -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; @@ -13,7 +16,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services [TestFixture] public class LocalizedTextServiceTests { - private static ILoggerFactory _loggerFactory = NullLoggerFactory.Instance; + private static readonly ILoggerFactory s_loggerFactory = NullLoggerFactory.Instance; + [Test] public void Using_Dictionary_Gets_All_Stored_Values() { @@ -27,22 +31,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services { "testArea1", new Dictionary { - {"testKey1", "testValue1"}, - {"testKey2", "testValue2"} + { "testKey1", "testValue1" }, + { "testKey2", "testValue2" } } }, { "testArea2", new Dictionary { - {"blah1", "blahValue1"}, - {"blah2", "blahValue2"} + { "blah1", "blahValue1" }, + { "blah2", "blahValue2" } } }, } } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.GetAllStoredValues(culture); + IDictionary result = txtService.GetAllStoredValues(culture); Assert.AreEqual(4, result.Count); Assert.AreEqual("testArea1/testKey1", result.ElementAt(0).Key); @@ -53,18 +57,19 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services Assert.AreEqual("testValue2", result["testArea1/testKey2"]); Assert.AreEqual("blahValue1", result["testArea2/blah1"]); Assert.AreEqual("blahValue2", result["testArea2/blah2"]); - } [Test] public void Using_XDocument_Gets_All_Stored_Values() { var culture = CultureInfo.GetCultureInfo("en-US"); - var txtService = new LocalizedTextService(new Dictionary> + var txtService = new LocalizedTextService( + new Dictionary> { { culture, new Lazy(() => new XDocument( - new XElement("language", + new XElement( + "language", new XElement("area", new XAttribute("alias", "testArea1"), new XElement("key", new XAttribute("alias", "testKey1"), "testValue1"), new XElement("key", new XAttribute("alias", "testKey2"), "testValue2")), @@ -72,9 +77,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services new XElement("key", new XAttribute("alias", "blah1"), "blahValue1"), new XElement("key", new XAttribute("alias", "blah2"), "blahValue2"))))) } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.GetAllStoredValues(culture); + IDictionary result = txtService.GetAllStoredValues(culture); Assert.AreEqual(4, result.Count()); Assert.AreEqual("testArea1/testKey1", result.ElementAt(0).Key); @@ -85,10 +90,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services Assert.AreEqual("testValue2", result["testArea1/testKey2"]); Assert.AreEqual("blahValue1", result["testArea2/blah1"]); Assert.AreEqual("blahValue2", result["testArea2/blah2"]); - } - [Test] public void Using_XDocument_Gets_All_Stored_Values_With_Duplicates() { @@ -98,17 +101,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services { { culture, new Lazy(() => new XDocument( - new XElement("language", + new XElement( + "language", new XElement("area", new XAttribute("alias", "testArea1"), new XElement("key", new XAttribute("alias", "testKey1"), "testValue1"), new XElement("key", new XAttribute("alias", "testKey1"), "testValue1"))))) } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.GetAllStoredValues(culture); + IDictionary result = txtService.GetAllStoredValues(culture); Assert.AreEqual(1, result.Count()); - } [Test] @@ -124,14 +127,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services { "testArea", new Dictionary { - {"testKey", "testValue"} + { "testKey", "testValue" } } } } } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("testArea/testKey", culture); + string result = txtService.Localize("testArea/testKey", culture); Assert.AreEqual("testValue", result); } @@ -149,14 +152,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services { "testArea", new Dictionary { - {"testKey", "testValue"} + { "testKey", "testValue" } } } } } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("testKey", culture); + string result = txtService.Localize("testKey", culture); Assert.AreEqual("testValue", result); } @@ -174,16 +177,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services { "testArea", new Dictionary { - {"testKey", "testValue"} + { "testKey", "testValue" } } } } } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("testArea/doNotFind", culture); + string result = txtService.Localize("testArea/doNotFind", culture); - //NOTE: Based on how legacy works, the default text does not contain the area, just the key + // NOTE: Based on how legacy works, the default text does not contain the area, just the key Assert.AreEqual("[doNotFind]", result); } @@ -200,14 +203,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services { "testArea", new Dictionary { - {"testKey", "testValue"} + { "testKey", "testValue" } } } } } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("doNotFind", culture); + string result = txtService.Localize("doNotFind", culture); Assert.AreEqual("[doNotFind]", result); } @@ -225,14 +228,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services { "testArea", new Dictionary { - {"testKey", "Hello %0%, you are such a %1% %2%"} + { "testKey", "Hello %0%, you are such a %1% %2%" } } } } } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("testKey", culture, + string result = txtService.Localize( + "testKey", + culture, new Dictionary { { "0", "world" }, { "1", "great" }, { "2", "planet" } }); Assert.AreEqual("Hello world, you are such a great planet", result); @@ -251,9 +256,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services new XElement("key", new XAttribute("alias", "testKey"), "testValue")))) } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("testArea/testKey", culture); + string result = txtService.Localize("testArea/testKey", culture); Assert.AreEqual("testValue", result); } @@ -271,9 +276,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services new XElement("key", new XAttribute("alias", "testKey"), "testValue")))) } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("testKey", culture); + string result = txtService.Localize("testKey", culture); Assert.AreEqual("testValue", result); } @@ -291,11 +296,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services new XElement("key", new XAttribute("alias", "testKey"), "testValue")))) } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("testArea/doNotFind", culture); + string result = txtService.Localize("testArea/doNotFind", culture); - //NOTE: Based on how legacy works, the default text does not contain the area, just the key + // NOTE: Based on how legacy works, the default text does not contain the area, just the key Assert.AreEqual("[doNotFind]", result); } @@ -312,9 +317,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services new XElement("key", new XAttribute("alias", "testKey"), "testValue")))) } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("doNotFind", culture); + string result = txtService.Localize("doNotFind", culture); Assert.AreEqual("[doNotFind]", result); } @@ -332,9 +337,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services new XElement("key", new XAttribute("alias", "testKey"), "Hello %0%, you are such a %1% %2%")))) } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); - var result = txtService.Localize("testKey", culture, + string result = txtService.Localize("testKey", culture, new Dictionary { { "0", "world" }, { "1", "great" }, { "2", "planet" } }); Assert.AreEqual("Hello world, you are such a great planet", result); @@ -353,12 +358,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services { "testArea", new Dictionary { - {"testKey", "testValue"} + { "testKey", "testValue" } } } } } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); Assert.AreEqual("[testKey]", txtService.Localize("testArea/testKey", CultureInfo.GetCultureInfo("en-AU"))); } @@ -373,10 +378,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services { culture, new Lazy(() => new XDocument( new XElement("area", new XAttribute("alias", "testArea"), - new XElement("key", new XAttribute("alias", "testKey"), - "testValue")))) + new XElement("key", new XAttribute("alias", "testKey"), "testValue")))) } - }, _loggerFactory.CreateLogger()); + }, s_loggerFactory.CreateLogger()); Assert.AreEqual("[testKey]", txtService.Localize("testArea/testKey", CultureInfo.GetCultureInfo("en-AU"))); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/PropertyValidationServiceTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/PropertyValidationServiceTests.cs index abc1bb0c9d..2f26b041c6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/PropertyValidationServiceTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Services/PropertyValidationServiceTests.cs @@ -1,4 +1,7 @@ -using System.Threading; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Threading; using Moq; using NUnit.Framework; using Umbraco.Core; @@ -23,15 +26,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services textService.Setup(x => x.Localize(It.IsAny(), Thread.CurrentThread.CurrentCulture, null)).Returns("Localized text"); var dataTypeService = new Mock(); - var dataType = Mock.Of( - x => x.Configuration == (object)string.Empty //irrelevant but needs a value + IDataType dataType = Mock.Of( + x => x.Configuration == (object)string.Empty // irrelevant but needs a value && x.DatabaseType == ValueStorageType.Nvarchar && x.EditorAlias == Constants.PropertyEditors.Aliases.TextBox); dataTypeService.Setup(x => x.GetDataType(It.IsAny())).Returns(() => dataType); dt = dataType; - //new data editor that returns a TextOnlyValueEditor which will do the validation for the properties - var dataEditor = Mock.Of( + // new data editor that returns a TextOnlyValueEditor which will do the validation for the properties + IDataEditor dataEditor = Mock.Of( x => x.Type == EditorType.PropertyValue && x.Alias == Constants.PropertyEditors.Aliases.TextBox); Mock.Get(dataEditor).Setup(x => x.GetValueEditor(It.IsAny())) @@ -45,22 +48,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services [Test] public void Validate_Invariant_Properties_On_Variant_Default_Culture() { - MockObjects(out var validationService, out var dataType); + MockObjects(out PropertyValidationService validationService, out IDataType dataType); - var p1 = new Property(new PropertyType(ShortStringHelper, dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture}); + var p1 = new Property(new PropertyType(ShortStringHelper, dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture }); p1.SetValue("Hello", "en-US"); var p2 = new Property(new PropertyType(ShortStringHelper, dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing }); p2.SetValue("Hello", null); var p3 = new Property(new PropertyType(ShortStringHelper, dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture }); - p3.SetValue(null, "en-US"); //invalid + p3.SetValue(null, "en-US"); // invalid var p4 = new Property(new PropertyType(ShortStringHelper, dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing }); - p4.SetValue(null, null); //invalid + p4.SetValue(null, null); // invalid - var content = Mock.Of( - x => x.Published == true //set to published, the default culture will validate invariant anyways + IContent content = Mock.Of( + x => x.Published == true // set to published, the default culture will validate invariant anyways && x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 })); - var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.Explicit("en-US", true)); + bool result = validationService.IsPropertyDataValid(content, out IProperty[] invalid, CultureImpact.Explicit("en-US", true)); Assert.IsFalse(result); Assert.AreEqual(2, invalid.Length); @@ -69,22 +72,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services [Test] public void Validate_Invariant_Properties_On_Variant_Non_Default_Culture() { - MockObjects(out var validationService, out var dataType); + MockObjects(out PropertyValidationService validationService, out IDataType dataType); var p1 = new Property(new PropertyType(ShortStringHelper, dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture }); p1.SetValue("Hello", "en-US"); var p2 = new Property(new PropertyType(ShortStringHelper, dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing }); p2.SetValue("Hello", null); var p3 = new Property(new PropertyType(ShortStringHelper, dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture }); - p3.SetValue(null, "en-US"); //invalid + p3.SetValue(null, "en-US"); // invalid var p4 = new Property(new PropertyType(ShortStringHelper, dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing }); - p4.SetValue(null, null); //invalid + p4.SetValue(null, null); // invalid - var content = Mock.Of( - x => x.Published == false //set to not published, the non default culture will need to validate invariant too + IContent content = Mock.Of( + x => x.Published == false // set to not published, the non default culture will need to validate invariant too && x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 })); - var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.Explicit("en-US", false)); + bool result = validationService.IsPropertyDataValid(content, out IProperty[] invalid, CultureImpact.Explicit("en-US", false)); Assert.IsFalse(result); Assert.AreEqual(2, invalid.Length); @@ -93,22 +96,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services [Test] public void Validate_Variant_Properties_On_Variant() { - MockObjects(out var validationService, out var dataType); + MockObjects(out PropertyValidationService validationService, out IDataType dataType); var p1 = new Property(new PropertyType(ShortStringHelper, dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture }); - p1.SetValue(null, "en-US"); //invalid + p1.SetValue(null, "en-US"); // invalid var p2 = new Property(new PropertyType(ShortStringHelper, dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing }); - p2.SetValue(null, null); //invalid + p2.SetValue(null, null); // invalid var p3 = new Property(new PropertyType(ShortStringHelper, dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture }); - p3.SetValue(null, "en-US"); //ignored because the impact isn't the default lang + the content is published + p3.SetValue(null, "en-US"); // ignored because the impact isn't the default lang + the content is published var p4 = new Property(new PropertyType(ShortStringHelper, dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing }); - p4.SetValue(null, null); //ignored because the impact isn't the default lang + the content is published + p4.SetValue(null, null); // ignored because the impact isn't the default lang + the content is published - var content = Mock.Of( - x => x.Published == true //set to published + IContent content = Mock.Of( + x => x.Published == true // set to published && x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 })); - var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.Explicit("en-US", false)); + bool result = validationService.IsPropertyDataValid(content, out IProperty[] invalid, CultureImpact.Explicit("en-US", false)); Assert.IsFalse(result); Assert.AreEqual(2, invalid.Length); @@ -117,21 +120,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services [Test] public void Validate_Invariant_Properties_On_Invariant() { - MockObjects(out var validationService, out var dataType); + MockObjects(out PropertyValidationService validationService, out IDataType dataType); var p1 = new Property(new PropertyType(ShortStringHelper, dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture }); - p1.SetValue(null, "en-US"); //ignored since this is variant + p1.SetValue(null, "en-US"); // ignored since this is variant var p2 = new Property(new PropertyType(ShortStringHelper, dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing }); - p2.SetValue(null, null); //invalid + p2.SetValue(null, null); // invalid var p3 = new Property(new PropertyType(ShortStringHelper, dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture }); - p3.SetValue("Hello", "en-US"); //ignored since this is variant + p3.SetValue("Hello", "en-US"); // ignored since this is variant var p4 = new Property(new PropertyType(ShortStringHelper, dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing }); - p4.SetValue(null, null); //invalid + p4.SetValue(null, null); // invalid - var content = Mock.Of( + IContent content = Mock.Of( x => x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 })); - var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.Invariant); + bool result = validationService.IsPropertyDataValid(content, out IProperty[] invalid, CultureImpact.Invariant); Assert.IsFalse(result); Assert.AreEqual(2, invalid.Length); @@ -140,28 +143,27 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services [Test] public void Validate_Properties_On_All() { - MockObjects(out var validationService, out var dataType); + MockObjects(out PropertyValidationService validationService, out IDataType dataType); var p1 = new Property(new PropertyType(ShortStringHelper, dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture }); - p1.SetValue(null, "en-US"); //invalid + p1.SetValue(null, "en-US"); // invalid var p2 = new Property(new PropertyType(ShortStringHelper, dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing }); - p2.SetValue(null, null); //invalid + p2.SetValue(null, null); // invalid var p3 = new Property(new PropertyType(ShortStringHelper, dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture }); - p3.SetValue(null, "en-US"); //invalid + p3.SetValue(null, "en-US"); // invalid var p4 = new Property(new PropertyType(ShortStringHelper, dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing }); - p4.SetValue(null, null); //invalid + p4.SetValue(null, null); // invalid - var content = Mock.Of( + IContent content = Mock.Of( x => x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 })); - var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.All); + bool result = validationService.IsPropertyDataValid(content, out IProperty[] invalid, CultureImpact.All); Assert.IsFalse(result); Assert.AreEqual(4, invalid.Length); } - - //used so we can inject a mock - we should fix the base class DataValueEditor to be able to have the ILocalizedTextField passed + // used so we can inject a mock - we should fix the base class DataValueEditor to be able to have the ILocalizedTextField passed // in to create the Requried and Regex validators so we aren't using singletons private class CustomTextOnlyValueEditor : TextOnlyValueEditor { @@ -174,10 +176,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Services ILocalizedTextService textService, IShortStringHelper shortStringHelper, IJsonSerializer jsonSerializer) - : base(dataTypeService, localizationService, attribute, textService, shortStringHelper, jsonSerializer) - { - _textService = textService; - } + : base(dataTypeService, localizationService, attribute, textService, shortStringHelper, jsonSerializer) => _textService = textService; public override IValueRequiredValidator RequiredValidator => new RequiredValidator(_textService); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/BuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/BuilderTests.cs index 80c8b057ab..af77d0e570 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/BuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/BuilderTests.cs @@ -1,8 +1,12 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; +using Semver; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.ModelsBuilder.Embedded; @@ -13,12 +17,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded [TestFixture] public class BuilderTests { - [Test] public void GenerateSimpleType() { - // Umbraco returns nice, pascal-cased names - + // Umbraco returns nice, pascal-cased names. var type1 = new TypeModel { Id = 1, @@ -35,21 +37,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded ModelClrType = typeof(string), }); - var types = new[] { type1 }; - - var code = new Dictionary - { - }; + TypeModel[] types = new[] { type1 }; var modelsBuilderConfig = new ModelsBuilderSettings(); var builder = new TextBuilder(modelsBuilderConfig, types); - var btypes = builder.TypeModels; var sb = new StringBuilder(); builder.Generate(sb, builder.GetModelsToGenerate().First()); var gen = sb.ToString(); - var version = ApiVersion.Current.Version; + SemVersion version = ApiVersion.Current.Version; var expected = @"//------------------------------------------------------------------------------ // // This code was generated by a tool. @@ -110,8 +107,7 @@ namespace Umbraco.Web.PublishedModels [Test] public void GenerateSimpleType_Ambiguous_Issue() { - // Umbraco returns nice, pascal-cased names - + // Umbraco returns nice, pascal-cased names. var type1 = new TypeModel { Id = 1, @@ -138,25 +134,13 @@ namespace Umbraco.Web.PublishedModels ItemType = TypeModel.ItemTypes.Element, }; - var types = new[] { type1, type2 }; - - var code = new Dictionary - { - { "code", @" -namespace Umbraco.Web.PublishedModels -{ - public partial class Foo - { - } -} -" } - }; + TypeModel[] types = new[] { type1, type2 }; var modelsBuilderConfig = new ModelsBuilderSettings(); - var builder = new TextBuilder(modelsBuilderConfig, types); - var btypes = builder.TypeModels; - - builder.ModelsNamespace = "Umbraco.Web.PublishedModels"; + var builder = new TextBuilder(modelsBuilderConfig, types) + { + ModelsNamespace = "Umbraco.Web.PublishedModels" + }; var sb1 = new StringBuilder(); builder.Generate(sb1, builder.GetModelsToGenerate().Skip(1).First()); @@ -167,7 +151,7 @@ namespace Umbraco.Web.PublishedModels builder.Generate(sb, builder.GetModelsToGenerate().First()); var gen = sb.ToString(); - var version = ApiVersion.Current.Version; + SemVersion version = ApiVersion.Current.Version; var expected = @"//------------------------------------------------------------------------------ // // This code was generated by a tool. @@ -228,8 +212,6 @@ namespace Umbraco.Web.PublishedModels [Test] public void GenerateAmbiguous() { - // NOTE: since - var type1 = new TypeModel { Id = 1, @@ -258,20 +240,20 @@ namespace Umbraco.Web.PublishedModels ClrName = "Prop3", ModelClrType = typeof(global::Umbraco.Core.Exceptions.BootFailedException), }); - var types = new[] { type1 }; - - var code = new Dictionary - { - }; + TypeModel[] types = new[] { type1 }; var modelsBuilderConfig = new ModelsBuilderSettings(); - var builder = new TextBuilder(modelsBuilderConfig, types); - builder.ModelsNamespace = "Umbraco.ModelsBuilder.Models"; // forces conflict with Umbraco.ModelsBuilder.Umbraco - var btypes = builder.TypeModels; + var builder = new TextBuilder(modelsBuilderConfig, types) + { + ModelsNamespace = "Umbraco.ModelsBuilder.Models" // forces conflict with Umbraco.ModelsBuilder.Umbraco + }; var sb = new StringBuilder(); - foreach (var model in builder.GetModelsToGenerate()) + foreach (TypeModel model in builder.GetModelsToGenerate()) + { builder.Generate(sb, model); + } + var gen = sb.ToString(); Console.WriteLine(gen); @@ -289,9 +271,10 @@ namespace Umbraco.Web.PublishedModels { // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things - - var builder = new TextBuilder(); - builder.ModelsNamespaceForTests = "ModelsNamespace"; + var builder = new TextBuilder + { + ModelsNamespaceForTests = "ModelsNamespace" + }; var sb = new StringBuilder(); builder.WriteClrType(sb, input); Assert.AreEqual(expected, sb.ToString()); @@ -305,7 +288,6 @@ namespace Umbraco.Web.PublishedModels { // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things - var builder = new TextBuilder(); builder.Using.Add("Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder"); builder.ModelsNamespaceForTests = "ModelsNamespace"; @@ -325,15 +307,16 @@ namespace Umbraco.Web.PublishedModels // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things - Assert.AreEqual("global::System.Text.StringBuilder", sb.ToString()); } [Test] public void WriteClrTypeAnother_WithoutUsing() { - var builder = new TextBuilder(); - builder.ModelsNamespaceForTests = "Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Models"; + var builder = new TextBuilder + { + ModelsNamespaceForTests = "Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Models" + }; var sb = new StringBuilder(); builder.WriteClrType(sb, typeof(StringBuilder)); Assert.AreEqual("global::System.Text.StringBuilder", sb.ToString()); @@ -351,7 +334,6 @@ namespace Umbraco.Web.PublishedModels // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things - Assert.AreEqual("global::System.Text.ASCIIEncoding", sb.ToString()); } @@ -367,7 +349,6 @@ namespace Umbraco.Web.PublishedModels // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things - Assert.AreEqual("global::System.Text.ASCIIEncoding", sb.ToString()); } @@ -383,7 +364,6 @@ namespace Umbraco.Web.PublishedModels // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things - Assert.AreEqual("global::Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.ASCIIEncoding", sb.ToString()); } @@ -399,7 +379,6 @@ namespace Umbraco.Web.PublishedModels // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things - Assert.AreEqual("global::Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.ASCIIEncoding", sb.ToString()); } @@ -415,21 +394,28 @@ namespace Umbraco.Web.PublishedModels // note - these assertions differ from the original tests in MB because in the embedded version, the result of Builder.IsAmbiguousSymbol is always true // which means global:: syntax will be applied to most things - Assert.AreEqual("global::Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded.ASCIIEncoding.Nested", sb.ToString()); } - public class Class1 { } + public class Class1 + { + } } // make it public to be ambiguous (see above) public class ASCIIEncoding { // can we handle nested types? - public class Nested { } + public class Nested + { + } } - class BuilderTestsClass1 { } + public class BuilderTestsClass1 + { + } - public class System { } + public class System + { + } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/StringExtensions.cs b/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/StringExtensions.cs index 2afcd4f471..45065bbd53 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/StringExtensions.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/StringExtensions.cs @@ -1,10 +1,10 @@ -namespace Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded +// Copyright (c) Umbraco. +// See LICENSE for more details. + +namespace Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded { public static class StringExtensions { - public static string ClearLf(this string s) - { - return s.Replace("\r", ""); - } + public static string ClearLf(this string s) => s.Replace("\r", string.Empty); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/UmbracoApplicationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/UmbracoApplicationTests.cs index 25d1d9f1f9..0c75318c87 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/UmbracoApplicationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.ModelsBuilder.Embedded/UmbracoApplicationTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using NUnit.Framework; using Umbraco.ModelsBuilder.Embedded; @@ -9,23 +12,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.ModelsBuilder.Embedded [TestFixture] public class UmbracoApplicationTests { - //[Test] - //public void Test() - //{ - // // start and terminate - // using (var app = Application.GetApplication(TestOptions.ConnectionString, TestOptions.DatabaseProvider)) - // { } + //// [Test] + //// public void Test() + //// { + //// // start and terminate + //// using (var app = Application.GetApplication(TestOptions.ConnectionString, TestOptions.DatabaseProvider)) + //// { } - // // start and terminate - // using (var app = Application.GetApplication(TestOptions.ConnectionString, TestOptions.DatabaseProvider)) - // { } + //// // start and terminate + //// using (var app = Application.GetApplication(TestOptions.ConnectionString, TestOptions.DatabaseProvider)) + //// { } - // // start, use and terminate - // using (var app = Application.GetApplication(TestOptions.ConnectionString, TestOptions.DatabaseProvider)) - // { - // var types = app.GetContentTypes(); - // } - //} + //// // start, use and terminate + //// using (var app = Application.GetApplication(TestOptions.ConnectionString, TestOptions.DatabaseProvider)) + //// { + //// var types = app.GetContentTypes(); + //// } + //// } [Test] public void ThrowsOnDuplicateAliases() diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.PublishedCache.NuCache/SnapDictionaryTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.PublishedCache.NuCache/SnapDictionaryTests.cs index 05157d961a..7a60cf473c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.PublishedCache.NuCache/SnapDictionaryTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.PublishedCache.NuCache/SnapDictionaryTests.cs @@ -1,4 +1,6 @@ - +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Linq; using System.Threading.Tasks; @@ -47,7 +49,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(1, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s = d.CreateSnapshot(); + SnapDictionary.Snapshot s = d.CreateSnapshot(); Assert.AreEqual(1, s.Gen); Assert.AreEqual(1, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -67,7 +69,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache public void MissingReturnsNull() { var d = new SnapDictionary(); - var s = d.CreateSnapshot(); + SnapDictionary.Snapshot s = d.CreateSnapshot(); Assert.IsNull(s.Get(1)); } @@ -80,13 +82,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache // gen 1 d.Set(1, "one"); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual("one", s1.Get(1)); // gen 2 d.Clear(1); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.IsNull(s2.Get(1)); Assert.AreEqual("one", s1.Get(1)); @@ -110,7 +112,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(1, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(1, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -125,7 +127,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(2, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(2, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -140,7 +142,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(3, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var tv = d.Test.GetValues(1); + SnapDictionary.TestHelper.GenVal[] tv = d.Test.GetValues(1); Assert.AreEqual(3, tv[0].Gen); Assert.AreEqual(2, tv[1].Gen); Assert.AreEqual(1, tv[2].Gen); @@ -185,7 +187,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache var d = new SnapDictionary(); d.Test.CollectAuto = false; - for (var i = 0; i < 32; i++) + for (int i = 0; i < 32; i++) { d.Set(i, i.ToString()); d.CreateSnapshot().Dispose(); @@ -201,8 +203,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(0, d.SnapCount); Assert.AreEqual(32, d.Count); - for (var i = 0; i < 32; i++) + for (int i = 0; i < 32; i++) + { d.Set(i, null); + } d.CreateSnapshot().Dispose(); @@ -237,7 +241,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(1, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(1, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -252,7 +256,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(2, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(2, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -269,7 +273,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(3, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var tv = d.Test.GetValues(1); + SnapDictionary.TestHelper.GenVal[] tv = d.Test.GetValues(1); Assert.AreEqual(3, tv[0].Gen); Assert.AreEqual(2, tv[1].Gen); Assert.AreEqual(1, tv[2].Gen); @@ -334,11 +338,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.IsTrue(d.Test.NextGen); await d.CollectAsync(); - var tv = d.Test.GetValues(1); + SnapDictionary.TestHelper.GenVal[] tv = d.Test.GetValues(1); Assert.AreEqual(1, tv.Length); Assert.AreEqual(1, tv[0].Gen); - var s = d.CreateSnapshot(); + SnapDictionary.Snapshot s = d.CreateSnapshot(); Assert.AreEqual("one", s.Get(1)); Assert.AreEqual(1, d.Test.LiveGen); @@ -391,7 +395,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache // collect liveGen GC.Collect(); - Assert.IsTrue(d.Test.GenObjs.TryPeek(out var genObj)); + Assert.IsTrue(d.Test.GenObjs.TryPeek(out global::Umbraco.Web.PublishedCache.NuCache.Snap.GenObj genObj)); genObj = null; // in Release mode, it works, but in Debug mode, the weak reference is still alive @@ -426,7 +430,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(1, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(1, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -438,7 +442,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(2, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(2, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -450,7 +454,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(3, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s3 = d.CreateSnapshot(); + SnapDictionary.Snapshot s3 = d.CreateSnapshot(); Assert.AreEqual(3, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -486,7 +490,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(1, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(1, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -498,7 +502,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(2, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(2, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -510,7 +514,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(3, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s3 = d.CreateSnapshot(); + SnapDictionary.Snapshot s3 = d.CreateSnapshot(); Assert.AreEqual(3, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); @@ -539,14 +543,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache d.Set(1, "one"); d.Set(2, "two"); - var s1 = d.CreateSnapshot(); - var v1 = s1.Get(1); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); + string v1 = s1.Get(1); Assert.AreEqual("one", v1); d.Set(1, "uno"); - var s2 = d.CreateSnapshot(); - var v2 = s2.Get(1); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); + string v2 = s2.Get(1); Assert.AreEqual("uno", v2); v1 = s1.Get(1); @@ -586,14 +590,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache d.Set(1, "one"); d.Set(2, "two"); - var s1 = d.CreateSnapshot(); - var v1 = s1.Get(1); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); + string v1 = s1.Get(1); Assert.AreEqual("one", v1); d.Clear(1); - var s2 = d.CreateSnapshot(); - var v2 = s2.Get(1); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); + string v2 = s2.Get(1); Assert.AreEqual(null, v2); v1 = s1.Get(1); @@ -638,7 +642,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache using (d.GetScopedWriteLock(GetScopeProvider())) { - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(0, s1.Gen); Assert.AreEqual(1, d.Test.LiveGen); @@ -646,7 +650,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.IsNull(s1.Get(1)); } - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(1, s2.Gen); Assert.AreEqual(1, d.Test.LiveGen); @@ -667,7 +671,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(1, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(1, s1.Gen); Assert.AreEqual(1, d.Test.LiveGen); @@ -682,7 +686,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(2, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(2, s2.Gen); Assert.AreEqual(2, d.Test.LiveGen); @@ -699,7 +703,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(3, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s3 = d.CreateSnapshot(); + SnapDictionary.Snapshot s3 = d.CreateSnapshot(); Assert.AreEqual(2, s3.Gen); Assert.AreEqual(3, d.Test.LiveGen); @@ -707,7 +711,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual("uno", s3.Get(1)); } - var s4 = d.CreateSnapshot(); + SnapDictionary.Snapshot s4 = d.CreateSnapshot(); Assert.AreEqual(3, s4.Gen); Assert.AreEqual(3, d.Test.LiveGen); @@ -719,16 +723,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache public void NestedWriteLocking1() { var d = new SnapDictionary(); - var t = d.Test; + SnapDictionary.TestHelper t = d.Test; t.CollectAuto = false; Assert.AreEqual(0, d.CreateSnapshot().Gen); // no scope context: writers nest, last one to be disposed commits + IScopeProvider scopeProvider = GetScopeProvider(); - var scopeProvider = GetScopeProvider(); - - using (var w1 = d.GetScopedWriteLock(scopeProvider)) + using (IDisposable w1 = d.GetScopedWriteLock(scopeProvider)) { Assert.AreEqual(1, t.LiveGen); Assert.IsTrue(t.IsLocked); @@ -736,7 +739,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.Throws(() => { - using (var w2 = d.GetScopedWriteLock(scopeProvider)) + using (IDisposable w2 = d.GetScopedWriteLock(scopeProvider)) { } }); @@ -764,16 +767,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(0, d.CreateSnapshot().Gen); // scope context: writers enlist - var scopeContext = new ScopeContext(); - var scopeProvider = GetScopeProvider(scopeContext); + IScopeProvider scopeProvider = GetScopeProvider(scopeContext); - using (var w1 = d.GetScopedWriteLock(scopeProvider)) + using (IDisposable w1 = d.GetScopedWriteLock(scopeProvider)) { // This one is interesting, although we don't allow recursive locks, since this is - // using the same ScopeContext/key, the lock acquisition is only done once - - using (var w2 = d.GetScopedWriteLock(scopeProvider)) + // using the same ScopeContext/key, the lock acquisition is only done once. + using (IDisposable w2 = d.GetScopedWriteLock(scopeProvider)) { Assert.AreSame(w1, w2); @@ -786,16 +787,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache public void NestedWriteLocking3() { var d = new SnapDictionary(); - var t = d.Test; + SnapDictionary.TestHelper t = d.Test; t.CollectAuto = false; Assert.AreEqual(0, d.CreateSnapshot().Gen); var scopeContext = new ScopeContext(); - var scopeProvider1 = GetScopeProvider(); - var scopeProvider2 = GetScopeProvider(scopeContext); + IScopeProvider scopeProvider1 = GetScopeProvider(); + IScopeProvider scopeProvider2 = GetScopeProvider(scopeContext); - using (var w1 = d.GetScopedWriteLock(scopeProvider1)) + using (IDisposable w1 = d.GetScopedWriteLock(scopeProvider1)) { Assert.AreEqual(1, t.LiveGen); Assert.IsTrue(t.IsLocked); @@ -803,11 +804,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.Throws(() => { - using (var w2 = d.GetScopedWriteLock(scopeProvider2)) + using (IDisposable w2 = d.GetScopedWriteLock(scopeProvider2)) { } }); - } } @@ -824,7 +824,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(1, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(1, s1.Gen); Assert.AreEqual(1, d.Test.LiveGen); @@ -839,15 +839,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(2, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(2, s2.Gen); Assert.AreEqual(2, d.Test.LiveGen); Assert.IsFalse(d.Test.NextGen); Assert.AreEqual("uno", s2.Get(1)); - - var scopeProvider = GetScopeProvider(); + IScopeProvider scopeProvider = GetScopeProvider(); using (d.GetScopedWriteLock(scopeProvider)) { // gen 3 @@ -858,7 +857,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(3, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s3 = d.CreateSnapshot(); + SnapDictionary.Snapshot s3 = d.CreateSnapshot(); Assert.AreEqual(2, s3.Gen); Assert.AreEqual(3, d.Test.LiveGen); @@ -866,7 +865,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual("uno", s3.Get(1)); } - var s4 = d.CreateSnapshot(); + SnapDictionary.Snapshot s4 = d.CreateSnapshot(); Assert.AreEqual(3, s4.Gen); Assert.AreEqual(3, d.Test.LiveGen); @@ -880,35 +879,34 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache var d = new SnapDictionary(); d.Test.CollectAuto = false; - // gen 1 d.Set(1, "one"); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(1, s1.Gen); Assert.AreEqual("one", s1.Get(1)); d.Set(1, "uno"); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(2, s2.Gen); Assert.AreEqual("uno", s2.Get(1)); - var scopeProvider = GetScopeProvider(); + IScopeProvider scopeProvider = GetScopeProvider(); using (d.GetScopedWriteLock(scopeProvider)) { // creating a snapshot in a write-lock does NOT return the "current" content // it uses the previous snapshot, so new snapshot created only on release d.SetLocked(1, "ein"); - var s3 = d.CreateSnapshot(); + SnapDictionary.Snapshot s3 = d.CreateSnapshot(); Assert.AreEqual(2, s3.Gen); Assert.AreEqual("uno", s3.Get(1)); // but live snapshot contains changes - var ls = d.Test.LiveSnapshot; + SnapDictionary.Snapshot ls = d.Test.LiveSnapshot; Assert.AreEqual("ein", ls.Get(1)); Assert.AreEqual(3, ls.Gen); } - var s4 = d.CreateSnapshot(); + SnapDictionary.Snapshot s4 = d.CreateSnapshot(); Assert.AreEqual(3, s4.Gen); Assert.AreEqual("ein", s4.Get(1)); } @@ -921,39 +919,39 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache // gen 1 d.Set(1, "one"); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(1, s1.Gen); Assert.AreEqual("one", s1.Get(1)); d.Set(1, "uno"); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(2, s2.Gen); Assert.AreEqual("uno", s2.Get(1)); var scopeContext = new ScopeContext(); - var scopeProvider = GetScopeProvider(scopeContext); + IScopeProvider scopeProvider = GetScopeProvider(scopeContext); using (d.GetScopedWriteLock(scopeProvider)) { // creating a snapshot in a write-lock does NOT return the "current" content // it uses the previous snapshot, so new snapshot created only on release d.SetLocked(1, "ein"); - var s3 = d.CreateSnapshot(); + SnapDictionary.Snapshot s3 = d.CreateSnapshot(); Assert.AreEqual(2, s3.Gen); Assert.AreEqual("uno", s3.Get(1)); // but live snapshot contains changes - var ls = d.Test.LiveSnapshot; + SnapDictionary.Snapshot ls = d.Test.LiveSnapshot; Assert.AreEqual("ein", ls.Get(1)); Assert.AreEqual(3, ls.Gen); } - var s4 = d.CreateSnapshot(); + SnapDictionary.Snapshot s4 = d.CreateSnapshot(); Assert.AreEqual(2, s4.Gen); Assert.AreEqual("uno", s4.Get(1)); scopeContext.ScopeExit(true); - var s5 = d.CreateSnapshot(); + SnapDictionary.Snapshot s5 = d.CreateSnapshot(); Assert.AreEqual(3, s5.Gen); Assert.AreEqual("ein", s5.Get(1)); } @@ -962,17 +960,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache public void ScopeLocking2() { var d = new SnapDictionary(); - var t = d.Test; + SnapDictionary.TestHelper t = d.Test; t.CollectAuto = false; // gen 1 d.Set(1, "one"); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.AreEqual(1, s1.Gen); Assert.AreEqual("one", s1.Get(1)); d.Set(1, "uno"); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.AreEqual(2, s2.Gen); Assert.AreEqual("uno", s2.Get(1)); @@ -980,13 +978,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.IsFalse(t.NextGen); var scopeContext = new ScopeContext(); - var scopeProvider = GetScopeProvider(scopeContext); + IScopeProvider scopeProvider = GetScopeProvider(scopeContext); using (d.GetScopedWriteLock(scopeProvider)) { // creating a snapshot in a write-lock does NOT return the "current" content // it uses the previous snapshot, so new snapshot created only on release d.SetLocked(1, "ein"); - var s3 = d.CreateSnapshot(); + SnapDictionary.Snapshot s3 = d.CreateSnapshot(); Assert.AreEqual(2, s3.Gen); Assert.AreEqual("uno", s3.Get(1)); @@ -996,7 +994,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.IsTrue(t.IsLocked); // but live snapshot contains changes - var ls = t.LiveSnapshot; + SnapDictionary.Snapshot ls = t.LiveSnapshot; Assert.AreEqual("ein", ls.Get(1)); Assert.AreEqual(3, ls.Gen); } @@ -1007,7 +1005,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.IsTrue(t.IsLocked); // no changes until exit - var s4 = d.CreateSnapshot(); + SnapDictionary.Snapshot s4 = d.CreateSnapshot(); Assert.AreEqual(2, s4.Gen); Assert.AreEqual("uno", s4.Get(1)); @@ -1019,7 +1017,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.IsFalse(t.IsLocked); // no changes since not completed - var s5 = d.CreateSnapshot(); + SnapDictionary.Snapshot s5 = d.CreateSnapshot(); Assert.AreEqual(2, s5.Gen); Assert.AreEqual("uno", s5.Get(1)); } @@ -1037,14 +1035,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache d.Set(3, "three"); d.Set(4, "four"); - var s1 = d.CreateSnapshot(); - var all = s1.GetAll().ToArray(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); + string[] all = s1.GetAll().ToArray(); Assert.AreEqual(4, all.Length); Assert.AreEqual("one", all[0]); Assert.AreEqual("four", all[3]); d.Set(1, "uno"); - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); all = s1.GetAll().ToArray(); Assert.AreEqual(4, all.Length); @@ -1071,7 +1069,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(1, d.Test.LiveGen); Assert.IsNull(d.Test.GenObj); - var s1 = d.CreateSnapshot(); + SnapDictionary.Snapshot s1 = d.CreateSnapshot(); Assert.IsFalse(d.Test.NextGen); Assert.AreEqual(1, d.Test.LiveGen); Assert.IsNotNull(d.Test.GenObj); @@ -1087,13 +1085,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(1, d.Test.GenObj.Gen); var scopeContext = new ScopeContext(); - var scopeProvider = GetScopeProvider(scopeContext); + IScopeProvider scopeProvider = GetScopeProvider(scopeContext); // scopeProvider.Context == scopeContext -> writer is scoped // writer is scope contextual and scoped // when disposed, nothing happens // when the context exists, the writer is released - using (d.GetScopedWriteLock(scopeProvider)) { d.SetLocked(1, "ein"); @@ -1113,7 +1110,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(3, d.Test.LiveGen); // panic! - var s2 = d.CreateSnapshot(); + SnapDictionary.Snapshot s2 = d.CreateSnapshot(); Assert.IsTrue(d.Test.IsLocked); Assert.IsNotNull(d.Test.GenObj); @@ -1130,7 +1127,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache Assert.AreEqual(3, d.Test.LiveGen); Assert.IsTrue(d.Test.NextGen); - var s3 = d.CreateSnapshot(); + SnapDictionary.Snapshot s3 = d.CreateSnapshot(); Assert.IsFalse(d.Test.IsLocked); Assert.IsNotNull(d.Test.GenObj); @@ -1141,7 +1138,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache private IScopeProvider GetScopeProvider(ScopeContext scopeContext = null) { - var scopeProvider = Mock.Of(); + IScopeProvider scopeProvider = Mock.Of(); Mock.Get(scopeProvider) .Setup(x => x.Context).Returns(scopeContext); return scopeProvider; @@ -1182,7 +1179,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Umbraco.PublishedCache private static IScopeProvider GetScopeProvider() { - var scopeProvider = Mock.Of(); + IScopeProvider scopeProvider = Mock.Of(); Mock.Get(scopeProvider) .Setup(x => x.Context).Returns(() => null); return scopeProvider; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/AllowedContentTypeDetail.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/AllowedContentTypeDetail.cs index 08ac69b1bb..b4c59de805 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/AllowedContentTypeDetail.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/AllowedContentTypeDetail.cs @@ -1,4 +1,7 @@ -namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders +// Copyright (c) Umbraco. +// See LICENSE for more details. + +namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders { public class AllowedContentTypeDetail { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ContentTypeBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ContentTypeBuilderTests.cs index 98d887d984..157bf67fea 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ContentTypeBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ContentTypeBuilderTests.cs @@ -1,5 +1,7 @@ -using System; -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using NUnit.Framework; using Umbraco.Core; @@ -23,8 +25,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const string testPropertyGroupName = "Content"; const int testParentId = 98; const int testCreatorId = 22; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; const int testLevel = 3; const string testPath = "-1, 4, 10"; const int testSortOrder = 5; @@ -43,7 +45,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new ContentTypeBuilder(); // Act - var contentType = builder + IContentType contentType = builder .WithId(testId) .WithKey(testKey) .WithAlias(testAlias) @@ -119,7 +121,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders Assert.IsFalse(contentType.IsContainer); Assert.AreEqual(2, contentType.PropertyTypes.Count()); - var propertyTypeIds = contentType.PropertyTypes.Select(x => x.Id).OrderBy(x => x); + IOrderedEnumerable propertyTypeIds = contentType.PropertyTypes.Select(x => x.Id).OrderBy(x => x); Assert.AreEqual(testPropertyTypeIdsIncrementingFrom + 1, propertyTypeIds.Min()); Assert.AreEqual(testPropertyTypeIdsIncrementingFrom + 2, propertyTypeIds.Max()); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DataTypeBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DataTypeBuilderTests.cs index ce47c69763..5e9ebccdb9 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DataTypeBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DataTypeBuilderTests.cs @@ -1,4 +1,8 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -16,12 +20,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new DataTypeBuilder(); // Act - var dtd = builder + DataType dataType = builder .WithId(testId) .Build(); // Assert - Assert.AreEqual(testId, dtd.Id); + Assert.AreEqual(testId, dataType.Id); } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilderTests.cs index 0aa93be802..3f99904f61 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilderTests.cs @@ -1,6 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using NUnit.Framework; +using Umbraco.Core.Models.Entities; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -26,15 +30,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const string testContentTypeIcon = "icon"; const string testContentTypeThumbnail = "thumb"; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; var testAdditionalData1 = new KeyValuePair("test1", 123); var testAdditionalData2 = new KeyValuePair("test2", "hello"); var builder = new DocumentEntitySlimBuilder(); // Act - var item = builder + DocumentEntitySlim item = builder .WithId(testId) .WithKey(testKey) .WithCreatorId(testCreatorId) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/LanguageBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/LanguageBuilderTests.cs index 1efd9ddc01..a30ec6b0bf 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/LanguageBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/LanguageBuilderTests.cs @@ -1,5 +1,9 @@ -using System.Globalization; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Globalization; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -17,7 +21,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var expected = CultureInfo.GetCultureInfo("en-GB"); // Act - var language = builder + ILanguage language = builder .WithCultureInfo(expected.Name) .Build(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MacroBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MacroBuilderTests.cs index bf5d899d6a..fd98331634 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MacroBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MacroBuilderTests.cs @@ -1,5 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -31,7 +35,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new MacroBuilder(); // Act - var macro = builder + Macro macro = builder .WithId(id) .WithKey(key) .WithUseInEditor(useInEditor) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MediaTypeBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MediaTypeBuilderTests.cs index 1c4af5da81..720c6dbb8c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MediaTypeBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MediaTypeBuilderTests.cs @@ -1,5 +1,7 @@ -using System; -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using NUnit.Framework; using Umbraco.Core; @@ -23,8 +25,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const string testPropertyGroupName = "Additional Content"; const int testParentId = 98; const int testCreatorId = 22; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; const int testLevel = 3; const string testPath = "-1, 4, 10"; const int testSortOrder = 5; @@ -39,7 +41,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new MediaTypeBuilder(); // Act - var mediaType = builder + IMediaType mediaType = builder .WithId(testId) .WithKey(testKey) .WithAlias(testAlias) @@ -99,7 +101,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders Assert.IsFalse(mediaType.IsContainer); Assert.AreEqual(7, mediaType.PropertyTypes.Count()); // 5 from media properties group, 2 custom - var propertyTypeIds = mediaType.PropertyTypes.Select(x => x.Id).OrderBy(x => x); + IOrderedEnumerable propertyTypeIds = mediaType.PropertyTypes.Select(x => x.Id).OrderBy(x => x); Assert.AreEqual(testPropertyTypeIdsIncrementingFrom + 1, propertyTypeIds.Min()); Assert.AreEqual(testPropertyTypeIdsIncrementingFrom + 7, propertyTypeIds.Max()); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberBuilderTests.cs index 4a85949826..16b1a98ec8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberBuilderTests.cs @@ -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; @@ -33,12 +36,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const int testSortOrder = 5; const bool testTrashed = false; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; const int testFailedPasswordAttempts = 22; - var testLastLockoutDate = DateTime.Now.AddHours(-2); - var testLastLoginDate = DateTime.Now.AddHours(-3); - var testLastPasswordChangeDate = DateTime.Now.AddHours(-4); + DateTime testLastLockoutDate = DateTime.Now.AddHours(-2); + DateTime testLastLoginDate = DateTime.Now.AddHours(-3); + DateTime testLastPasswordChangeDate = DateTime.Now.AddHours(-4); var testPropertyType1 = new PropertyTypeDetail { Alias = "title", Name = "Title", SortOrder = 1, DataTypeId = -88 }; var testPropertyType2 = new PropertyTypeDetail { Alias = "bodyText", Name = "Body Text", SortOrder = 2, DataTypeId = -87 }; var testPropertyType3 = new PropertyTypeDetail { Alias = "author", Name = "Author", Description = "Writer of the article", SortOrder = 1, DataTypeId = -88 }; @@ -53,7 +56,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new MemberBuilder(); // Act - var member = builder + Member member = builder .AddMemberType() .WithId(testMemberTypeId) .WithAlias(testMemberTypeAlias) @@ -140,7 +143,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders Assert.AreEqual(testPropertyData2.Value, member.GetValue(testPropertyData2.Key)); Assert.AreEqual(testPropertyData3.Value, member.GetValue(testPropertyData3.Key)); - var propertyIds = member.Properties.Select(x => x.Id).OrderBy(x => x); + IOrderedEnumerable propertyIds = member.Properties.Select(x => x.Id).OrderBy(x => x); Assert.AreEqual(testPropertyIdsIncrementingFrom + 1, propertyIds.Min()); Assert.AreEqual(testPropertyIdsIncrementingFrom + 10, propertyIds.Max()); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberGroupBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberGroupBuilderTests.cs index 4cb47de052..afa7de5aac 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberGroupBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberGroupBuilderTests.cs @@ -1,6 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -17,15 +21,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const string testName = "Test Group"; const int testCreatorId = 4; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; var testAdditionalData1 = new KeyValuePair("test1", 123); var testAdditionalData2 = new KeyValuePair("test2", "hello"); var builder = new MemberGroupBuilder(); // Act - var group = builder + MemberGroup group = builder .WithId(testId) .WithKey(testKey) .WithName(testName) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberTypeBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberTypeBuilderTests.cs index e42ad306f8..b55d6467f1 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberTypeBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberTypeBuilderTests.cs @@ -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; @@ -23,8 +26,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const string testPropertyGroupName = "Content"; const int testParentId = 98; const int testCreatorId = 22; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; const int testLevel = 3; const string testPath = "-1, 4, 10"; const int testSortOrder = 5; @@ -40,7 +43,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new MemberTypeBuilder(); // Act - var memberType = builder + IMemberType memberType = builder .WithId(testId) .WithKey(testKey) .WithAlias(testAlias) @@ -99,7 +102,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders Assert.IsFalse(memberType.IsContainer); Assert.AreEqual(9, memberType.PropertyTypes.Count()); // 7 from membership properties group, 2 custom - var propertyTypeIds = memberType.PropertyTypes.Select(x => x.Id).OrderBy(x => x); + IOrderedEnumerable propertyTypeIds = memberType.PropertyTypes.Select(x => x.Id).OrderBy(x => x); Assert.AreEqual(testPropertyTypeIdsIncrementingFrom + 1, propertyTypeIds.Min()); Assert.AreEqual(testPropertyTypeIdsIncrementingFrom + 9, propertyTypeIds.Max()); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyBuilderTests.cs index 7010132091..8ce3b89bd3 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyBuilderTests.cs @@ -1,5 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -14,14 +18,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders // Arrange const int testId = 4; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; var testPropertyTypeId = 3; var builder = new PropertyBuilder(); // Act - var property = builder + IProperty property = builder .WithId(testId) .WithKey(testKey) .WithCreateDate(testCreateDate) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyGroupBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyGroupBuilderTests.cs index aa68e02388..adc460732b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyGroupBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyGroupBuilderTests.cs @@ -1,5 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -16,14 +20,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var testKey = Guid.NewGuid(); const string testName = "Group1"; const int testSortOrder = 555; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; const int testPropertyTypeId = 3; var builder = new PropertyGroupBuilder(); // Act - var propertyGroup = builder + PropertyGroup propertyGroup = builder .WithId(testId) .WithCreateDate(testCreateDate) .WithName(testName) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeBuilderTests.cs index 6bcb22ce4d..a774e924f8 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeBuilderTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; @@ -21,8 +24,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const string testName = "Test"; const int testSortOrder = 9; const int testDataTypeId = 5; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; const string testDescription = "testing"; const int testPropertyGroupId = 11; const bool testMandatory = true; @@ -33,7 +36,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new PropertyTypeBuilder(); // Act - var propertyType = builder + PropertyType propertyType = builder .WithId(testId) .WithPropertyEditorAlias(testPropertyEditorAlias) .WithValueStorageType(testValueStorageType) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeDetail.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeDetail.cs index 1b1a1f013b..d074e6443d 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeDetail.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeDetail.cs @@ -1,4 +1,7 @@ -namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders +// Copyright (c) Umbraco. +// See LICENSE for more details. + +namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders { public class PropertyTypeDetail { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationBuilderTests.cs index b59ae261e0..09d9121295 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationBuilderTests.cs @@ -1,5 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -16,8 +20,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const int childId = 8; const int id = 4; var key = Guid.NewGuid(); - var createDate = DateTime.Now.AddHours(-1); - var updateDate = DateTime.Now; + DateTime createDate = DateTime.Now.AddHours(-1); + DateTime updateDate = DateTime.Now; const string comment = "test comment"; const int relationTypeId = 66; const string relationTypeAlias = "test"; @@ -28,7 +32,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new RelationBuilder(); // Act - var relation = builder + Relation relation = builder .BetweenIds(parentId, childId) .WithId(id) .WithComment(comment) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationTypeBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationTypeBuilderTests.cs index 274ae7d878..e262d5ebbe 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationTypeBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationTypeBuilderTests.cs @@ -1,5 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -16,9 +20,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const string alias = "test"; const string name = "Test"; var key = Guid.NewGuid(); - var createDate = DateTime.Now.AddHours(-2); - var updateDate = DateTime.Now.AddHours(-1); - var deleteDate = DateTime.Now; + DateTime createDate = DateTime.Now.AddHours(-2); + DateTime updateDate = DateTime.Now.AddHours(-1); + DateTime deleteDate = DateTime.Now; var parentObjectType = Guid.NewGuid(); var childObjectType = Guid.NewGuid(); const bool isBidirectional = true; @@ -26,7 +30,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new RelationTypeBuilder(); // Act - var relationType = builder + IRelationType relationType = builder .WithId(id) .WithAlias(alias) .WithName(name) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/StylesheetBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/StylesheetBuilderTests.cs index c770860b9c..9c8e5fbc28 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/StylesheetBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/StylesheetBuilderTests.cs @@ -1,6 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.IO; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Core.Routing; using Umbraco.Tests.Common.Builders; @@ -19,7 +22,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new StylesheetBuilder(); // Act - var stylesheet = builder + Stylesheet stylesheet = builder .WithPath(testPath) .WithContent(testContent) .Build(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateBuilderTests.cs index 717c937f7d..e0ec812d4e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateBuilderTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders; @@ -17,8 +20,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const string testAlias = "test"; const string testName = "Test"; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; const string testPath = "-1,3"; const string testContent = "blah"; const string testMasterTemplateAlias = "master"; @@ -27,7 +30,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new TemplateBuilder(); // Act - var template = builder + ITemplate template = builder .WithId(3) .WithAlias(testAlias) .WithName(testName) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateDetail.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateDetail.cs index 2a085931b8..f612fcf0a3 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateDetail.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateDetail.cs @@ -1,4 +1,7 @@ -namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders +// Copyright (c) Umbraco. +// See LICENSE for more details. + +namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders { public class TemplateDetail { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserBuilderTests.cs index 5b3b0595a3..1063f7cf96 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserBuilderTests.cs @@ -1,5 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; +using Umbraco.Core.Models.Membership; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -20,12 +24,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders const bool testIsApproved = true; const bool testIsLockedOut = true; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + DateTime testCreateDate = DateTime.Now.AddHours(-1); + DateTime testUpdateDate = DateTime.Now; const int testFailedPasswordAttempts = 22; - var testLastLockoutDate = DateTime.Now.AddHours(-2); - var testLastLoginDate = DateTime.Now.AddHours(-3); - var testLastPasswordChangeDate = DateTime.Now.AddHours(-4); + DateTime testLastLockoutDate = DateTime.Now.AddHours(-2); + DateTime testLastLoginDate = DateTime.Now.AddHours(-3); + DateTime testLastPasswordChangeDate = DateTime.Now.AddHours(-4); var testComments = "comments"; var testSessionTimeout = 5; var testStartContentIds = new[] { 3 }; @@ -34,7 +38,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new UserBuilder(); // Act - var user = builder + User user = builder .WithId(testId) .WithKey(testKey) .WithName(testName) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserGroupBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserGroupBuilderTests.cs index 0cfa0649ff..2751ea0e15 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserGroupBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserGroupBuilderTests.cs @@ -1,5 +1,9 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using NUnit.Framework; +using Umbraco.Core.Models.Membership; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -24,7 +28,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new UserGroupBuilder(); // Act - var userGroup = builder + IUserGroup userGroup = builder .WithId(testId) .WithAlias(testAlias) .WithName(testName) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/XmlDocumentBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/XmlDocumentBuilderTests.cs index 64f305edd8..028b2842d1 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/XmlDocumentBuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/XmlDocumentBuilderTests.cs @@ -1,4 +1,8 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Xml; +using NUnit.Framework; using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders @@ -16,7 +20,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders var builder = new XmlDocumentBuilder(); // Act - var xml = builder + XmlDocument xml = builder .WithContent(content) .Build(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerUnitTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerTests.cs similarity index 86% rename from src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerUnitTests.cs rename to src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerTests.cs index 4f4db85e5e..d8e5a04c59 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerUnitTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using AutoFixture.NUnit3; using Moq; using NUnit.Framework; @@ -9,9 +12,10 @@ using Umbraco.Web.Common.Exceptions; namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Controllers { [TestFixture] - public class UsersControllerUnitTests + public class UsersControllerTests { - [Test,AutoMoqData] + [Test] + [AutoMoqData] public void PostUnlockUsers_When_User_Lockout_Update_Fails_Expect_Failure_Response( [Frozen] IBackOfficeUserManager backOfficeUserManager, UsersController sut, @@ -25,6 +29,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Controllers Assert.ThrowsAsync(() => sut.PostUnlockUsers(userIds)); } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Extensions/ModelStateExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Extensions/ModelStateExtensionsTests.cs index 01dad1eebf..ce182c7e7c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Extensions/ModelStateExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Extensions/ModelStateExtensionsTests.cs @@ -1,4 +1,8 @@ -using System.ComponentModel.DataAnnotations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; using System.Linq; using Microsoft.AspNetCore.Mvc.ModelBinding; using Moq; @@ -11,7 +15,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Extensions [TestFixture] public class ModelStateExtensionsTests { - [Test] public void Get_Cultures_With_Errors() { @@ -19,12 +22,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Extensions var localizationService = new Mock(); localizationService.Setup(x => x.GetDefaultLanguageIsoCode()).Returns("en-US"); - ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", null); //invariant property - ms.AddPropertyError(new ValidationResult("title missing"), "title", "en-US"); //variant property + ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", null); // invariant property + ms.AddPropertyError(new ValidationResult("title missing"), "title", "en-US"); // variant property - var result = ms.GetVariantsWithErrors("en-US"); + IReadOnlyList<(string culture, string segment)> result = ms.GetVariantsWithErrors("en-US"); - //even though there are 2 errors, they are both for en-US since that is the default language and one of the errors is for an invariant property + // even though there are 2 errors, they are both for en-US since that is the default language and one of the errors is for an invariant property Assert.AreEqual(1, result.Count); Assert.AreEqual("en-US", result[0].culture); @@ -44,12 +47,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Extensions var localizationService = new Mock(); localizationService.Setup(x => x.GetDefaultLanguageIsoCode()).Returns("en-US"); - ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", null); //invariant property - ms.AddPropertyError(new ValidationResult("title missing"), "title", "en-US"); //variant property + ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", null); // invariant property + ms.AddPropertyError(new ValidationResult("title missing"), "title", "en-US"); // variant property - var result = ms.GetVariantsWithPropertyErrors("en-US"); + IReadOnlyList<(string culture, string segment)> result = ms.GetVariantsWithPropertyErrors("en-US"); - //even though there are 2 errors, they are both for en-US since that is the default language and one of the errors is for an invariant property + // even though there are 2 errors, they are both for en-US since that is the default language and one of the errors is for an invariant property Assert.AreEqual(1, result.Count); Assert.AreEqual("en-US", result[0].culture); } @@ -61,7 +64,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Extensions var localizationService = new Mock(); localizationService.Setup(x => x.GetDefaultLanguageIsoCode()).Returns("en-US"); - ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", null); //invariant property + ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", null); // invariant property Assert.AreEqual("_Properties.headerImage.invariant.null", ms.Keys.First()); } @@ -73,7 +76,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Extensions var localizationService = new Mock(); localizationService.Setup(x => x.GetDefaultLanguageIsoCode()).Returns("en-US"); - ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", "en-US"); //variant property + ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", "en-US"); // variant property Assert.AreEqual("_Properties.headerImage.en-US.null", ms.Keys.First()); } @@ -85,7 +88,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Extensions var localizationService = new Mock(); localizationService.Setup(x => x.GetDefaultLanguageIsoCode()).Returns("en-US"); - ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", null, "mySegment"); //invariant/segment property + ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", null, "mySegment"); // invariant/segment property Assert.AreEqual("_Properties.headerImage.invariant.mySegment", ms.Keys.First()); } @@ -97,7 +100,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Extensions var localizationService = new Mock(); localizationService.Setup(x => x.GetDefaultLanguageIsoCode()).Returns("en-US"); - ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", "en-US", "mySegment"); //variant/segment property + ms.AddPropertyError(new ValidationResult("no header image"), "headerImage", "en-US", "mySegment"); // variant/segment property Assert.AreEqual("_Properties.headerImage.en-US.mySegment", ms.Keys.First()); } @@ -109,7 +112,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Extensions var localizationService = new Mock(); localizationService.Setup(x => x.GetDefaultLanguageIsoCode()).Returns("en-US"); - ms.AddPropertyError(new ValidationResult("no header image", new[] { "myField" }), "headerImage", null, "mySegment"); //invariant/segment property + ms.AddPropertyError(new ValidationResult("no header image", new[] { "myField" }), "headerImage", null, "mySegment"); // invariant/segment property Assert.AreEqual("_Properties.headerImage.invariant.mySegment.myField", ms.Keys.First()); } @@ -121,7 +124,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Extensions var localizationService = new Mock(); localizationService.Setup(x => x.GetDefaultLanguageIsoCode()).Returns("en-US"); - ms.AddPropertyError(new ValidationResult("no header image", new[] { "myField" }), "headerImage", "en-US", "mySegment"); //variant/segment property + ms.AddPropertyError(new ValidationResult("no header image", new[] { "myField" }), "headerImage", "en-US", "mySegment"); // variant/segment property Assert.AreEqual("_Properties.headerImage.en-US.mySegment.myField", ms.Keys.First()); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs index e18f5cb3f4..fe442a023b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs @@ -1,10 +1,14 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.Primitives; using Moq; using NUnit.Framework; using Umbraco.Core.Models.Membership; @@ -20,14 +24,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Appends_Header_When_No_User_Parameter_Provider() { // Arrange - var context = CreateContext(); + ActionExecutingContext context = CreateContext(); var attribute = new AppendUserModifiedHeaderAttribute(); // Act attribute.OnActionExecuting(context); // Assert - context.HttpContext.Response.Headers.TryGetValue("X-Umb-User-Modified", out var headerValue); + context.HttpContext.Response.Headers.TryGetValue("X-Umb-User-Modified", out StringValues headerValue); Assert.AreEqual("1", headerValue[0]); } @@ -35,14 +39,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Does_Not_Append_Header_If_Already_Exists() { // Arrange - var context = CreateContext(headerValue: "0"); + ActionExecutingContext context = CreateContext(headerValue: "0"); var attribute = new AppendUserModifiedHeaderAttribute(); // Act attribute.OnActionExecuting(context); // Assert - context.HttpContext.Response.Headers.TryGetValue("X-Umb-User-Modified", out var headerValue); + context.HttpContext.Response.Headers.TryGetValue("X-Umb-User-Modified", out StringValues headerValue); Assert.AreEqual("0", headerValue[0]); } @@ -50,7 +54,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Does_Not_Append_Header_When_User_Id_Parameter_Provided_And_Does_Not_Match_Current_User() { // Arrange - var context = CreateContext(actionArgument: new KeyValuePair("UserId", 99)); + ActionExecutingContext context = CreateContext(actionArgument: new KeyValuePair("UserId", 99)); var userIdParameter = "UserId"; var attribute = new AppendUserModifiedHeaderAttribute(userIdParameter); @@ -65,7 +69,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Appends_Header_When_User_Id_Parameter_Provided_And_Does_Not_Match_Current_User() { // Arrange - var context = CreateContext(actionArgument: new KeyValuePair("UserId", 100)); + ActionExecutingContext context = CreateContext(actionArgument: new KeyValuePair("UserId", 100)); var userIdParameter = "UserId"; var attribute = new AppendUserModifiedHeaderAttribute(userIdParameter); @@ -73,7 +77,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters attribute.OnActionExecuting(context); // Assert - context.HttpContext.Response.Headers.TryGetValue("X-Umb-User-Modified", out var headerValue); + context.HttpContext.Response.Headers.TryGetValue("X-Umb-User-Modified", out StringValues headerValue); Assert.AreEqual("1", headerValue[0]); } @@ -95,7 +99,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters .SetupGet(x => x.CurrentUser) .Returns(currentUserMock.Object); - var serviceProviderMock = new Mock(); serviceProviderMock .Setup(x => x.GetService(typeof(IBackOfficeSecurity))) diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs index 295ece927d..97f819a402 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.ComponentModel.DataAnnotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -11,7 +14,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters [TestFixture] public class ContentModelValidatorTests { - [Test] public void Test_Serializer() { @@ -52,7 +54,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters var outerError = new ComplexEditorValidationResult(); var id4 = Guid.NewGuid(); var addressBookCollectionElementTypeResult = new ComplexEditorElementTypeValidationResult("addressBookCollection", id4); - var booksPropertyTypeResult= new ComplexEditorPropertyTypeValidationResult("books"); + var booksPropertyTypeResult = new ComplexEditorPropertyTypeValidationResult("books"); booksPropertyTypeResult.AddValidationResult(nestedLevel1); // books is the outer most validation result addressBookCollectionElementTypeResult.ValidationResults.Add(booksPropertyTypeResult); outerError.ValidationResults.Add(addressBookCollectionElementTypeResult); @@ -60,7 +62,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters var serialized = JsonConvert.SerializeObject(outerError, Formatting.Indented, new ValidationResultConverter()); Console.WriteLine(serialized); - var jsonError = JsonConvert.DeserializeObject(serialized); + JArray jsonError = JsonConvert.DeserializeObject(serialized); Assert.IsNotNull(jsonError.SelectToken("$[0]")); Assert.AreEqual(id4.ToString(), jsonError.SelectToken("$[0].$id").Value()); @@ -105,6 +107,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters Assert.IsNotNull(error5); Assert.AreEqual(2, error5.Count); } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttributeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttributeTests.cs index 6126ee9419..fcd0dd0aea 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttributeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttributeTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Moq; @@ -23,16 +26,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters [Test] public void GetValueFromResponse_Already_EnumerableContent() { - var expected = new List() {new ContentItemBasic()}; + var expected = new List() { new ContentItemBasic() }; - var att = new FilterAllowedOutgoingContentFilter(expected.GetType(), + var att = new FilterAllowedOutgoingContentFilter( + expected.GetType(), null, ActionBrowse.ActionLetter, Mock.Of(), Mock.Of(), - Mock.Of() ); + Mock.Of()); - var result = att.GetValueFromResponse(new ObjectResult(expected)); + dynamic result = att.GetValueFromResponse(new ObjectResult(expected)); Assert.AreEqual(expected, result); } @@ -41,16 +45,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void GetValueFromResponse_From_Property() { var expected = new List() { new ContentItemBasic() }; - var container = new MyTestClass() {MyList = expected}; + var container = new MyTestClass() { MyList = expected }; - var att = new FilterAllowedOutgoingContentFilter(expected.GetType(), + var att = new FilterAllowedOutgoingContentFilter( + expected.GetType(), nameof(MyTestClass.MyList), ActionBrowse.ActionLetter, Mock.Of(), Mock.Of(), - Mock.Of() ); + Mock.Of()); - var result = att.GetValueFromResponse(new ObjectResult(container)); + dynamic result = att.GetValueFromResponse(new ObjectResult(container)); Assert.AreEqual(expected, result); } @@ -61,45 +66,47 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters var expected = new List() { new ContentItemBasic() }; var container = new MyTestClass() { MyList = expected }; - var att = new FilterAllowedOutgoingContentFilter(expected.GetType(), + var att = new FilterAllowedOutgoingContentFilter( + expected.GetType(), "DontFind", ActionBrowse.ActionLetter, Mock.Of(), Mock.Of(), - Mock.Of() ); + Mock.Of()); - var actual = att.GetValueFromResponse(new ObjectResult(container)); + dynamic actual = att.GetValueFromResponse(new ObjectResult(container)); Assert.IsNull(actual); - } [Test] public void Filter_On_Start_Node() { - var user = CreateUser(id: 9, startContentId: 5); + IUser user = CreateUser(id: 9, startContentId: 5); var userServiceMock = new Mock(); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; var entityServiceMock = new Mock(); entityServiceMock.Setup(x => x.GetAllPaths(It.IsAny(), It.IsAny())) .Returns(new[] { Mock.Of(entity => entity.Id == 5 && entity.Path == "-1,5") }); - var entityService = entityServiceMock.Object; + IEntityService entityService = entityServiceMock.Object; var list = new List(); - var att = new FilterAllowedOutgoingContentFilter(list.GetType(), + var att = new FilterAllowedOutgoingContentFilter( + list.GetType(), null, ActionBrowse.ActionLetter, userService, entityService, - Mock.Of() ); + Mock.Of()); - var path = ""; + var path = string.Empty; for (var i = 0; i < 10; i++) { if (i > 0 && path.EndsWith(",") == false) { path += ","; } + path += i.ToInvariantString(); list.Add(new ContentItemBasic { Id = i, Name = "Test" + i, ParentId = i, Path = path }); } @@ -107,7 +114,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters att.FilterBasedOnStartNode(list, user); Assert.AreEqual(5, list.Count); - } [Test] @@ -116,30 +122,33 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters var list = new List(); for (var i = 0; i < 10; i++) { - list.Add(new ContentItemBasic{Id = i, Name = "Test" + i, ParentId = -1}); + list.Add(new ContentItemBasic { Id = i, Name = "Test" + i, ParentId = -1 }); } + var ids = list.Select(x => (int)x.Id).ToArray(); - var user = CreateUser(id: 9, startContentId: 0); + IUser user = CreateUser(id: 9, startContentId: 0); var userServiceMock = new Mock(); - //we're only assigning 3 nodes browse permissions so that is what we expect as a result + + // We're only assigning 3 nodes browse permissions so that is what we expect as a result var permissions = new EntityPermissionCollection { - new EntityPermission(9876, 1, new string[]{ ActionBrowse.ActionLetter.ToString() }), - new EntityPermission(9876, 2, new string[]{ ActionBrowse.ActionLetter.ToString() }), - new EntityPermission(9876, 3, new string[]{ ActionBrowse.ActionLetter.ToString() }), - new EntityPermission(9876, 4, new string[]{ ActionUpdate.ActionLetter.ToString() }) + new EntityPermission(9876, 1, new string[] { ActionBrowse.ActionLetter.ToString() }), + new EntityPermission(9876, 2, new string[] { ActionBrowse.ActionLetter.ToString() }), + new EntityPermission(9876, 3, new string[] { ActionBrowse.ActionLetter.ToString() }), + new EntityPermission(9876, 4, new string[] { ActionUpdate.ActionLetter.ToString() }) }; userServiceMock.Setup(x => x.GetPermissions(user, ids)).Returns(permissions); - var userService = userServiceMock.Object; + IUserService userService = userServiceMock.Object; - var att = new FilterAllowedOutgoingContentFilter(list.GetType(), + var att = new FilterAllowedOutgoingContentFilter( + list.GetType(), null, ActionBrowse.ActionLetter, userService, Mock.Of(), - Mock.Of() ); + Mock.Of()); att.FilterBasedOnPermissions(list, user); Assert.AreEqual(3, list.Count); @@ -148,13 +157,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters Assert.AreEqual(3, list.ElementAt(2).Id); } - private IUser CreateUser(int id = 0, int? startContentId = null) - { - return new UserBuilder() + private IUser CreateUser(int id = 0, int? startContentId = null) => + new UserBuilder() .WithId(id) .WithStartContentIds(startContentId.HasValue ? new[] { startContentId.Value } : new int[0]) .Build(); - } private class MyTestClass { diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/OnlyLocalRequestsAttributeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/OnlyLocalRequestsAttributeTests.cs index 7d1fbdddf1..f616216974 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/OnlyLocalRequestsAttributeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/OnlyLocalRequestsAttributeTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Net; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -18,7 +21,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Does_Not_Set_Result_When_No_Remote_Address() { // Arrange - var context = CreateContext(); + ActionExecutingContext context = CreateContext(); var attribute = new OnlyLocalRequestsAttribute(); // Act @@ -32,7 +35,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Does_Not_Set_Result_When_Remote_Address_Is_Null_Ip_Address() { // Arrange - var context = CreateContext(remoteIpAddress: "::1"); + ActionExecutingContext context = CreateContext(remoteIpAddress: "::1"); var attribute = new OnlyLocalRequestsAttribute(); // Act @@ -46,7 +49,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Does_Not_Set_Result_When_Remote_Address_Matches_Local_Address() { // Arrange - var context = CreateContext(remoteIpAddress: "100.1.2.3", localIpAddress: "100.1.2.3"); + ActionExecutingContext context = CreateContext(remoteIpAddress: "100.1.2.3", localIpAddress: "100.1.2.3"); var attribute = new OnlyLocalRequestsAttribute(); // Act @@ -60,7 +63,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Returns_Not_Found_When_Remote_Address_Does_Not_Match_Local_Address() { // Arrange - var context = CreateContext(remoteIpAddress: "100.1.2.3", localIpAddress: "100.1.2.2"); + ActionExecutingContext context = CreateContext(remoteIpAddress: "100.1.2.3", localIpAddress: "100.1.2.2"); var attribute = new OnlyLocalRequestsAttribute(); // Act @@ -75,7 +78,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Does_Not_Set_Result_When_Remote_Address_Matches_LoopBack_Address() { // Arrange - var context = CreateContext(remoteIpAddress: "127.0.0.1", localIpAddress: "::1"); + ActionExecutingContext context = CreateContext(remoteIpAddress: "127.0.0.1", localIpAddress: "::1"); var attribute = new OnlyLocalRequestsAttribute(); // Act @@ -89,7 +92,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Returns_Not_Found_When_Remote_Address_Does_Not_Match_LoopBack_Address() { // Arrange - var context = CreateContext(remoteIpAddress: "100.1.2.3", localIpAddress: "::1"); + ActionExecutingContext context = CreateContext(remoteIpAddress: "100.1.2.3", localIpAddress: "::1"); var attribute = new OnlyLocalRequestsAttribute(); // Act diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/ValidationFilterAttributeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/ValidationFilterAttributeTests.cs index 51521c48fa..a14084c923 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/ValidationFilterAttributeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/ValidationFilterAttributeTests.cs @@ -1,12 +1,12 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Collections.Generic; -using System.Net; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using Moq; using NUnit.Framework; @@ -21,7 +21,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Does_Not_Set_Result_When_No_Errors_In_Model_State() { // Arrange - var context = CreateContext(); + ActionExecutingContext context = CreateContext(); var attribute = new ValidationFilterAttribute(); // Act @@ -35,7 +35,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters public void Returns_Bad_Request_When_Errors_In_Model_State() { // Arrange - var context = CreateContext(withError: true); + ActionExecutingContext context = CreateContext(withError: true); var attribute = new ValidationFilterAttribute(); // Act diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Security/BackOfficeAntiforgeryTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Security/BackOfficeAntiforgeryTests.cs index 7899ef39c2..568318006e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Security/BackOfficeAntiforgeryTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Security/BackOfficeAntiforgeryTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Linq; using System.Security.Claims; @@ -43,12 +46,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Security var container = new ServiceCollection(); container.AddLogging(); container.AddAntiforgery(); - var services = container.BuildServiceProvider(); + ServiceProvider services = container.BuildServiceProvider(); - var antiforgery = services.GetRequiredService(); - var options = services.GetRequiredService>(); + IAntiforgery antiforgery = services.GetRequiredService(); + IOptions options = services.GetRequiredService>(); - var httpContext = GetHttpContext(); + HttpContext httpContext = GetHttpContext(); var backofficeAntiforgery = new BackOfficeAntiforgery(antiforgery, options); backofficeAntiforgery.GetTokens(httpContext, out var cookieToken, out var headerToken); @@ -58,7 +61,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Security // the same context cannot validate since it's already created tokens httpContext = GetHttpContext(); - var result = await backofficeAntiforgery.ValidateRequestAsync(httpContext); + Attempt result = await backofficeAntiforgery.ValidateRequestAsync(httpContext); Assert.IsFalse(result.Success); // missing token diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Security/BackOfficeCookieManagerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Security/BackOfficeCookieManagerTests.cs index 80432cdce2..b677f11f2c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Security/BackOfficeCookieManagerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Security/BackOfficeCookieManagerTests.cs @@ -1,10 +1,10 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Routing; using Moq; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Cache; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Extensions; @@ -22,7 +22,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Backoffice.Security { var globalSettings = new GlobalSettings(); - var runtime = Mock.Of(x => x.Level == RuntimeLevel.Install); + IRuntimeState runtime = Mock.Of(x => x.Level == RuntimeLevel.Install); var mgr = new BackOfficeCookieManager( Mock.Of(), runtime, @@ -39,7 +39,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Backoffice.Security { var globalSettings = new GlobalSettings(); - var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); + IRuntimeState runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); var mgr = new BackOfficeCookieManager( Mock.Of(), runtime, @@ -56,7 +56,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Backoffice.Security { var globalSettings = new GlobalSettings(); - var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); + IRuntimeState runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); GenerateAuthPaths(out var remainingTimeoutSecondsPath, out var isAuthPath); @@ -73,13 +73,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Backoffice.Security Assert.IsTrue(result); } - [Test] public void ShouldAuthenticateRequest_Not_Back_Office() { var globalSettings = new GlobalSettings(); - var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); + IRuntimeState runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); var mgr = new BackOfficeCookieManager( Mock.Of(), @@ -104,7 +103,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Backoffice.Security // this is on the same controller but is considered a back office request var aPath = isAuthPath = $"/umbraco/{Constants.Web.Mvc.BackOfficePathSegment}/{Constants.Web.Mvc.BackOfficeApiArea}/{controllerName}/{nameof(AuthenticationController.IsAuthenticated)}".ToLower(); - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/ContentModelSerializationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/ContentModelSerializationTests.cs index eb8b2f8a23..79a971d9f4 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/ContentModelSerializationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/ContentModelSerializationTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -14,7 +17,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.AngularIntegration [Test] public void Content_Display_To_Json() { - //create 3 tabs with 3 properties each + // create 3 tabs with 3 properties each var tabs = new List>(); for (var tabIndex = 0; tabIndex < 3; tabIndex++) { @@ -33,6 +36,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.AngularIntegration HideLabel = false }); } + tabs.Add(new Tab() { Alias = "Tab" + tabIndex, @@ -60,7 +64,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.AngularIntegration Assert.AreEqual("1234", jObject["id"].ToString()); Assert.AreEqual("Test", jObject["variants"][0]["name"].ToString()); - var jsonTabs = jObject["variants"][0]["tabs"]; + + JToken jsonTabs = jObject["variants"][0]["tabs"]; Assert.AreEqual(3, jsonTabs.Count()); for (var tab = 0; tab < jsonTabs.Count(); tab++) { @@ -79,6 +84,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.AngularIntegration } } } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/JsInitializationTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/JsInitializationTests.cs index f082ba5d76..c29f5f16b7 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/JsInitializationTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/JsInitializationTests.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core; using Umbraco.Web.WebAssets; @@ -7,13 +10,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.AngularIntegration [TestFixture] public class JsInitializationTests { - [Test] public void Parse_Main() { var result = BackOfficeJavaScriptInitializer.WriteScript("[World]", "Hello", "Blah"); - Assert.AreEqual(@"LazyLoad.js([World], function () { + Assert.AreEqual( + @"LazyLoad.js([World], function () { //we need to set the legacy UmbClientMgr path if ((typeof UmbClientMgr) !== ""undefined"") { UmbClientMgr.setUmbracoPath('Hello'); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/ServerVariablesParserTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/ServerVariablesParserTests.cs index 0663c423d8..fd9f28946f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/ServerVariablesParserTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/AngularIntegration/ServerVariablesParserTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using NUnit.Framework; using Umbraco.Core; using Umbraco.Web.WebAssets; @@ -11,12 +14,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.AngularIntegration [Test] public void Parse() { - var d = new Dictionary(); - d.Add("test1", "Test 1"); - d.Add("test2", "Test 2"); - d.Add("test3", "Test 3"); - d.Add("test4", "Test 4"); - d.Add("test5", "Test 5"); + var d = new Dictionary + { + { "test1", "Test 1" }, + { "test2", "Test 2" }, + { "test3", "Test 3" }, + { "test4", "Test 4" }, + { "test5", "Test 5" } + }; var output = ServerVariablesParser.Parse(d).StripWhitespace(); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Extensions/HtmlHelperExtensionMethodsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Extensions/HtmlHelperExtensionMethodsTests.cs index abb44a5dfb..19433769fa 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Extensions/HtmlHelperExtensionMethodsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Extensions/HtmlHelperExtensionMethodsTests.cs @@ -1,4 +1,7 @@ -using System.Text.Encodings.Web; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Text.Encodings.Web; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures; @@ -10,7 +13,6 @@ using Umbraco.Extensions; namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Filters { - [TestFixture] public class HtmlHelperExtensionMethodsTests { @@ -18,16 +20,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Filters private const string SampleWithBoldAndAnchorElements = "Hello world, this is some text with a link"; [SetUp] - public virtual void Initialize() - { - //create an empty htmlHelper - _htmlHelper = new HtmlHelper(Mock.Of(), + public virtual void Initialize() => + + // Create an empty HtmlHelper. + _htmlHelper = new HtmlHelper( + Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new HtmlTestEncoder(), UrlEncoder.Default); - } private HtmlHelper _htmlHelper; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/FileNameTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/FileNameTests.cs index bee0b8bf15..5fc5987354 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/FileNameTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/FileNameTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Collections.Generic; using System.IO; using System.Linq; @@ -8,7 +11,6 @@ using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; -using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Tests.UnitTests.AutoFixture; @@ -48,7 +50,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common var viewResult = await sut.Index() as ViewResult; var fileName = GetViewName(viewResult, Path.DirectorySeparatorChar.ToString()); - var views = GetUiFiles(new[] { "umbraco", "UmbracoInstall" }); + IEnumerable views = GetUiFiles(new[] { "umbraco", "UmbracoInstall" }); Assert.True(views.Contains(fileName), $"Expected {fileName} to exist, but it didn't"); } @@ -63,7 +65,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common var viewResult = sut.Index() as ViewResult; var fileName = GetViewName(viewResult); - var views = GetUiFiles(new[] { "umbraco", "UmbracoBackOffice" }); + IEnumerable views = GetUiFiles(new[] { "umbraco", "UmbracoBackOffice" }); Assert.True(views.Contains(fileName), $"Expected {fileName} to exist, but it didn't"); } @@ -80,24 +82,24 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common Mock.Get(hostingEnvironment).Setup(x => x.ToAbsolute("/")).Returns("http://localhost/"); Mock.Get(hostingEnvironment).SetupGet(x => x.ApplicationVirtualPath).Returns("/"); - sut.TempData = tempDataDictionary; var viewResult = await sut.Default() as ViewResult; var fileName = GetViewName(viewResult); - var views = GetUiFiles(new[] { "umbraco", "UmbracoBackOffice" }); + IEnumerable views = GetUiFiles(new[] { "umbraco", "UmbracoBackOffice" }); Assert.True(views.Contains(fileName), $"Expected {fileName} to exist, but it didn't"); } - [Test] public void LanguageFilesAreLowercase() { - var files = GetUiFiles(new[] { "umbraco", "config", "lang" }); + IEnumerable files = GetUiFiles(new[] { "umbraco", "config", "lang" }); foreach (var fileName in files) { - Assert.AreEqual(fileName.ToLower(), fileName, + Assert.AreEqual( + fileName.ToLower(), + fileName, $"Language files must be all lowercase but {fileName} is not lowercase."); } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Filters/ValidateUmbracoFormRouteStringFilterTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Filters/ValidateUmbracoFormRouteStringFilterTests.cs index 3ed4a28b06..03bab2e02b 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Filters/ValidateUmbracoFormRouteStringFilterTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Filters/ValidateUmbracoFormRouteStringFilterTests.cs @@ -1,4 +1,7 @@ -using Microsoft.AspNetCore.DataProtection; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.AspNetCore.DataProtection; using NUnit.Framework; using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Common.Filters; @@ -36,6 +39,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Filters Assert.DoesNotThrow(() => filter.ValidateRouteString(validUfprt, ControllerName, ControllerAction, Area)); Assert.DoesNotThrow(() => filter.ValidateRouteString(validUfprt, ControllerName.ToLowerInvariant(), ControllerAction.ToLowerInvariant(), Area.ToLowerInvariant())); } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Formatters/IgnoreRequiredAttributesResolverUnitTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Formatters/IgnoreRequiredAttributesResolverUnitTests.cs index 94133c9e27..ab087b325a 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Formatters/IgnoreRequiredAttributesResolverUnitTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Formatters/IgnoreRequiredAttributesResolverUnitTests.cs @@ -1,4 +1,6 @@ -using System.ComponentModel.DataAnnotations; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Runtime.Serialization; using Newtonsoft.Json; using NUnit.Framework; @@ -9,7 +11,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Formatters [TestFixture] public class IgnoreRequiredAttributesResolverUnitTests { - [Test] public void Test() { @@ -17,14 +18,16 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Formatters Assert.Multiple(() => { - //Ensure the deserialization throws if using default settings + // Ensure the deserialization throws if using default settings Assert.Throws(() => JsonConvert.DeserializeObject(emptyJsonObject)); - var actual = JsonConvert.DeserializeObject(emptyJsonObject,new JsonSerializerSettings - { - ContractResolver = new IgnoreRequiredAttributesResolver() - }); + ObjectWithRequiredProperty actual = JsonConvert.DeserializeObject( + emptyJsonObject, + new JsonSerializerSettings + { + ContractResolver = new IgnoreRequiredAttributesResolver() + }); Assert.IsNotNull(actual); Assert.IsNull(actual.Property); @@ -35,7 +38,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Formatters private class ObjectWithRequiredProperty { [DataMember(Name = "property", IsRequired = true)] - public string Property{ get; set; } + public string Property { get; set; } } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ImageCropperTest.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ImageCropperTest.cs index 417880f476..2ec4c40714 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ImageCropperTest.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ImageCropperTest.cs @@ -1,19 +1,21 @@ -using System.Globalization; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Globalization; +using System.Text; using Newtonsoft.Json; -using NUnit.Framework; using Newtonsoft.Json.Linq; +using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Media; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors.ValueConverters; -using Umbraco.Web.Models; -using System.Text; -using Umbraco.Core.Media; using Umbraco.Extensions; -using System.Collections.Generic; +using Umbraco.Web.Models; namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common { - [TestFixture] public class ImageCropperTest { @@ -25,9 +27,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common [Test] public void CanConvertImageCropperDataSetSrcToString() { - //cropperJson3 - has not crops - var cropperValue = CropperJson3.DeserializeImageCropperValue(); - var serialized = cropperValue.TryConvertTo(); + // cropperJson3 - has not crops + ImageCropperValue cropperValue = CropperJson3.DeserializeImageCropperValue(); + Attempt serialized = cropperValue.TryConvertTo(); Assert.IsTrue(serialized.Success); Assert.AreEqual("/media/1005/img_0672.jpg", serialized.Result); } @@ -35,9 +37,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common [Test] public void CanConvertImageCropperDataSetJObject() { - //cropperJson3 - has not crops - var cropperValue = CropperJson3.DeserializeImageCropperValue(); - var serialized = cropperValue.TryConvertTo(); + // cropperJson3 - has not crops + ImageCropperValue cropperValue = CropperJson3.DeserializeImageCropperValue(); + Attempt serialized = cropperValue.TryConvertTo(); Assert.IsTrue(serialized.Success); Assert.AreEqual(cropperValue, serialized.Result.ToObject()); } @@ -45,56 +47,56 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common [Test] public void CanConvertImageCropperDataSetJsonToString() { - var cropperValue = CropperJson1.DeserializeImageCropperValue(); - var serialized = cropperValue.TryConvertTo(); + ImageCropperValue cropperValue = CropperJson1.DeserializeImageCropperValue(); + Attempt serialized = cropperValue.TryConvertTo(); Assert.IsTrue(serialized.Success); Assert.IsTrue(serialized.Result.DetectIsJson()); - var obj = JsonConvert.DeserializeObject(CropperJson1, new JsonSerializerSettings {Culture = CultureInfo.InvariantCulture, FloatParseHandling = FloatParseHandling.Decimal}); + ImageCropperValue obj = JsonConvert.DeserializeObject(CropperJson1, new JsonSerializerSettings { Culture = CultureInfo.InvariantCulture, FloatParseHandling = FloatParseHandling.Decimal }); Assert.AreEqual(cropperValue, obj); } - // [TestCase(CropperJson1, CropperJson1, true)] - // [TestCase(CropperJson1, CropperJson2, false)] - // public void CanConvertImageCropperPropertyEditor(string val1, string val2, bool expected) - // { - // try - // { - // var container = TestHelper.GetRegister(); - // var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); - // - // composition.WithCollectionBuilder(); - // - // Current.Factory = composition.CreateFactory(); - // - // var logger = Mock.Of(); - // var scheme = Mock.Of(); - // var shortStringHelper = Mock.Of(); - // - // var mediaFileSystem = new MediaFileSystem(Mock.Of(), scheme, logger, shortStringHelper); - // - // var dataTypeService = new TestObjects.TestDataTypeService( - // new DataType(new ImageCropperPropertyEditor(Mock.Of(), mediaFileSystem, Mock.Of(), Mock.Of(), Mock.Of(), TestHelper.IOHelper, TestHelper.ShortStringHelper, Mock.Of())) { Id = 1 }); - // - // var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeService); - // - // var converter = new ImageCropperValueConverter(); - // var result = converter.ConvertSourceToIntermediate(null, factory.CreatePropertyType("test", 1), val1, false); // does not use type for conversion - // - // var resultShouldMatch = val2.DeserializeImageCropperValue(); - // if (expected) - // { - // Assert.AreEqual(resultShouldMatch, result); - // } - // else - // { - // Assert.AreNotEqual(resultShouldMatch, result); - // } - // } - // finally - // { - // Current.Reset(); - // } - // } + //// [TestCase(CropperJson1, CropperJson1, true)] + //// [TestCase(CropperJson1, CropperJson2, false)] + //// public void CanConvertImageCropperPropertyEditor(string val1, string val2, bool expected) + //// { + //// try + //// { + //// var container = TestHelper.GetRegister(); + //// var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + //// + //// composition.WithCollectionBuilder(); + //// + //// Current.Factory = composition.CreateFactory(); + //// + //// var logger = Mock.Of(); + //// var scheme = Mock.Of(); + //// var shortStringHelper = Mock.Of(); + //// + //// var mediaFileSystem = new MediaFileSystem(Mock.Of(), scheme, logger, shortStringHelper); + //// + //// var dataTypeService = new TestObjects.TestDataTypeService( + //// new DataType(new ImageCropperPropertyEditor(Mock.Of(), mediaFileSystem, Mock.Of(), Mock.Of(), Mock.Of(), TestHelper.IOHelper, TestHelper.ShortStringHelper, Mock.Of())) { Id = 1 }); + //// + //// var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeService); + //// + //// var converter = new ImageCropperValueConverter(); + //// var result = converter.ConvertSourceToIntermediate(null, factory.CreatePropertyType("test", 1), val1, false); // does not use type for conversion + //// + //// var resultShouldMatch = val2.DeserializeImageCropperValue(); + //// if (expected) + //// { + //// Assert.AreEqual(resultShouldMatch, result); + //// } + //// else + //// { + //// Assert.AreNotEqual(resultShouldMatch, result); + //// } + //// } + //// finally + //// { + //// Current.Reset(); + //// } + //// } [Test] public void GetCropUrl_CropAliasTest() @@ -150,7 +152,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common [Test] public void GetBaseCropUrlFromModelTest() { - var cropDataSet = CropperJson1.DeserializeImageCropperValue(); + ImageCropperValue cropDataSet = CropperJson1.DeserializeImageCropperValue(); var urlString = cropDataSet.GetCropUrl("thumb", new TestImageUrlGenerator()); Assert.AreEqual("?c=0.58729977382575338,0.055768992440203169,0,0.32457553600198386&w=100&h=100", urlString); } @@ -161,7 +163,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common [Test] public void GetCropUrl_CropAliasHeightRatioModeTest() { - var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, cropAlias: "Thumb", useCropDimensions: true, ratioMode:ImageCropRatioMode.Height); + var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, cropAlias: "Thumb", useCropDimensions: true, ratioMode: ImageCropRatioMode.Height); Assert.AreEqual(MediaPath + "?c=0.58729977382575338,0.055768992440203169,0,0.32457553600198386&hr=1&w=100", urlString); } @@ -171,7 +173,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common [Test] public void GetCropUrl_WidthHeightRatioModeTest() { - var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, ratioMode:ImageCropRatioMode.Height); + var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, ratioMode: ImageCropRatioMode.Height); Assert.AreEqual(MediaPath + "?f=0.80827067669172936x0.96&hr=0.5&w=300", urlString); } @@ -194,7 +196,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common var urlStringMin = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.Min); var urlStringBoxPad = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.BoxPad); var urlStringPad = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.Pad); - var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode:ImageCropMode.Max); + var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.Max); var urlStringStretch = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.Stretch); Assert.AreEqual(MediaPath + "?m=min&w=300&h=150", urlStringMin); @@ -222,7 +224,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common { const string cropperJson = "{\"focalPoint\": {\"left\": 0.5,\"top\": 0.5},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\":\"thumb\",\"width\": 100,\"height\": 100,\"coordinates\": {\"x1\": 0.58729977382575338,\"y1\": 0.055768992440203169,\"x2\": 0,\"y2\": 0.32457553600198386}}]}"; - var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: cropperJson, width: 300, height: 150, preferFocalPoint:true); + var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: cropperJson, width: 300, height: 150, preferFocalPoint: true); Assert.AreEqual(MediaPath + "?m=defaultcrop&w=300&h=150", urlString); } @@ -340,20 +342,62 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common else { imageProcessorUrl.Append("?m=" + options.ImageCropMode.ToString().ToLower()); - if (options.ImageCropAnchor != null)imageProcessorUrl.Append("&a=" + options.ImageCropAnchor.ToString().ToLower()); + if (options.ImageCropAnchor != null) + { + imageProcessorUrl.Append("&a=" + options.ImageCropAnchor.ToString().ToLower()); + } } var hasFormat = options.FurtherOptions != null && options.FurtherOptions.InvariantContains("&f="); - if (options.Quality != null && hasFormat == false) imageProcessorUrl.Append("&q=" + options.Quality); - if (options.HeightRatio != null) imageProcessorUrl.Append("&hr=" + options.HeightRatio.Value.ToString(CultureInfo.InvariantCulture)); - if (options.WidthRatio != null) imageProcessorUrl.Append("&wr=" + options.WidthRatio.Value.ToString(CultureInfo.InvariantCulture)); - if (options.Width != null) imageProcessorUrl.Append("&w=" + options.Width); - if (options.Height != null) imageProcessorUrl.Append("&h=" + options.Height); - if (options.UpScale == false) imageProcessorUrl.Append("&u=no"); - if (options.AnimationProcessMode != null) imageProcessorUrl.Append("&apm=" + options.AnimationProcessMode); - if (options.FurtherOptions != null) imageProcessorUrl.Append(options.FurtherOptions); - if (options.Quality != null && hasFormat) imageProcessorUrl.Append("&q=" + options.Quality); - if (options.CacheBusterValue != null) imageProcessorUrl.Append("&r=").Append(options.CacheBusterValue); + if (options.Quality != null && hasFormat == false) + { + imageProcessorUrl.Append("&q=" + options.Quality); + } + + if (options.HeightRatio != null) + { + imageProcessorUrl.Append("&hr=" + options.HeightRatio.Value.ToString(CultureInfo.InvariantCulture)); + } + + if (options.WidthRatio != null) + { + imageProcessorUrl.Append("&wr=" + options.WidthRatio.Value.ToString(CultureInfo.InvariantCulture)); + } + + if (options.Width != null) + { + imageProcessorUrl.Append("&w=" + options.Width); + } + + if (options.Height != null) + { + imageProcessorUrl.Append("&h=" + options.Height); + } + + if (options.UpScale == false) + { + imageProcessorUrl.Append("&u=no"); + } + + if (options.AnimationProcessMode != null) + { + imageProcessorUrl.Append("&apm=" + options.AnimationProcessMode); + } + + if (options.FurtherOptions != null) + { + imageProcessorUrl.Append(options.FurtherOptions); + } + + if (options.Quality != null && hasFormat) + { + imageProcessorUrl.Append("&q=" + options.Quality); + } + + if (options.CacheBusterValue != null) + { + imageProcessorUrl.Append("&r=").Append(options.CacheBusterValue); + } return imageProcessorUrl.ToString(); } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroParserTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroParserTests.cs index 80a25d7fc5..e8cfa0501f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroParserTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroParserTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using NUnit.Framework; using Umbraco.Web.Macros; @@ -11,155 +14,129 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Macros [Test] public void Format_RTE_Data_For_Editor_With_No_Macros() { - var content = @"

hello world

"; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); + string content = @"

hello world

"; + string result = MacroTagParser.FormatRichTextContentForPersistence(content); Assert.AreEqual(@"

hello world

", content); } [Test] public void Format_RTE_Data_For_Editor_With_Non_AlphaNumeric_Char_In_Alias() { - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); -// Assert.AreEqual(@"

asdfasdf

-//

asdfsadf

-//
-// -//Macro alias: Map
-//

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

Macro alias: My.Map.isCool eh[boy!]
-

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

asdfasdf

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Editor() { - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary(){{"test1", "value1"},{"test2", "value2"}}); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); -// Assert.AreEqual(@"

asdfasdf

-//

asdfsadf

-//
-// -//Macro alias: Map
-//

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); - - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

Macro alias: Map
-

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

asdfasdf

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Editor_Closing_Tag() { - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); -// Assert.AreEqual(@"

asdfasdf

-//

asdfsadf

-//
-// -//Macro alias: Map
-//

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

Macro alias: Map
-

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

asdfasdf

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Editor_With_Params() { - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); -// Assert.AreEqual(@"

asdfasdf

-//

asdfsadf

-//
-// -//Macro alias: Map
-//

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

Macro alias: Map
-

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

asdfasdf

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Editor_With_Params_When_MacroAlias_Not_First() { - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); -// Assert.AreEqual(@"

asdfasdf

-//

asdfsadf

-//
-// -//Macro alias: Map
-//

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

Macro alias: Map
-

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

asdfasdf

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Editor_With_Params_When_MacroAlias_Is_First() { - - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); - // Assert.AreEqual(@"

asdfasdf

- //

asdfsadf

- //
- // - //Macro alias: Map
- //

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

Macro alias: Map
-

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

asdfasdf

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Editor_With_Params_When_Multiple_Macros() { - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfsadf

@@ -167,24 +144,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Macros

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); - // Assert.AreEqual(@"

asdfasdf

- //

asdfsadf

- //
- // - //Macro alias: Map
- //

asdfsadf

- //
- // - //Macro alias: Map
- //

asdfsadf

- //
- // - //Macro alias: Map
- //

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); - - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

@@ -197,21 +160,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Macros
Macro alias: Map
-

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

asdfasdf

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Editor_With_Multiple_Macros() { - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

 

 

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary()); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary()); - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

Macro alias: Breadcrumb
@@ -220,13 +185,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Macros
Macro alias: login
-

 

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

 

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Persistence_Multiline_Parameters() { - var content = @" + string content = @"

asdfasdf

@@ -243,9 +209,10 @@ asdfsdf
"; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); + string result = MacroTagParser.FormatRichTextContentForPersistence(content); - Assert.AreEqual(@" + Assert.AreEqual( + @"

asdfasdf

asdfsdf
-".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Editor_With_Params_Closing_Tag() { - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); -// Assert.AreEqual(@"

asdfasdf

-//

asdfsadf

-//
-// -//Macro alias: Map
-//

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

Macro alias: Map
-

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

asdfasdf

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Editor_With_Params_Closing_Tag_And_Content() { - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2" } }); -// Assert.AreEqual(@"

asdfasdf

-//

asdfsadf

-//
-// -//Macro alias: Map
-//

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

Macro alias: Map
-

asdfasdf

".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +

asdfasdf

".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } - [Test] public void Format_RTE_Data_For_Editor_With_Multiline_Parameters() { - - var content = @"

asdfasdf

+ string content = @"

asdfasdf

asdfsadf

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2\r\ntest" } }); + string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary() { { "test1", "value1" }, { "test2", "value2\r\ntest" } }); - Assert.AreEqual(@"

asdfasdf

+ Assert.AreEqual( + @"

asdfasdf

asdfsadf

Macro alias: Map
-

asdfasdf

".NoCrLf(), result.NoCrLf()); +

asdfasdf

".NoCrLf(), + result.NoCrLf()); } [Test] public void Format_RTE_Data_For_Persistence() { -// var content = @" -// -//

asdfasdf

-//
-// -//asdfasdf -//asdfas -//asdfasdfasdf -//

asdfasdf

-//
-//asdfdasf -//
-//asdfsdf -//
-// -//"; - var content = @" + string content = @"

asdfasdf

@@ -361,9 +305,10 @@ asdfsdf
"; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); + string result = MacroTagParser.FormatRichTextContentForPersistence(content); - Assert.AreEqual(@" + Assert.AreEqual( + @"

asdfasdf

@@ -372,13 +317,14 @@ asdfsdf asdfsdf -".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Persistence_No_Class() { - var content = @" + string content = @"

asdfasdf

@@ -394,9 +340,10 @@ asdfsdf
"; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); + string result = MacroTagParser.FormatRichTextContentForPersistence(content); - Assert.AreEqual(@" + Assert.AreEqual( + @"

asdfasdf

@@ -405,21 +352,14 @@ asdfsdf asdfsdf -".Replace(Environment.NewLine, string.Empty), result.Replace(Environment.NewLine, string.Empty)); +".Replace(Environment.NewLine, string.Empty), + result.Replace(Environment.NewLine, string.Empty)); } [Test] public void Format_RTE_Data_For_Persistence_Custom_Single_Entry() { -// var content = @"
-//
-//
-//

null

-//
-//
1089
-//
-//
"; - var content = @"
+ string content = @"

null

@@ -427,10 +367,9 @@ asdfsdf
1089
"; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); + string result = MacroTagParser.FormatRichTextContentForPersistence(content); Assert.AreEqual(@"", result); } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroTests.cs index 9bb4e6e54a..d789156eb5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroTests.cs @@ -1,4 +1,7 @@ -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Core.Cache; using Umbraco.Web.Macros; @@ -7,11 +10,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Macros [TestFixture] public class MacroTests { - [SetUp] public void Setup() { - //we DO want cache enabled for these tests + // We DO want cache enabled for these tests var cacheHelper = new AppCaches( new ObjectCacheAppCache(), NoAppCache.Instance, @@ -28,23 +30,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Macros }; var filename = MacroRenderer.GetMacroFileName(model); if (expectedNonNull) + { Assert.IsNotNull(filename); + } else + { Assert.IsNull(filename); - } - - //[TestCase(-5, true)] //the cache DateTime will be older than the file date - //[TestCase(5, false)] //the cache DateTime will be newer than the file date - public void Macro_Needs_Removing_Based_On_Macro_File(int minutesToNow, bool expectedNull) - { - // macro has been refactored, and macro.GetMacroContentFromCache() will - // take care of the macro file, if any. It requires a web environment, - // so we cannot really test this anymore. - } - - public void Get_Macro_Cache_Identifier() - { - //var asdf = macro.GetCacheIdentifier() + } } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/ContentModelBinderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/ContentModelBinderTests.cs index b414e49e95..a27f259de4 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/ContentModelBinderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/ContentModelBinderTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; @@ -20,7 +23,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public void Does_Not_Bind_Model_When_UmbracoDataToken_Not_In_Route_Data() { // Arrange - var bindingContext = CreateBindingContext(typeof(ContentModel), withUmbracoDataToken: false); + ModelBindingContext bindingContext = CreateBindingContext(typeof(ContentModel), withUmbracoDataToken: false); var binder = new ContentModelBinder(); // Act @@ -34,7 +37,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public void Does_Not_Bind_Model_When_Source_Not_Of_Expected_Type() { // Arrange - var bindingContext = CreateBindingContext(typeof(ContentModel), source: new NonContentModel()); + ModelBindingContext bindingContext = CreateBindingContext(typeof(ContentModel), source: new NonContentModel()); var binder = new ContentModelBinder(); // Act @@ -49,7 +52,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders { // Arrange var content = new ContentModel(CreatePublishedContent()); - var bindingContext = CreateBindingContext(typeof(ContentModel), source: content); + ModelBindingContext bindingContext = CreateBindingContext(typeof(ContentModel), source: content); var binder = new ContentModelBinder(); // Act @@ -63,7 +66,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public void Binds_From_IPublishedContent_To_Content_Model() { // Arrange - var bindingContext = CreateBindingContext(typeof(ContentModel), source: CreatePublishedContent()); + ModelBindingContext bindingContext = CreateBindingContext(typeof(ContentModel), source: CreatePublishedContent()); var binder = new ContentModelBinder(); // Act @@ -77,7 +80,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public void Binds_From_IPublishedContent_To_Content_Model_Of_T() { // Arrange - var bindingContext = CreateBindingContext(typeof(ContentModel), source: new ContentModel(new ContentType2(CreatePublishedContent()))); + ModelBindingContext bindingContext = CreateBindingContext(typeof(ContentModel), source: new ContentModel(new ContentType2(CreatePublishedContent()))); var binder = new ContentModelBinder(); // Act @@ -92,7 +95,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders var httpContext = new DefaultHttpContext(); var routeData = new RouteData(); if (withUmbracoDataToken) + { routeData.DataTokens.Add(Constants.Web.UmbracoDataToken, source); + } var actionContext = new ActionContext(httpContext, routeData, new ActionDescriptor()); var metadataProvider = new EmptyModelMetadataProvider(); @@ -111,19 +116,22 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders { } - private IPublishedContent CreatePublishedContent() - { - return new ContentType2(new Mock().Object); - } + private IPublishedContent CreatePublishedContent() => new ContentType2(new Mock().Object); public class ContentType1 : PublishedContentWrapped { - public ContentType1(IPublishedContent content) : base(content) { } + public ContentType1(IPublishedContent content) + : base(content) + { + } } public class ContentType2 : ContentType1 { - public ContentType2(IPublishedContent content) : base(content) { } + public ContentType2(IPublishedContent content) + : base(content) + { + } } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/HttpQueryStringModelBinderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/HttpQueryStringModelBinderTests.cs index 6dd3b024b3..6e06adf727 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/HttpQueryStringModelBinderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/HttpQueryStringModelBinderTests.cs @@ -1,4 +1,8 @@ -using Microsoft.AspNetCore.Http; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ModelBinding; @@ -16,7 +20,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public void Binds_Query_To_FormCollection() { // Arrange - var bindingContext = CreateBindingContext("?foo=bar&baz=buzz"); + ModelBindingContext bindingContext = CreateBindingContext("?foo=bar&baz=buzz"); var binder = new HttpQueryStringModelBinder(); // Act @@ -35,7 +39,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public void Sets_Culture_Form_Value_From_Query_If_Provided() { // Arrange - var bindingContext = CreateBindingContext("?foo=bar&baz=buzz&culture=en-gb"); + ModelBindingContext bindingContext = CreateBindingContext("?foo=bar&baz=buzz&culture=en-gb"); var binder = new HttpQueryStringModelBinder(); // Act @@ -53,7 +57,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public void Sets_Culture_Form_Value_From_Header_If_Not_Provided_In_Query() { // Arrange - var bindingContext = CreateBindingContext("?foo=bar&baz=buzz"); + ModelBindingContext bindingContext = CreateBindingContext("?foo=bar&baz=buzz"); var binder = new HttpQueryStringModelBinder(); // Act @@ -77,7 +81,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders var metadataProvider = new EmptyModelMetadataProvider(); var routeValueDictionary = new RouteValueDictionary(); var valueProvider = new RouteValueProvider(BindingSource.Path, routeValueDictionary); - var modelType = typeof(FormCollection); + Type modelType = typeof(FormCollection); return new DefaultModelBindingContext { ActionContext = actionContext, diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/RenderModelBinderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/RenderModelBinderTests.cs index 501c10551d..6bd2e3f315 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/RenderModelBinderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/ModelBinders/RenderModelBinderTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; @@ -17,11 +20,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public class RenderModelBinderTests { private ContentModelBinder _contentModelBinder; + [SetUp] - public void SetUp() - { - _contentModelBinder = new ContentModelBinder(); - } + public void SetUp() => _contentModelBinder = new ContentModelBinder(); [Test] [TestCase(typeof(IPublishedContent), false)] @@ -37,7 +38,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders var contextMock = new Mock(); contextMock.Setup(x => x.Metadata).Returns(new EmptyModelMetadataProvider().GetMetadataForType(testType)); - var found = binderProvider.GetBinder(contextMock.Object); + IModelBinder found = binderProvider.GetBinder(contextMock.Object); if (expectNull) { Assert.IsNull(found); @@ -86,8 +87,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders var bindingContext = new DefaultModelBindingContext(); _contentModelBinder.BindModelAsync(bindingContext, content, typeof(ContentModel)); - var bound = (IContentModel) bindingContext.Result.Model; + var bound = (IContentModel)bindingContext.Result.Model; Assert.AreSame(content, bound.Content); } @@ -98,8 +99,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders var bindingContext = new DefaultModelBindingContext(); _contentModelBinder.BindModelAsync(bindingContext, content, typeof(ContentModel)); - var bound = (IContentModel) bindingContext.Result.Model; + var bound = (IContentModel)bindingContext.Result.Model; Assert.AreSame(content, bound.Content); } @@ -107,7 +108,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public void No_DataToken_Returns_Null() { var content = new MyContent(Mock.Of()); - var bindingContext = CreateBindingContext(typeof(ContentModel), false, content); + ModelBindingContext bindingContext = CreateBindingContext(typeof(ContentModel), false, content); _contentModelBinder.BindModelAsync(bindingContext); @@ -117,7 +118,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders [Test] public void Invalid_DataToken_Model_Type_Returns_Null() { - var bindingContext = CreateBindingContext(typeof(IPublishedContent), source: "Hello"); + ModelBindingContext bindingContext = CreateBindingContext(typeof(IPublishedContent), source: "Hello"); _contentModelBinder.BindModelAsync(bindingContext); Assert.IsNull(bindingContext.Result.Model); } @@ -126,7 +127,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders public void IPublishedContent_DataToken_Model_Type_Uses_DefaultImplementation() { var content = new MyContent(Mock.Of()); - var bindingContext = CreateBindingContext(typeof(MyContent), source: content); + ModelBindingContext bindingContext = CreateBindingContext(typeof(MyContent), source: content); _contentModelBinder.BindModelAsync(bindingContext); @@ -138,7 +139,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders var httpContext = new DefaultHttpContext(); var routeData = new RouteData(); if (withUmbracoDataToken) + { routeData.DataTokens.Add(Constants.Web.UmbracoDataToken, source); + } var actionContext = new ActionContext(httpContext, routeData, new ActionDescriptor()); var metadataProvider = new EmptyModelMetadataProvider(); @@ -157,17 +160,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.ModelBinders { public MyCustomContentModel(IPublishedContent content) : base(content) - { } + { + } } public class MyOtherContent { - } public class MyContent : PublishedContentWrapped { - public MyContent(IPublishedContent content) : base(content) + public MyContent(IPublishedContent content) + : base(content) { } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Mvc/HtmlStringUtilitiesTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Mvc/HtmlStringUtilitiesTests.cs index 4b1675b7f0..b106d24ed6 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Mvc/HtmlStringUtilitiesTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Mvc/HtmlStringUtilitiesTests.cs @@ -1,5 +1,7 @@ -using NUnit.Framework; -using Umbraco.Web; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using NUnit.Framework; using Umbraco.Web.Common.Mvc; namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Mvc @@ -10,16 +12,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Mvc private HtmlStringUtilities _htmlStringUtilities; [SetUp] - public virtual void Initialize() - { - - _htmlStringUtilities = new HtmlStringUtilities(); - } + public virtual void Initialize() => _htmlStringUtilities = new HtmlStringUtilities(); [Test] public void TruncateWithElipsis() { - var output = _htmlStringUtilities.Truncate("hello world", 5, true, false).ToString(); + string output = _htmlStringUtilities.Truncate("hello world", 5, true, false).ToString(); var expected = "hello…"; Assert.AreEqual(expected, output); } @@ -27,7 +25,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Mvc [Test] public void TruncateWithoutElipsis() { - var output = _htmlStringUtilities.Truncate("hello world", 5, false, false).ToString(); + string output = _htmlStringUtilities.Truncate("hello world", 5, false, false).ToString(); var expected = "hello"; Assert.AreEqual(expected, output); } @@ -35,7 +33,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Mvc [Test] public void TruncateShorterWordThanHellip() { - //http://issues.umbraco.org/issue/U4-10478 + // http://issues.umbraco.org/issue/U4-10478 var output = _htmlStringUtilities.Truncate("hi", 5, true, false).ToString(); var expected = "hi"; Assert.AreEqual(expected, output); @@ -48,7 +46,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Mvc var expected = "hello…"; Assert.AreEqual(expected, output); } - - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/BackOfficeAreaRoutesTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/BackOfficeAreaRoutesTests.cs index 40b7030ba8..e221e88dd1 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/BackOfficeAreaRoutesTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/BackOfficeAreaRoutesTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Options; @@ -17,7 +20,6 @@ using Constants = Umbraco.Core.Constants; namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing { - [TestFixture] public class BackOfficeAreaRoutesTests { @@ -27,7 +29,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing [TestCase(RuntimeLevel.Boot)] public void RuntimeState_No_Routes(RuntimeLevel level) { - var routes = GetBackOfficeAreaRoutes(level); + BackOfficeAreaRoutes routes = GetBackOfficeAreaRoutes(level); var endpoints = new TestRouteBuilder(); routes.CreateRoutes(endpoints); @@ -37,12 +39,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing [Test] public void RuntimeState_Upgrade() { - var routes = GetBackOfficeAreaRoutes(RuntimeLevel.Upgrade); + BackOfficeAreaRoutes routes = GetBackOfficeAreaRoutes(RuntimeLevel.Upgrade); var endpoints = new TestRouteBuilder(); routes.CreateRoutes(endpoints); Assert.AreEqual(1, endpoints.DataSources.Count); - var route = endpoints.DataSources.First(); + EndpointDataSource route = endpoints.DataSources.First(); Assert.AreEqual(2, route.Endpoints.Count); AssertMinimalBackOfficeRoutes(route); } @@ -50,18 +52,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing [Test] public void RuntimeState_Run() { - var routes = GetBackOfficeAreaRoutes(RuntimeLevel.Run); + BackOfficeAreaRoutes routes = GetBackOfficeAreaRoutes(RuntimeLevel.Run); var endpoints = new TestRouteBuilder(); routes.CreateRoutes(endpoints); Assert.AreEqual(1, endpoints.DataSources.Count); - var route = endpoints.DataSources.First(); + EndpointDataSource route = endpoints.DataSources.First(); Assert.AreEqual(3, route.Endpoints.Count); AssertMinimalBackOfficeRoutes(route); var endpoint4 = (RouteEndpoint)route.Endpoints[2]; - var apiControllerName = ControllerExtensions.GetControllerName(); + string apiControllerName = ControllerExtensions.GetControllerName(); Assert.AreEqual($"umbraco/backoffice/api/{apiControllerName.ToLowerInvariant()}/{{action}}/{{id?}}", endpoint4.RoutePattern.RawText); Assert.IsFalse(endpoint4.RoutePattern.Defaults.ContainsKey("area")); Assert.IsFalse(endpoint4.RoutePattern.Defaults.ContainsKey("action")); @@ -78,7 +80,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing Assert.AreEqual(endpoint1.RoutePattern.Defaults["area"], typeof(BackOfficeController).GetCustomAttribute(false).RouteValue); var endpoint2 = (RouteEndpoint)route.Endpoints[1]; - var controllerName = ControllerExtensions.GetControllerName(); + string controllerName = ControllerExtensions.GetControllerName(); Assert.AreEqual($"umbraco/backoffice/{Constants.Web.Mvc.BackOfficeApiArea.ToLowerInvariant()}/{controllerName.ToLowerInvariant()}/{{action}}/{{id?}}", endpoint2.RoutePattern.RawText); Assert.AreEqual(Constants.Web.Mvc.BackOfficeApiArea, endpoint2.RoutePattern.Defaults["area"]); Assert.IsFalse(endpoint2.RoutePattern.Defaults.ContainsKey("action")); @@ -101,7 +103,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing [IsBackOffice] private class Testing1Controller : UmbracoApiController { - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/EndpointRouteBuilderExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/EndpointRouteBuilderExtensionsTests.cs index a5b7c6dae3..f5b491a8af 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/EndpointRouteBuilderExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/EndpointRouteBuilderExtensionsTests.cs @@ -1,10 +1,10 @@ -using Microsoft.AspNetCore.Http.Features; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using NUnit.Framework; -using System; -using System.Linq; -using System.Text; using Umbraco.Core; using Umbraco.Extensions; using Umbraco.Web.Common.Routing; @@ -12,7 +12,6 @@ using Constants = Umbraco.Core.Constants; namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing { - [TestFixture] public class EndpointRouteBuilderExtensionsTests { @@ -37,31 +36,45 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing var endpoints = new TestRouteBuilder(); endpoints.MapUmbracoRoute(umbracoPath, area, prefix, defaultAction, includeControllerName); - var route = endpoints.DataSources.First(); + EndpointDataSource route = endpoints.DataSources.First(); var endpoint = (RouteEndpoint)route.Endpoints[0]; - var controllerName = ControllerExtensions.GetControllerName(); - var controllerNamePattern = controllerName.ToLowerInvariant(); + string controllerName = ControllerExtensions.GetControllerName(); + string controllerNamePattern = controllerName.ToLowerInvariant(); if (includeControllerName) { if (prefix.IsNullOrWhiteSpace()) + { Assert.AreEqual($"{umbracoPath}/{controllerNamePattern}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText); + } else + { Assert.AreEqual($"{umbracoPath}/{prefix}/{controllerNamePattern}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText); + } } else { if (prefix.IsNullOrWhiteSpace()) + { Assert.AreEqual($"{umbracoPath}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText); + } else + { Assert.AreEqual($"{umbracoPath}/{prefix}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText); + } } if (!area.IsNullOrWhiteSpace()) + { Assert.AreEqual(area, endpoint.RoutePattern.Defaults["area"]); + } + if (!defaultAction.IsNullOrWhiteSpace()) - Assert.AreEqual(defaultAction, endpoint.RoutePattern.Defaults["action"]); + { + Assert.AreEqual(defaultAction, endpoint.RoutePattern.Defaults["action"]); + } + Assert.AreEqual(controllerName, endpoint.RoutePattern.Defaults["controller"]); } @@ -78,38 +91,51 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing var endpoints = new TestRouteBuilder(); endpoints.MapUmbracoApiRoute(umbracoPath, area, isBackOffice, defaultAction); - var route = endpoints.DataSources.First(); + EndpointDataSource route = endpoints.DataSources.First(); var endpoint = (RouteEndpoint)route.Endpoints[0]; - var controllerName = ControllerExtensions.GetControllerName(); - var controllerNamePattern = controllerName.ToLowerInvariant(); - var areaPattern = area?.ToLowerInvariant(); + string controllerName = ControllerExtensions.GetControllerName(); + string controllerNamePattern = controllerName.ToLowerInvariant(); + string areaPattern = area?.ToLowerInvariant(); if (isBackOffice) { if (area.IsNullOrWhiteSpace()) + { Assert.AreEqual($"{umbracoPath}/backoffice/api/{controllerNamePattern}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText); + } else + { Assert.AreEqual($"{umbracoPath}/backoffice/{areaPattern}/{controllerNamePattern}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText); + } } else { if (area.IsNullOrWhiteSpace()) + { Assert.AreEqual($"{umbracoPath}/api/{controllerNamePattern}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText); + } else + { Assert.AreEqual($"{umbracoPath}/{areaPattern}/{controllerNamePattern}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText); + } } if (!area.IsNullOrWhiteSpace()) + { Assert.AreEqual(area, endpoint.RoutePattern.Defaults["area"]); + } + if (!defaultAction.IsNullOrWhiteSpace()) + { Assert.AreEqual(defaultAction, endpoint.RoutePattern.Defaults["action"]); + } + Assert.AreEqual(controllerName, endpoint.RoutePattern.Defaults["controller"]); } private class Testing1Controller : ControllerBase { - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/InstallAreaRoutesTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/InstallAreaRoutesTests.cs index 4035c4d2d0..74671f819a 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/InstallAreaRoutesTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/InstallAreaRoutesTests.cs @@ -1,8 +1,11 @@ -using Microsoft.AspNetCore.Mvc; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Moq; using NUnit.Framework; -using System.Linq; using Umbraco.Core; using Umbraco.Core.Hosting; using Umbraco.Extensions; @@ -18,7 +21,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing [TestCase(RuntimeLevel.Boot)] public void RuntimeState_No_Routes(RuntimeLevel level) { - var routes = GetInstallAreaRoutes(level); + InstallAreaRoutes routes = GetInstallAreaRoutes(level); var endpoints = new TestRouteBuilder(); routes.CreateRoutes(endpoints); @@ -29,12 +32,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing [TestCase(RuntimeLevel.Upgrade)] public void RuntimeState_Install(RuntimeLevel level) { - var routes = GetInstallAreaRoutes(level); + InstallAreaRoutes routes = GetInstallAreaRoutes(level); var endpoints = new TestRouteBuilder(); routes.CreateRoutes(endpoints); Assert.AreEqual(2, endpoints.DataSources.Count); - var route = endpoints.DataSources.First(); + EndpointDataSource route = endpoints.DataSources.First(); Assert.AreEqual(2, route.Endpoints.Count); var endpoint1 = (RouteEndpoint)route.Endpoints[0]; @@ -51,7 +54,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing Assert.AreEqual(ControllerExtensions.GetControllerName(), endpoint2.RoutePattern.Defaults["controller"]); Assert.AreEqual(endpoint2.RoutePattern.Defaults["area"], typeof(InstallController).GetCustomAttribute(false).RouteValue); - var fallbackRoute = endpoints.DataSources.Last(); + EndpointDataSource fallbackRoute = endpoints.DataSources.Last(); Assert.AreEqual(1, fallbackRoute.Endpoints.Count); Assert.AreEqual("Fallback {*path:nonfile}", fallbackRoute.Endpoints[0].ToString()); @@ -60,26 +63,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing [Test] public void RuntimeState_Run() { - var routes = GetInstallAreaRoutes(RuntimeLevel.Run); + InstallAreaRoutes routes = GetInstallAreaRoutes(RuntimeLevel.Run); var endpoints = new TestRouteBuilder(); routes.CreateRoutes(endpoints); Assert.AreEqual(1, endpoints.DataSources.Count); - var route = endpoints.DataSources.First(); + EndpointDataSource route = endpoints.DataSources.First(); Assert.AreEqual(1, route.Endpoints.Count); Assert.AreEqual("install/{controller?}/{action?} HTTP: GET", route.Endpoints[0].ToString()); - } - private InstallAreaRoutes GetInstallAreaRoutes(RuntimeLevel level) - { - var routes = new InstallAreaRoutes( + private InstallAreaRoutes GetInstallAreaRoutes(RuntimeLevel level) => + new InstallAreaRoutes( Mock.Of(x => x.Level == level), Mock.Of(x => x.ToAbsolute(It.IsAny()) == "/install" && x.ApplicationVirtualPath == string.Empty), Mock.Of()); - - return routes; - } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/PreviewRoutesTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/PreviewRoutesTests.cs index 1fc6b092c8..32d4f41f8a 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/PreviewRoutesTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/PreviewRoutesTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Options; @@ -10,15 +13,10 @@ using Umbraco.Core.Hosting; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Controllers; using Umbraco.Web.BackOffice.Routing; -using Umbraco.Web.BackOffice.SignalR; -using Umbraco.Web.Common.Attributes; -using Umbraco.Web.Common.Controllers; -using Umbraco.Web.WebApi; using Constants = Umbraco.Core.Constants; namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing { - [TestFixture] public class PreviewRoutesTests { @@ -29,31 +27,29 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing [TestCase(RuntimeLevel.Upgrade)] public void RuntimeState_No_Routes(RuntimeLevel level) { - var routes = GetRoutes(level); + PreviewRoutes routes = GetRoutes(level); var endpoints = new TestRouteBuilder(); routes.CreateRoutes(endpoints); Assert.AreEqual(0, endpoints.DataSources.Count); } - [Test] public void RuntimeState_Run() { - var routes = GetRoutes(RuntimeLevel.Run); + PreviewRoutes routes = GetRoutes(RuntimeLevel.Run); var endpoints = new TestRouteBuilder(); routes.CreateRoutes(endpoints); Assert.AreEqual(2, endpoints.DataSources.Count); - var route = endpoints.DataSources.First(); + EndpointDataSource route = endpoints.DataSources.First(); Assert.AreEqual(2, route.Endpoints.Count); - var endpoint0 = (RouteEndpoint) route.Endpoints[0]; + var endpoint0 = (RouteEndpoint)route.Endpoints[0]; Assert.AreEqual($"{routes.GetPreviewHubRoute()}/negotiate", endpoint0.RoutePattern.RawText); - var endpoint1 = (RouteEndpoint) route.Endpoints[1]; + var endpoint1 = (RouteEndpoint)route.Endpoints[1]; Assert.AreEqual($"{routes.GetPreviewHubRoute()}", endpoint1.RoutePattern.RawText); - var endpoint3 = (RouteEndpoint)endpoints.DataSources.Last().Endpoints[0]; var previewControllerName = ControllerExtensions.GetControllerName(); Assert.AreEqual($"umbraco/{previewControllerName.ToLowerInvariant()}/{{action}}/{{id?}}", endpoint3.RoutePattern.RawText); @@ -61,9 +57,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing Assert.AreEqual("Index", endpoint3.RoutePattern.Defaults["action"]); Assert.AreEqual(previewControllerName, endpoint3.RoutePattern.Defaults["controller"]); Assert.AreEqual(endpoint3.RoutePattern.Defaults["area"], typeof(PreviewController).GetCustomAttribute(false).RouteValue); - - } + private PreviewRoutes GetRoutes(RuntimeLevel level) { var globalSettings = new GlobalSettings(); @@ -72,7 +67,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing Mock.Of(x => x.ToAbsolute(It.IsAny()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty), Mock.Of(x => x.Level == level)); - return routes; } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/TestRouteBuilder.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/TestRouteBuilder.cs index de21bc5129..c35c1a1d9e 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/TestRouteBuilder.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/TestRouteBuilder.cs @@ -1,15 +1,16 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.DependencyInjection; -using Moq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting.Internal; using Microsoft.Extensions.Logging; +using Moq; namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing { @@ -37,6 +38,5 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing mock.Setup(x => x.Build()).Returns(httpContext => Task.CompletedTask); return mock.Object; } - } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Security/EncryptionHelperTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Security/EncryptionHelperTests.cs index db80e2cd74..0e54676f10 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Security/EncryptionHelperTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Security/EncryptionHelperTests.cs @@ -1,8 +1,9 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using Microsoft.AspNetCore.DataProtection; using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Web; using Umbraco.Web.Common.Security; namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Security @@ -10,7 +11,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Security [TestFixture] public class EncryptionHelperTests { - private IDataProtectionProvider DataProtectionProvider { get; } = new EphemeralDataProtectionProvider(); [Test] @@ -28,9 +28,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Security DataProtectionProvider, "FormController", "FormAction", - "", - additionalRouteValues - ); + string.Empty, + additionalRouteValues); var result = EncryptionHelper.Decrypt(encryptedRouteString, DataProtectionProvider); @@ -44,19 +43,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Security { var additionalRouteValues = new Dictionary() { - {"key1", "value1"}, - {"key2", "value2"}, - {"Key3", "Value3"}, - {"keY4", "valuE4"} + { "key1", "value1" }, + { "key2", "value2" }, + { "Key3", "Value3" }, + { "keY4", "valuE4" } }; var encryptedRouteString = EncryptionHelper.CreateEncryptedRouteString( DataProtectionProvider, "FormController", "FormAction", - "", - additionalRouteValues - ); + string.Empty, + additionalRouteValues); var result = EncryptionHelper.Decrypt(encryptedRouteString, DataProtectionProvider); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Views/UmbracoViewPageTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Views/UmbracoViewPageTests.cs index 3b52d0701e..d67f507f0f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Views/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Views/UmbracoViewPageTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; @@ -13,14 +16,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views [TestFixture] public class UmbracoViewPageTests { - #region RenderModel To ... [Test] public void RenderModel_To_RenderModel() { var content = new ContentType1(null); var model = new ContentModel(content); var view = new RenderModelTestPage(); - var viewData = GetViewDataDictionary(model); + ViewDataDictionary viewData = GetViewDataDictionary(model); view.ViewData = viewData; Assert.AreSame(model, view.Model); @@ -31,7 +33,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views { var content = new ContentType1(null); var view = new ContentType1TestPage(); - var viewData = GetViewDataDictionary(content); + ViewDataDictionary viewData = GetViewDataDictionary(content); view.ViewData = viewData; @@ -44,7 +46,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType2(null); var view = new ContentType1TestPage(); - var viewData = GetViewDataDictionary(content); + ViewDataDictionary viewData = GetViewDataDictionary(content); view.ViewData = viewData; Assert.IsInstanceOf(view.Model); @@ -56,7 +58,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType1(null); var model = new ContentModel(content); var view = new ContentType2TestPage(); - var viewData = GetViewDataDictionary(model); + ViewDataDictionary viewData = GetViewDataDictionary(model); Assert.ThrowsAsync(async () => await view.SetViewDataAsyncX(viewData)); } @@ -67,7 +69,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType1(null); var model = new ContentModel(content); var view = new RenderModelOfContentType1TestPage(); - var viewData = GetViewDataDictionary>(model); + ViewDataDictionary> viewData = GetViewDataDictionary>(model); view.ViewData = viewData; @@ -81,7 +83,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType2(null); var model = new ContentModel(content); var view = new RenderModelOfContentType1TestPage(); - var viewData = GetViewDataDictionary>(model); + ViewDataDictionary> viewData = GetViewDataDictionary>(model); view.ViewData = viewData; Assert.IsInstanceOf>(view.Model); @@ -94,22 +96,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType1(null); var model = new ContentModel(content); var view = new RenderModelOfContentType2TestPage(); - var viewData = GetViewDataDictionary(model); + ViewDataDictionary viewData = GetViewDataDictionary(model); Assert.ThrowsAsync(async () => await view.SetViewDataAsyncX(viewData)); } - #endregion - - #region RenderModelOf To ... - [Test] public void RenderModelOf_ContentType1_To_RenderModel() { var content = new ContentType1(null); var model = new ContentModel(content); var view = new RenderModelTestPage(); - var viewData = GetViewDataDictionary(model); + ViewDataDictionary viewData = GetViewDataDictionary(model); view.ViewData = viewData; @@ -122,7 +120,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType1(null); var model = new ContentModel(content); var view = new ContentType1TestPage(); - var viewData = GetViewDataDictionary>(model); + ViewDataDictionary> viewData = GetViewDataDictionary>(model); await view.SetViewDataAsyncX(viewData); @@ -135,9 +133,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType2(null); var model = new ContentModel(content); var view = new ContentType1TestPage(); - var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) + var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { - Model = model + Model = model }; await view.SetViewDataAsyncX(viewData); @@ -148,11 +146,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views [Test] public async Task RenderModelOf_ContentType1_To_ContentType2() { - var content = new ContentType1(null); var model = new ContentModel(content); var view = new ContentType2TestPage(); - var viewData = GetViewDataDictionary(model); + ViewDataDictionary viewData = GetViewDataDictionary(model); Assert.ThrowsAsync(async () => await view.SetViewDataAsyncX(viewData)); } @@ -163,7 +160,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType1(null); var model = new ContentModel(content); var view = new RenderModelOfContentType1TestPage(); - var viewData = GetViewDataDictionary>(model); + ViewDataDictionary> viewData = GetViewDataDictionary>(model); view.ViewData = viewData; @@ -177,7 +174,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType2(null); var model = new ContentModel(content); var view = new RenderModelOfContentType1TestPage(); - var viewData = GetViewDataDictionary>(model); + ViewDataDictionary> viewData = GetViewDataDictionary>(model); await view.SetViewDataAsyncX(viewData); @@ -191,22 +188,18 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType1(null); var model = new ContentModel(content); var view = new RenderModelOfContentType2TestPage(); - var viewData = GetViewDataDictionary(model); + ViewDataDictionary viewData = GetViewDataDictionary(model); Assert.ThrowsAsync(async () => await view.SetViewDataAsyncX(viewData)); } - #endregion - - #region ContentType To ... - [Test] public async Task ContentType1_To_RenderModel() { var content = new ContentType1(null); var view = new RenderModelTestPage(); - var viewData = GetViewDataDictionary(content); + ViewDataDictionary viewData = GetViewDataDictionary(content); await view.SetViewDataAsyncX(viewData); @@ -219,7 +212,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views var content = new ContentType1(null); var view = new RenderModelOfContentType1TestPage(); - var viewData = GetViewDataDictionary(content); + ViewDataDictionary viewData = GetViewDataDictionary(content); await view.SetViewDataAsyncX(viewData); Assert.IsInstanceOf>(view.Model); @@ -232,7 +225,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views // Same as above but with ContentModel var content = new ContentType2(null); var view = new RenderModelOfContentType1TestPage(); - var viewData = GetViewDataDictionary(content); + ViewDataDictionary viewData = GetViewDataDictionary(content); await view.SetViewDataAsyncX(viewData); @@ -245,7 +238,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views { var content = new ContentType1(null); var view = new RenderModelOfContentType2TestPage(); - var viewData = GetViewDataDictionary(content); + ViewDataDictionary viewData = GetViewDataDictionary(content); Assert.ThrowsAsync(async () => await view.SetViewDataAsyncX(viewData)); } @@ -255,7 +248,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views { var content = new ContentType1(null); var view = new ContentType1TestPage(); - var viewData = GetViewDataDictionary(content); + ViewDataDictionary viewData = GetViewDataDictionary(content); await view.SetViewDataAsyncX(viewData); @@ -267,7 +260,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views { var content = new ContentType1(null); var view = new ContentType2TestPage(); - var viewData = GetViewDataDictionary(content); + ViewDataDictionary viewData = GetViewDataDictionary(content); Assert.ThrowsAsync(async () => await view.SetViewDataAsyncX(viewData)); } @@ -277,17 +270,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views { var content = new ContentType2(null); var view = new ContentType1TestPage(); - var viewData = GetViewDataDictionary(content); + ViewDataDictionary viewData = GetViewDataDictionary(content); await view.SetViewDataAsyncX(viewData); Assert.IsInstanceOf(view.Model); } - #endregion - - #region Test helpers methods - private ViewDataDictionary GetViewDataDictionary(object model) { var sourceViewDataDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()); @@ -303,48 +292,47 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Views }; } - #endregion - - #region Test elements - public class ContentType1 : PublishedContentWrapped { - public ContentType1(IPublishedContent content) : base(content) {} + public ContentType1(IPublishedContent content) + : base(content) + { + } } public class ContentType2 : ContentType1 { - public ContentType2(IPublishedContent content) : base(content) { } + public ContentType2(IPublishedContent content) + : base(content) + { + } } public class TestPage : UmbracoViewPage { - public override Task ExecuteAsync() - { - throw new NotImplementedException(); - } + public override Task ExecuteAsync() => throw new NotImplementedException(); - public async Task SetViewDataAsyncX(ViewDataDictionary viewData) - { - await SetViewDataAsync(viewData); - } + public async Task SetViewDataAsyncX(ViewDataDictionary viewData) => await SetViewDataAsync(viewData); } public class RenderModelTestPage : TestPage - { } + { + } public class ContentType1TestPage : TestPage - { } + { + } public class ContentType2TestPage : TestPage - { } + { + } public class RenderModelOfContentType1TestPage : TestPage> - { } + { + } public class RenderModelOfContentType2TestPage : TestPage> - { } - - #endregion + { + } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/AspNetCoreHostingEnvironmentTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/AspNetCoreHostingEnvironmentTests.cs index 1e579cc7dd..8ecd05367a 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/AspNetCoreHostingEnvironmentTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/AspNetCoreHostingEnvironmentTests.cs @@ -1,11 +1,9 @@ -using System; -using AutoFixture.NUnit3; -using Moq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; -using Umbraco.Core.Hosting; -using Umbraco.Core.IO; using Umbraco.Core.Strings; -using Umbraco.Tests.TestHelpers; using Umbraco.Tests.UnitTests.AutoFixture; using Umbraco.Web.Common.AspNetCore; @@ -14,20 +12,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website [TestFixture] public class AspNetCoreHostingEnvironmentTests { - [InlineAutoMoqData("~/Scripts", "/Scripts", null)] [InlineAutoMoqData("/Scripts", "/Scripts", null)] [InlineAutoMoqData("../Scripts", "/Scripts", typeof(InvalidOperationException))] public void IOHelper_ResolveUrl(string input, string expected, Type expectedExceptionType, AspNetCoreHostingEnvironment sut) { - if (expectedExceptionType != null) { - Assert.Throws(expectedExceptionType, () =>sut.ToAbsolute(input)); + Assert.Throws(expectedExceptionType, () => sut.ToAbsolute(input)); } else { - var result = sut.ToAbsolute(input); Assert.AreEqual(expected, result); } @@ -36,7 +31,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website [Test] public void EnsurePathIsApplicationRootPrefixed() { - //Assert + // Assert Assert.AreEqual("~/Views/Template.cshtml", PathUtility.EnsurePathIsApplicationRootPrefixed("Views/Template.cshtml")); Assert.AreEqual("~/Views/Template.cshtml", PathUtility.EnsurePathIsApplicationRootPrefixed("/Views/Template.cshtml")); Assert.AreEqual("~/Views/Template.cshtml", PathUtility.EnsurePathIsApplicationRootPrefixed("~/Views/Template.cshtml")); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/RenderIndexActionSelectorAttributeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/RenderIndexActionSelectorAttributeTests.cs index 3a987fb038..872679769f 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/RenderIndexActionSelectorAttributeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/RenderIndexActionSelectorAttributeTests.cs @@ -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; @@ -27,62 +30,78 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers { var sut = new RenderIndexActionSelectorAttribute(); - var actionDescriptor = + ControllerActionDescriptor actionDescriptor = GetRenderMvcControllerIndexMethodFromCurrentType(typeof(MatchesDefaultIndexController)).First(); var actionDescriptorCollectionProviderMock = new Mock(); actionDescriptorCollectionProviderMock.Setup(x => x.ActionDescriptors) .Returns(new ActionDescriptorCollection(Array.Empty(), 1)); - var routeContext = CreateRouteContext(actionDescriptorCollectionProviderMock.Object); + RouteContext routeContext = CreateRouteContext(actionDescriptorCollectionProviderMock.Object); // Call the method multiple times - for (var i = 0; i < 1; i++) + for (int i = 0; i < 1; i++) { sut.IsValidForRequest(routeContext, actionDescriptor); } - //Ensure the underlying ActionDescriptors is only called once. - actionDescriptorCollectionProviderMock.Verify(x=>x.ActionDescriptors, Times.Once); + // Ensure the underlying ActionDescriptors is only called once. + actionDescriptorCollectionProviderMock.Verify(x => x.ActionDescriptors, Times.Once); } [Test] - [TestCase(typeof(MatchesDefaultIndexController), - "Index", new[] { typeof(ContentModel) }, typeof(IActionResult), ExpectedResult = true)] - [TestCase(typeof(MatchesOverriddenIndexController), - "Index", new[] { typeof(ContentModel) }, typeof(IActionResult), ExpectedResult = true)] - [TestCase(typeof(MatchesCustomIndexController), - "Index", new[] { typeof(ContentModel), typeof(int) }, typeof(IActionResult), ExpectedResult = false)] - [TestCase(typeof(MatchesAsyncIndexController), - "Index", new[] { typeof(ContentModel) }, typeof(Task), ExpectedResult = false)] + [TestCase( + typeof(MatchesDefaultIndexController), + "Index", + new[] { typeof(ContentModel) }, + typeof(IActionResult), + ExpectedResult = true)] + [TestCase( + typeof(MatchesOverriddenIndexController), + "Index", + new[] { typeof(ContentModel) }, + typeof(IActionResult), + ExpectedResult = true)] + [TestCase( + typeof(MatchesCustomIndexController), + "Index", + new[] { typeof(ContentModel), typeof(int) }, + typeof(IActionResult), + ExpectedResult = false)] + [TestCase( + typeof(MatchesAsyncIndexController), + "Index", + new[] { typeof(ContentModel) }, + typeof(Task), + ExpectedResult = false)] public bool IsValidForRequest__must_return_the_expected_result(Type controllerType, string actionName, Type[] parameterTypes, Type returnType) { - //Fake all IActionDescriptor's that will be returned by IActionDescriptorCollectionProvider - var actionDescriptors = GetRenderMvcControllerIndexMethodFromCurrentType(controllerType); + // Fake all IActionDescriptor's that will be returned by IActionDescriptorCollectionProvider + ControllerActionDescriptor[] actionDescriptors = GetRenderMvcControllerIndexMethodFromCurrentType(controllerType); // Find the one that match the current request - var actualActionDescriptor = actionDescriptors.Single(x => x.ActionName == actionName + ControllerActionDescriptor actualActionDescriptor = actionDescriptors.Single(x => x.ActionName == actionName && x.ControllerTypeInfo.Name == controllerType.Name && x.MethodInfo.ReturnType == returnType && x.MethodInfo.GetParameters().Select(m => m.ParameterType).SequenceEqual(parameterTypes)); - //Fake the IActionDescriptorCollectionProvider and add it to the service collection on httpcontext + // Fake the IActionDescriptorCollectionProvider and add it to the service collection on httpcontext var sut = new RenderIndexActionSelectorAttribute(); - var routeContext = CreateRouteContext(new TestActionDescriptorCollectionProvider(actionDescriptors)); + RouteContext routeContext = CreateRouteContext(new TestActionDescriptorCollectionProvider(actionDescriptors)); - //Act - var result = sut.IsValidForRequest(routeContext, actualActionDescriptor); + // Act + bool result = sut.IsValidForRequest(routeContext, actualActionDescriptor); return result; } private ControllerActionDescriptor[] GetRenderMvcControllerIndexMethodFromCurrentType(Type controllerType) { - var actions = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance) + IEnumerable actions = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => !m.IsSpecialName && m.GetCustomAttribute() is null && m.Module.Name.Contains("Umbraco")); - var actionDescriptors = actions + ControllerActionDescriptor[] actionDescriptors = actions .Select(x => new ControllerActionDescriptor() { ControllerTypeInfo = controllerType.GetTypeInfo(), @@ -95,7 +114,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers private static RouteContext CreateRouteContext(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) { - //Fake the IActionDescriptorCollectionProvider and add it to the service collection on httpcontext + // Fake the IActionDescriptorCollectionProvider and add it to the service collection on httpcontext var httpContext = new DefaultHttpContext(); var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(actionDescriptorCollectionProvider); @@ -110,57 +129,53 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers private class TestActionDescriptorCollectionProvider : IActionDescriptorCollectionProvider { - public TestActionDescriptorCollectionProvider(IReadOnlyList items) - { - ActionDescriptors = new ActionDescriptorCollection(items, 1); - } + public TestActionDescriptorCollectionProvider(IReadOnlyList items) => ActionDescriptors = new ActionDescriptorCollection(items, 1); public ActionDescriptorCollection ActionDescriptors { get; } } private class MatchesDefaultIndexController : RenderMvcController { - public MatchesDefaultIndexController(ILogger logger, - ICompositeViewEngine compositeViewEngine) : base(logger, compositeViewEngine) + public MatchesDefaultIndexController( + ILogger logger, + ICompositeViewEngine compositeViewEngine) + : base(logger, compositeViewEngine) { } } private class MatchesOverriddenIndexController : RenderMvcController { - public override IActionResult Index(ContentModel model) - { - return base.Index(model); - } + public override IActionResult Index(ContentModel model) => base.Index(model); - public MatchesOverriddenIndexController(ILogger logger, - ICompositeViewEngine compositeViewEngine) : base(logger, compositeViewEngine) + public MatchesOverriddenIndexController( + ILogger logger, + ICompositeViewEngine compositeViewEngine) + : base(logger, compositeViewEngine) { } } private class MatchesCustomIndexController : RenderMvcController { - public IActionResult Index(ContentModel model, int page) - { - return base.Index(model); - } + public IActionResult Index(ContentModel model, int page) => Index(model); - public MatchesCustomIndexController(ILogger logger, - ICompositeViewEngine compositeViewEngine) : base(logger, compositeViewEngine) + public MatchesCustomIndexController( + ILogger logger, + ICompositeViewEngine compositeViewEngine) + : base(logger, compositeViewEngine) { } } private class MatchesAsyncIndexController : RenderMvcController { - public new async Task Index(ContentModel model) - { - return await Task.FromResult(base.Index(model)); - } + public new async Task Index(ContentModel model) => await Task.FromResult(base.Index(model)); - public MatchesAsyncIndexController(ILogger logger, - ICompositeViewEngine compositeViewEngine) : base(logger, compositeViewEngine) + public MatchesAsyncIndexController( + ILogger logger, + ICompositeViewEngine compositeViewEngine) + : base(logger, compositeViewEngine) { } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/RenderNoContentControllerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/RenderNoContentControllerTests.cs index 182fb94a40..9320c87949 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/RenderNoContentControllerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/RenderNoContentControllerTests.cs @@ -1,4 +1,7 @@ -using Microsoft.AspNetCore.Mvc; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; @@ -17,7 +20,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers [Test] public void Redirects_To_Root_When_Content_Published() { - var mockUmbracoContext = new Mock(); mockUmbracoContext.Setup(x => x.Content.HasContent()).Returns(true); var mockIOHelper = new Mock(); @@ -40,7 +42,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers var mockIOHelper = new Mock(); mockIOHelper.Setup(x => x.ResolveUrl(It.Is(y => y == UmbracoPathSetting))).Returns(UmbracoPath); - var globalSettings = Options.Create(new GlobalSettings() + IOptions globalSettings = Options.Create(new GlobalSettings() { UmbracoPath = UmbracoPathSetting, NoNodesViewPath = ViewPath, diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs index 82bd6719d4..8b353488e9 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -16,7 +19,6 @@ using Umbraco.Tests.Testing; using Umbraco.Web; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; -using Umbraco.Web.Security; using Umbraco.Web.Website; using Umbraco.Web.Website.Controllers; using CoreConstants = Umbraco.Core.Constants; @@ -30,16 +32,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers private IUmbracoContextAccessor _umbracoContextAccessor; [SetUp] - public void SetUp() - { - _umbracoContextAccessor = new TestUmbracoContextAccessor(); - } + public void SetUp() => _umbracoContextAccessor = new TestUmbracoContextAccessor(); [Test] public void Can_Construct_And_Get_Result() { - var hostingEnvironment = Mock.Of(); - var backofficeSecurityAccessor = Mock.Of(); + IHostingEnvironment hostingEnvironment = Mock.Of(); + IBackOfficeSecurityAccessor backofficeSecurityAccessor = Mock.Of(); Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); var globalSettings = new GlobalSettings(); @@ -55,14 +54,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers Mock.Of(), backofficeSecurityAccessor); - var umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(); - var umbracoContext = umbracoContextReference.UmbracoContext; + UmbracoContextReference umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(); + IUmbracoContext umbracoContext = umbracoContextReference.UmbracoContext; var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); var ctrl = new TestSurfaceController(umbracoContextAccessor, Mock.Of(), Mock.Of()); - var result = ctrl.Index(); + IActionResult result = ctrl.Index(); Assert.IsNotNull(result); } @@ -71,8 +70,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers public void Umbraco_Context_Not_Null() { var globalSettings = new GlobalSettings(); - var hostingEnvironment = Mock.Of(); - var backofficeSecurityAccessor = Mock.Of(); + IHostingEnvironment hostingEnvironment = Mock.Of(); + IBackOfficeSecurityAccessor backofficeSecurityAccessor = Mock.Of(); Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); var umbracoContextFactory = new UmbracoContextFactory( _umbracoContextAccessor, @@ -86,8 +85,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers Mock.Of(), backofficeSecurityAccessor); - var umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(); - var umbCtx = umbracoContextReference.UmbracoContext; + UmbracoContextReference umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(); + IUmbracoContext umbCtx = umbracoContextReference.UmbracoContext; var umbracoContextAccessor = new TestUmbracoContextAccessor(umbCtx); @@ -103,10 +102,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers publishedSnapshot.Setup(x => x.Members).Returns(Mock.Of()); var content = new Mock(); content.Setup(x => x.Id).Returns(2); - var backofficeSecurityAccessor = Mock.Of(); + IBackOfficeSecurityAccessor backofficeSecurityAccessor = Mock.Of(); Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); var publishedSnapshotService = new Mock(); - var hostingEnvironment = Mock.Of(); + IHostingEnvironment hostingEnvironment = Mock.Of(); var globalSettings = new GlobalSettings(); var umbracoContextFactory = new UmbracoContextFactory( @@ -121,12 +120,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers Mock.Of(), backofficeSecurityAccessor); - var umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(); - var umbracoContext = umbracoContextReference.UmbracoContext; + UmbracoContextReference umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(); + IUmbracoContext umbracoContext = umbracoContextReference.UmbracoContext; var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var publishedContentQuery = Mock.Of(query => query.Content(2) == content.Object); + IPublishedContentQuery publishedContentQuery = Mock.Of(query => query.Content(2) == content.Object); var ctrl = new TestSurfaceController(umbracoContextAccessor, publishedContentQuery, Mock.Of()); var result = ctrl.GetContent(2) as PublishedContentResult; @@ -136,13 +135,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers Assert.AreEqual(2, result.Content.Id); } - [Test] public void Mock_Current_Page() { var globalSettings = new GlobalSettings(); - var hostingEnvironment = Mock.Of(); - var backofficeSecurityAccessor = Mock.Of(); + IHostingEnvironment hostingEnvironment = Mock.Of(); + IBackOfficeSecurityAccessor backofficeSecurityAccessor = Mock.Of(); Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); var umbracoContextFactory = new UmbracoContextFactory( _umbracoContextAccessor, @@ -156,17 +154,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers Mock.Of(), backofficeSecurityAccessor); - var umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(); - var umbracoContext = umbracoContextReference.UmbracoContext; + UmbracoContextReference umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(); + IUmbracoContext umbracoContext = umbracoContextReference.UmbracoContext; var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var content = Mock.Of(publishedContent => publishedContent.Id == 12345); + IPublishedContent content = Mock.Of(publishedContent => publishedContent.Id == 12345); var publishedRequestMock = new Mock(); publishedRequestMock.Setup(x => x.PublishedContent).Returns(content); - var routeDefinition = new RouteDefinition + var routeDefinition = new RouteDefinition { PublishedRequest = publishedRequestMock.Object }; @@ -174,11 +172,13 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers var routeData = new RouteData(); routeData.DataTokens.Add(CoreConstants.Web.UmbracoRouteDefinitionDataToken, routeDefinition); - var ctrl = new TestSurfaceController(umbracoContextAccessor, Mock.Of(), Mock.Of()); - ctrl.ControllerContext = new ControllerContext() + var ctrl = new TestSurfaceController(umbracoContextAccessor, Mock.Of(), Mock.Of()) { - HttpContext = Mock.Of(), - RouteData = routeData + ControllerContext = new ControllerContext() + { + HttpContext = Mock.Of(), + RouteData = routeData + } }; var result = ctrl.GetContentFromCurrentPage() as PublishedContentResult; @@ -186,33 +186,29 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers Assert.AreEqual(12345, result.Content.Id); } - public class TestSurfaceController : SurfaceController { private readonly IPublishedContentQuery _publishedContentQuery; public TestSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IPublishedContentQuery publishedContentQuery, IPublishedUrlProvider publishedUrlProvider) - : base(umbracoContextAccessor, null, ServiceContext.CreatePartial(), AppCaches.Disabled, null, publishedUrlProvider) - { + : base(umbracoContextAccessor, null, ServiceContext.CreatePartial(), AppCaches.Disabled, null, publishedUrlProvider) => _publishedContentQuery = publishedContentQuery; - } - public IActionResult Index() - { + public IActionResult Index() => + // ReSharper disable once Mvc.ViewNotResolved - return View(); - } + View(); public IActionResult GetContent(int id) { - var content = _publishedContentQuery.Content(id); + IPublishedContent content = _publishedContentQuery.Content(id); return new PublishedContentResult(content); } public IActionResult GetContentFromCurrentPage() { - var content = CurrentPage; + IPublishedContent content = CurrentPage; return new PublishedContentResult(content); } @@ -222,15 +218,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers { public IPublishedContent Content { get; set; } - public PublishedContentResult(IPublishedContent content) - { - Content = content; - } + public PublishedContentResult(IPublishedContent content) => Content = content; - public Task ExecuteResultAsync(ActionContext context) - { - return Task.CompletedTask; - } + public Task ExecuteResultAsync(ActionContext context) => Task.CompletedTask; } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Security/UmbracoWebsiteSecurityTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Security/UmbracoWebsiteSecurityTests.cs index d021d38c15..50ff362cdc 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Security/UmbracoWebsiteSecurityTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Security/UmbracoWebsiteSecurityTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using System.Security.Claims; using System.Security.Principal; using Microsoft.AspNetCore.Http; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/ViewEngines/ProfilingViewEngineWrapperMvcViewOptionsSetupTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/ViewEngines/ProfilingViewEngineWrapperMvcViewOptionsSetupTests.cs index a74431b705..ba791dd8f2 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/ViewEngines/ProfilingViewEngineWrapperMvcViewOptionsSetupTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/ViewEngines/ProfilingViewEngineWrapperMvcViewOptionsSetupTests.cs @@ -1,4 +1,7 @@ -using Microsoft.AspNetCore.Mvc; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using Umbraco.Core.Logging; @@ -11,6 +14,7 @@ namespace Umbraco.Tests.Runtimes { private ProfilingViewEngineWrapperMvcViewOptionsSetup Sut => new ProfilingViewEngineWrapperMvcViewOptionsSetup(Mock.Of()); + [Test] public void WrapViewEngines_HasEngines_WrapsAll() { @@ -67,9 +71,6 @@ namespace Umbraco.Tests.Runtimes } [Test] - public void WrapViewEngines_CollectionIsNull_DoesNotThrow() - { - Assert.DoesNotThrow(() => Sut.Configure(new MvcViewOptions())); - } + public void WrapViewEngines_CollectionIsNull_DoesNotThrow() => Assert.DoesNotThrow(() => Sut.Configure(new MvcViewOptions())); } }