diff --git a/src/Umbraco.Tests.Integration/Extensions/ServiceCollectionExtensions.cs b/src/Umbraco.Tests.Integration/Extensions/ServiceCollectionExtensions.cs index dc58d3e9e6..cc01a08287 100644 --- a/src/Umbraco.Tests.Integration/Extensions/ServiceCollectionExtensions.cs +++ b/src/Umbraco.Tests.Integration/Extensions/ServiceCollectionExtensions.cs @@ -1,4 +1,7 @@ -using Microsoft.AspNetCore.Hosting; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -11,15 +14,14 @@ namespace Umbraco.Tests.Integration.Extensions /// /// These services need to be manually added because they do not get added by the generic host /// - /// - /// - /// public static void AddRequiredNetCoreServices(this IServiceCollection services, TestHelper testHelper, IWebHostEnvironment webHostEnvironment) { services.AddSingleton(x => testHelper.GetHttpContextAccessor()); - // the generic host does add IHostEnvironment but not this one because we are not actually in a web context + + // The generic host does add IHostEnvironment but not this one because we are not actually in a web context services.AddSingleton(x => webHostEnvironment); - // replace the IHostEnvironment that generic host created too + + // Replace the IHostEnvironment that generic host created too services.AddSingleton(x => webHostEnvironment); } } diff --git a/src/Umbraco.Tests.Integration/GlobalSetupTeardown.cs b/src/Umbraco.Tests.Integration/GlobalSetupTeardown.cs index 6e86e97770..4aca5ff98a 100644 --- a/src/Umbraco.Tests.Integration/GlobalSetupTeardown.cs +++ b/src/Umbraco.Tests.Integration/GlobalSetupTeardown.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Diagnostics; @@ -5,12 +8,16 @@ using System.Text; using NUnit.Framework; using Umbraco.Tests.Integration.Testing; -// this class has NO NAMESPACE -// it applies to the whole assembly - -[SetUpFixture] // ReSharper disable once CheckNamespace -public class TestsSetup + +/// +/// Global setup and teardown. +/// +/// +/// This class has NO NAMESPACE so it applies to the whole assembly. +/// +[SetUpFixture] +public class GlobalSetupTeardown { private Stopwatch _stopwatch; diff --git a/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs b/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs index fd9ffe5d26..8095970553 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections; using System.ComponentModel; using System.Data.Common; @@ -44,22 +47,25 @@ namespace Umbraco.Tests.Integration.Implementations private readonly IHttpContextAccessor _httpContextAccessor; private string _tempWorkingDir; - public TestHelper() : base(typeof(TestHelper).Assembly) + public TestHelper() + : base(typeof(TestHelper).Assembly) { var httpContext = new DefaultHttpContext(); httpContext.Connection.RemoteIpAddress = IPAddress.Parse("127.0.0.1"); _httpContextAccessor = Mock.Of(x => x.HttpContext == httpContext); _ipResolver = new AspNetCoreIpResolver(_httpContextAccessor); - var contentRoot = Assembly.GetExecutingAssembly().GetRootDirectorySafe(); + string contentRoot = Assembly.GetExecutingAssembly().GetRootDirectorySafe(); var hostEnvironment = new Mock(); - // this must be the assembly name for the WebApplicationFactory to work + + // This must be the assembly name for the WebApplicationFactory to work. hostEnvironment.Setup(x => x.ApplicationName).Returns(GetType().Assembly.GetName().Name); hostEnvironment.Setup(x => x.ContentRootPath).Returns(() => contentRoot); hostEnvironment.Setup(x => x.ContentRootFileProvider).Returns(() => new PhysicalFileProvider(contentRoot)); hostEnvironment.Setup(x => x.WebRootPath).Returns(() => WorkingDirectory); hostEnvironment.Setup(x => x.WebRootFileProvider).Returns(() => new PhysicalFileProvider(WorkingDirectory)); - // we also need to expose it as the obsolete interface since netcore's WebApplicationFactory casts it + + // We also need to expose it as the obsolete interface since netcore's WebApplicationFactory casts it. hostEnvironment.As(); _hostEnvironment = hostEnvironment.Object; @@ -69,25 +75,24 @@ namespace Umbraco.Tests.Integration.Implementations ProfilingLogger = new ProfilingLogger(ConsoleLoggerFactory.CreateLogger(), Profiler); } - public override string WorkingDirectory { get { // For Azure Devops we can only store a database in certain locations so we will need to detect if we are running // on a build server and if so we'll use the %temp% path. - if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("System_DefaultWorkingDirectory"))) { - // we are using Azure Devops! + // We are using Azure Devops! + if (_tempWorkingDir != null) + { + return _tempWorkingDir; + } - if (_tempWorkingDir != null) return _tempWorkingDir; - - var temp = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoTemp"); + string temp = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoTemp"); Directory.CreateDirectory(temp); _tempWorkingDir = temp; return _tempWorkingDir; - } else { @@ -99,10 +104,13 @@ namespace Umbraco.Tests.Integration.Implementations public IUmbracoBootPermissionChecker UmbracoBootPermissionChecker { get; } = new TestUmbracoBootPermissionChecker(); - public AppCaches AppCaches { get; } = new AppCaches(NoAppCache.Instance, NoAppCache.Instance, + public AppCaches AppCaches { get; } = new AppCaches( + NoAppCache.Instance, + NoAppCache.Instance, new IsolatedCaches(type => NoAppCache.Instance)); public ILoggerFactory ConsoleLoggerFactory { get; private set; } + public IProfilingLogger ProfilingLogger { get; private set; } public IProfiler Profiler { get; } = new VoidProfiler(); @@ -123,7 +131,7 @@ namespace Umbraco.Tests.Integration.Implementations if (_backOfficeInfo == null) { var globalSettings = new GlobalSettings(); - var mockedOptionsMonitorOfGlobalSettings = Mock.Of>(x => x.CurrentValue == globalSettings); + IOptionsMonitor mockedOptionsMonitorOfGlobalSettings = Mock.Of>(x => x.CurrentValue == globalSettings); _backOfficeInfo = new AspNetCoreBackOfficeInfo(mockedOptionsMonitorOfGlobalSettings); } @@ -148,39 +156,43 @@ namespace Umbraco.Tests.Integration.Implementations /// /// 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 override string MapPathForTestFiles(string relativePath) { if (!relativePath.StartsWith("~/")) + { throw new ArgumentException("relativePath must start with '~/'", nameof(relativePath)); + } - var codeBase = typeof(TestHelperBase).Assembly.CodeBase; + string codeBase = typeof(TestHelperBase).Assembly.CodeBase; var uri = new Uri(codeBase); - var path = uri.LocalPath; - var bin = Path.GetDirectoryName(path); + string path = uri.LocalPath; + string bin = Path.GetDirectoryName(path); return relativePath.Replace("~/", bin + "/"); } - public void AssertPropertyValuesAreEqual(object actual, object expected, string dateTimeFormat = null, Func sorter = null, string[] ignoreProperties = null) + public void AssertPropertyValuesAreEqual(object actual, object expected, Func sorter = null, string[] ignoreProperties = null) { const int dateDeltaMilliseconds = 1000; // 1s - 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); + // Ignore properties that are attributed with EditorBrowsableState.Never. + EditorBrowsableAttribute att = property.GetCustomAttribute(false); if (att != null && att.State == EditorBrowsableState.Never) + { continue; + } - // ignore explicitly ignored properties + // Ignore explicitly ignored properties. if (ignoreProperties != null && ignoreProperties.Contains(property.Name)) + { continue; + } - var actualValue = property.GetValue(actual, null); - var expectedValue = property.GetValue(expected, null); + object actualValue = property.GetValue(actual, null); + object expectedValue = property.GetValue(expected, null); AssertAreEqual(property, expectedValue, actualValue, sorter, dateDeltaMilliseconds); } @@ -188,8 +200,6 @@ namespace Umbraco.Tests.Integration.Implementations 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 @@ -197,7 +207,7 @@ namespace Umbraco.Tests.Integration.Implementations { // 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; }; } @@ -205,46 +215,55 @@ namespace Umbraco.Tests.Integration.Implementations 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++) + for (int i = 0; i < actualListEx.Count; i++) + { AssertAreEqual(property, expectedListEx[i], actualListEx[i], sorter, dateDeltaMilliseconds); + } } 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 delta = (actualDateTime - expectedDateTime).TotalMilliseconds; + var actualDateTime = (DateTime)actual; + double 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++) + } + + for (int i = 0; i < expectedPropertyValues.Length; i++) { // This is not pretty, but since a property value can be a datetime we can't just always compare them as is. // This is made worse by the fact that PublishedValue is not always set, meaning we can't lump it all into the same if block if (expectedPropertyValues[i].EditedValue is DateTime expectedEditDateTime) { - var actualEditDateTime = (DateTime) actualPropertyValues[i].EditedValue; + var actualEditDateTime = (DateTime)actualPropertyValues[i].EditedValue; AssertDateTime(expectedEditDateTime, actualEditDateTime, $"{property.DeclaringType.Name}.{property.Name}: Expected draft value \"{expectedPropertyValues[i].EditedValue}\" but got \"{actualPropertyValues[i].EditedValue}\".", dateDeltaMilliseconds); } else @@ -254,7 +273,7 @@ namespace Umbraco.Tests.Integration.Implementations if (expectedPropertyValues[i].PublishedValue is DateTime expectedPublishDateTime) { - var actualPublishedDateTime = (DateTime) actualPropertyValues[i].PublishedValue; + var actualPublishedDateTime = (DateTime)actualPropertyValues[i].PublishedValue; AssertDateTime(expectedPublishDateTime, actualPublishedDateTime, $"{property.DeclaringType.Name}.{property.Name}: Expected published value \"{expectedPropertyValues[i].PublishedValue}\" but got \"{actualPropertyValues[i].PublishedValue}\".", dateDeltaMilliseconds); } else @@ -266,22 +285,28 @@ namespace Umbraco.Tests.Integration.Implementations 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 AssertDateTime(DateTime expected, DateTime actual, string failureMessage, - int dateDeltaMiliseconds = 0) + private static void AssertDateTime(DateTime expected, DateTime actual, string failureMessage, int dateDeltaMiliseconds = 0) { - var delta = (actual - expected).TotalMilliseconds; + double delta = (actual - expected).TotalMilliseconds; Assert.IsTrue(Math.Abs(delta) <= dateDeltaMiliseconds, failureMessage); } @@ -289,32 +314,38 @@ namespace Umbraco.Tests.Integration.Implementations { Try(() => { - if (Directory.Exists(path) == false) return; - foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) + if (Directory.Exists(path) == false) + { + return; + } + + foreach (string file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) + { File.Delete(file); + } }); Try(() => { - if (Directory.Exists(path) == false) return; + if (Directory.Exists(path) == false) + { + return; + } + Directory.Delete(path, true); }); } - public static void TryAssert(Action action, int maxTries = 5, int waitMilliseconds = 200) - { + public static void TryAssert(Action action, int maxTries = 5, int waitMilliseconds = 200) => Try(action, maxTries, waitMilliseconds); - } - public static void Try(Action action, int maxTries = 5, int waitMilliseconds = 200) - { + public static void Try(Action action, int maxTries = 5, int waitMilliseconds = 200) => Try(action, maxTries, waitMilliseconds); - } public static void Try(Action action, int maxTries = 5, int waitMilliseconds = 200) where T : Exception { - var tries = 0; + int tries = 0; while (true) { try @@ -325,7 +356,10 @@ namespace Umbraco.Tests.Integration.Implementations catch (T) { if (tries++ > maxTries) + { throw; + } + Thread.Sleep(waitMilliseconds); } } diff --git a/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs b/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs index 1a3415634b..2a91b6db83 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs @@ -1,4 +1,7 @@ -using Microsoft.AspNetCore.Hosting; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Options; using Umbraco.Core.Configuration.Models; using Umbraco.Web.Common.AspNetCore; @@ -14,10 +17,11 @@ namespace Umbraco.Tests.Integration.Implementations } /// - /// Override for tests since we are not hosted + /// Gets a value indicating whether we are hosted. /// /// - /// This is specifically used by IOHelper and we want this to return false so that the root path is manually calcualted which is what we want for tests. + /// This is specifically used by IOHelper and we want this to return false so that the root path is manually + /// calculated which is what we want for tests. /// bool IHostingEnvironment.IsHosted { get; } = false; } diff --git a/src/Umbraco.Tests.Integration/Implementations/TestLifetime.cs b/src/Umbraco.Tests.Integration/Implementations/TestLifetime.cs index a18360eff9..07f517e710 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestLifetime.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestLifetime.cs @@ -1,4 +1,7 @@ -using System.Threading; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; @@ -13,6 +16,4 @@ namespace Umbraco.Tests.Integration.Implementations public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask; } - - } diff --git a/src/Umbraco.Tests.Integration/Implementations/TestUmbracoBootPermissionChecker.cs b/src/Umbraco.Tests.Integration/Implementations/TestUmbracoBootPermissionChecker.cs index b4f876fc66..c032ad5551 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestUmbracoBootPermissionChecker.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestUmbracoBootPermissionChecker.cs @@ -1,4 +1,7 @@ -using Umbraco.Core.Runtime; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Umbraco.Core.Runtime; namespace Umbraco.Tests.Integration.Implementations { diff --git a/src/Umbraco.Tests.Integration/RuntimeTests.cs b/src/Umbraco.Tests.Integration/RuntimeTests.cs index 258f1992ff..cdb453ac90 100644 --- a/src/Umbraco.Tests.Integration/RuntimeTests.cs +++ b/src/Umbraco.Tests.Integration/RuntimeTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; @@ -17,7 +20,6 @@ using Umbraco.Web.Common.DependencyInjection; namespace Umbraco.Tests.Integration { - [TestFixture] public class RuntimeTests { @@ -43,16 +45,15 @@ namespace Umbraco.Tests.Integration { var testHelper = new TestHelper(); - var hostBuilder = new HostBuilder() + IHostBuilder hostBuilder = new HostBuilder() .ConfigureServices((hostContext, services) => { - var webHostEnvironment = testHelper.GetWebHostEnvironment(); + Microsoft.AspNetCore.Hosting.IWebHostEnvironment webHostEnvironment = testHelper.GetWebHostEnvironment(); services.AddSingleton(testHelper.DbProviderFactoryCreator); services.AddRequiredNetCoreServices(testHelper, webHostEnvironment); // Add it! - - var typeLoader = services.AddTypeLoader( + TypeLoader typeLoader = services.AddTypeLoader( GetType().Assembly, webHostEnvironment, testHelper.GetHostingEnvironment(), @@ -61,8 +62,7 @@ namespace Umbraco.Tests.Integration hostContext.Configuration, testHelper.Profiler); - var builder = new UmbracoBuilder(services, hostContext.Configuration, typeLoader, - testHelper.ConsoleLoggerFactory); + var builder = new UmbracoBuilder(services, hostContext.Configuration, typeLoader, testHelper.ConsoleLoggerFactory); builder.Services.AddUnique(AppCaches.NoCache); builder.AddConfiguration() .AddUmbracoCore() @@ -72,15 +72,14 @@ namespace Umbraco.Tests.Integration services.AddRouting(); // LinkGenerator }); - var host = await hostBuilder.StartAsync(); + IHost host = await hostBuilder.StartAsync(); var app = new ApplicationBuilder(host.Services); app.UseUmbracoCore(); - // assert results - var runtimeState = app.ApplicationServices.GetRequiredService(); - var mainDom = app.ApplicationServices.GetRequiredService(); + IRuntimeState runtimeState = app.ApplicationServices.GetRequiredService(); + IMainDom mainDom = app.ApplicationServices.GetRequiredService(); Assert.IsTrue(mainDom.IsMainDom); Assert.IsNull(runtimeState.BootFailedException); @@ -110,6 +109,7 @@ namespace Umbraco.Tests.Integration public class MyComponent : IComponent { public static bool IsInit { get; private set; } + public static bool IsTerminated { get; private set; } private readonly ILogger _logger; @@ -136,6 +136,4 @@ namespace Umbraco.Tests.Integration } } } - - } diff --git a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/BackOfficeAssetsControllerTests.cs b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/BackOfficeAssetsControllerTests.cs index 9d49ec22fa..f519d939b8 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/BackOfficeAssetsControllerTests.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/BackOfficeAssetsControllerTests.cs @@ -1,7 +1,10 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Net; +using System.Net.Http; using System.Threading.Tasks; using NUnit.Framework; -using Umbraco.Tests.Testing; using Umbraco.Web.BackOffice.Controllers; namespace Umbraco.Tests.Integration.TestServerTest.Controllers @@ -13,10 +16,10 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers public async Task EnsureSuccessStatusCode() { // Arrange - var url = PrepareUrl(x=>x.GetSupportedLocales()); + string url = PrepareUrl(x => x.GetSupportedLocales()); // Act - var response = await Client.GetAsync(url); + HttpResponseMessage response = await Client.GetAsync(url); // Assert Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); diff --git a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/ContentControllerTests.cs b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/ContentControllerTests.cs index f9d5d9f7da..cd7095ba75 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/ContentControllerTests.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/ContentControllerTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Linq; using System.Net; using System.Net.Http; @@ -18,14 +21,13 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [TestFixture] public class ContentControllerTests : UmbracoTestServerTestBase { - /// /// Returns 404 if the content wasn't found based on the ID specified /// [Test] public async Task PostSave_Validate_Existing_Content() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); // Add another language localizationService.Save(new LanguageBuilder() @@ -33,12 +35,12 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -51,7 +53,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -61,31 +63,29 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build(); contentService.SaveAndPublish(content); - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .WithId(-1337) // HERE We overwrite the Id, so we don't expect to find it on the server .Build(); // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - // Assert.AreEqual(")]}',\n{\"Message\":\"content was not found\"}", response.Item1.Content.ReadAsStringAsync().Result); - // - // //var obj = JsonConvert.DeserializeObject>(response.Item2); - // //Assert.AreEqual(0, obj.TotalItems); + //// Assert.AreEqual(")]}',\n{\"Message\":\"content was not found\"}", response.Item1.Content.ReadAsStringAsync().Result); + //// + //// //var obj = JsonConvert.DeserializeObject>(response.Item2); + //// //Assert.AreEqual(0, obj.TotalItems); } [Test] public async Task PostSave_Validate_At_Least_One_Variant_Flagged_For_Saving() { - - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); // Add another language localizationService.Save(new LanguageBuilder() @@ -93,11 +93,11 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentTypeService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -110,8 +110,8 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var contentService = GetRequiredService(); - var content = new ContentBuilder() + IContentService contentService = GetRequiredService(); + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -121,7 +121,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build(); contentService.SaveAndPublish(content); - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .Build(); @@ -133,20 +133,19 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers }); // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); Assert.AreEqual(AngularJsonMediaTypeFormatter.XsrfPrefix + "{\"Message\":\"No variants flagged for saving\"}", body); }); - } /// @@ -155,7 +154,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostSave_Validate_Properties_Exist() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); // Add another language localizationService.Save(new LanguageBuilder() @@ -163,12 +162,12 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -181,7 +180,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -191,7 +190,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build(); contentService.SaveAndPublish(content); - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithId(content.Id) .WithContentTypeAlias(content.ContentType.Alias) .AddVariant() @@ -203,15 +202,14 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Done() .Build(); - // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); @@ -221,20 +219,20 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostSave_Simple_Invariant() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - //Add another language + // Add another language localizationService.Save(new LanguageBuilder() .WithCultureInfo("da-DK") .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -247,7 +245,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -256,49 +254,46 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Done() .Build(); contentService.SaveAndPublish(content); - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .Build(); - // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, body); - var display = JsonConvert.DeserializeObject(body); + ContentItemDisplay display = JsonConvert.DeserializeObject(body); Assert.AreEqual(1, display.Variants.Count()); }); - } [Test] public async Task PostSave_Validate_Empty_Name() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - //Add another language + // Add another language localizationService.Save(new LanguageBuilder() .WithCultureInfo("da-DK") .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -311,7 +306,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) @@ -322,27 +317,25 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentService.SaveAndPublish(content); content.Name = null; // Removes the name of one of the variants to force an error - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .Build(); - // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); - var display = JsonConvert.DeserializeObject(body); + ContentItemDisplay display = JsonConvert.DeserializeObject(body); Assert.AreEqual(1, display.Errors.Count(), string.Join(",", display.Errors)); CollectionAssert.Contains(display.Errors.Keys, "Variants[0].Name"); }); @@ -351,20 +344,20 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostSave_Validate_Variants_Empty_Name() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - //Add another language + // Add another language localizationService.Save(new LanguageBuilder() .WithCultureInfo("da-DK") .WithIsDefault(false) .Build()); - var url = PrepareUrl(x => x.PostSave(null)); + string url = PrepareUrl(x => x.PostSave(null)); - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); - var contentType = new ContentTypeBuilder() + IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") @@ -377,7 +370,7 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentTypeService.Save(contentType); - var content = new ContentBuilder() + Content content = new ContentBuilder() .WithId(0) .WithCultureName("en-US", "English") .WithCultureName("da-DK", "Danish") @@ -389,30 +382,27 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers contentService.SaveAndPublish(content); content.CultureInfos[0].Name = null; // Removes the name of one of the variants to force an error - var model = new ContentItemSaveBuilder() + ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .Build(); // Act - var response = await Client.PostAsync(url, new MultipartFormDataContent + HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); - var display = JsonConvert.DeserializeObject(body); + ContentItemDisplay display = JsonConvert.DeserializeObject(body); Assert.AreEqual(2, display.Errors.Count()); CollectionAssert.Contains(display.Errors.Keys, "Variants[0].Name"); CollectionAssert.Contains(display.Errors.Keys, "_content_variant_en-US_null_"); }); - - } - } } diff --git a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/TemplateQueryControllerTests.cs b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/TemplateQueryControllerTests.cs index 747e99191b..8a558c53d4 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/TemplateQueryControllerTests.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/TemplateQueryControllerTests.cs @@ -1,6 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using System.Net; +using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -20,12 +24,12 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task GetContentTypes__Ensure_camel_case() { - var url = PrepareUrl(x => x.GetContentTypes()); + string url = PrepareUrl(x => x.GetContentTypes()); // Act - var response = await Client.GetAsync(url); + HttpResponseMessage response = await Client.GetAsync(url); - var body = await response.Content.ReadAsStringAsync(); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); @@ -36,17 +40,15 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers Assert.DoesNotThrow(() => JsonConvert.DeserializeObject(body)); - var jtokens = JsonConvert.DeserializeObject(body); - foreach (var jToken in jtokens) + JToken[] jtokens = JsonConvert.DeserializeObject(body); + foreach (JToken jToken in jtokens) { - var alias = nameof(ContentTypeModel.Alias); - var camelCaseAlias = alias.ToCamelCase(); + string alias = nameof(ContentTypeModel.Alias); + string camelCaseAlias = alias.ToCamelCase(); Assert.IsNotNull(jToken.Value(camelCaseAlias), $"'{jToken}' do not contain the key '{camelCaseAlias}' in the expected casing"); Assert.IsNull(jToken.Value(alias), $"'{jToken}' do contain the key '{alias}', which was not expect in that casing"); } }); - - } } } diff --git a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/UsersControllerTests.cs b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/UsersControllerTests.cs index c001eb2d92..fbba385cdc 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/Controllers/UsersControllerTests.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/Controllers/UsersControllerTests.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.Net; @@ -28,11 +31,11 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task Save_User() { - var url = PrepareUrl(x => x.PostSaveUser(null)); + string url = PrepareUrl(x => x.PostSaveUser(null)); - var userService = GetRequiredService(); + IUserService userService = GetRequiredService(); - var user = new UserBuilder() + User user = new UserBuilder() .AddUserGroup() .WithAlias("writer") // Needs to be an existing alias .Done() @@ -49,101 +52,102 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers Name = user.Name, UserGroups = user.Groups.Select(x => x.Alias).ToArray() }; + // Act - var response = await Client.PostAsync(url, - new StringContent(JsonConvert.SerializeObject(userSave), Encoding.UTF8, - MediaTypeNames.Application.Json)); + HttpResponseMessage response = await Client.PostAsync( + url, + new StringContent(JsonConvert.SerializeObject(userSave), Encoding.UTF8, MediaTypeNames.Application.Json)); // Assert - Assert.Multiple(() => { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + string body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); - var actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings + UserDisplay actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings { ContractResolver = new IgnoreRequiredAttributesResolver() }); Assert.AreEqual(userSave.Name, actual.Name); Assert.AreEqual(userSave.Id, actual.Id); Assert.AreEqual(userSave.Email, actual.Email); - var userGroupAliases = actual.UserGroups.Select(x => x.Alias).ToArray(); + string[] userGroupAliases = actual.UserGroups.Select(x => x.Alias).ToArray(); CollectionAssert.AreEquivalent(userSave.UserGroups, userGroupAliases); }); } [Test] - public async Task GetPagedUsers_Empty() - { - //We get page 2 to force an empty response because there always in the useradmin user - var url = PrepareUrl(x => x.GetPagedUsers(2, 10, "username", Direction.Ascending, null, null, string.Empty)); + public async Task GetPagedUsers_Empty() + { + // We get page 2 to force an empty response because there always in the useradmin user + string url = PrepareUrl(x => x.GetPagedUsers(2, 10, "username", Direction.Ascending, null, null, string.Empty)); - // Act - var response = await Client.GetAsync(url); + // Act + HttpResponseMessage response = await Client.GetAsync(url); - var body = await response.Content.ReadAsStringAsync(); - body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject>(body, new JsonSerializerSettings - { - ContractResolver = new IgnoreRequiredAttributesResolver() - }); - Assert.Multiple(() => - { - Assert.IsNotNull(actual); - Assert.AreEqual(1, actual.TotalItems); - CollectionAssert.IsEmpty(actual.Items); - }); - } + string body = await response.Content.ReadAsStringAsync(); + body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + PagedResult actual = JsonConvert.DeserializeObject>(body, new JsonSerializerSettings + { + ContractResolver = new IgnoreRequiredAttributesResolver() + }); + Assert.Multiple(() => + { + Assert.IsNotNull(actual); + Assert.AreEqual(1, actual.TotalItems); + CollectionAssert.IsEmpty(actual.Items); + }); + } - [Test] - public async Task GetPagedUsers_multiple_pages() - { - var totalNumberOfUsers = 11; - var pageSize = totalNumberOfUsers - 1; - var url = PrepareUrl(x => x.GetPagedUsers(1, pageSize, "username", Direction.Ascending, null, null, string.Empty)); + [Test] + public async Task GetPagedUsers_multiple_pages() + { + int totalNumberOfUsers = 11; + int pageSize = totalNumberOfUsers - 1; + string url = PrepareUrl(x => x.GetPagedUsers(1, pageSize, "username", Direction.Ascending, null, null, string.Empty)); - var userService = GetRequiredService(); + IUserService userService = GetRequiredService(); - for (int i = 1; i < totalNumberOfUsers; i++) // We already has admin user = -1, so we start from 1 - { - var user = new UserBuilder() + // We already has admin user = -1, so we start from 1. + for (int i = 1; i < totalNumberOfUsers; i++) + { + User user = new UserBuilder() .WithName($"Test user {i}") .AddUserGroup() .WithAlias("writer") // Needs to be an existing alias .Done() .Build(); - userService.Save(user); - } - - // Act - var response = await Client.GetAsync(url); - - var body = await response.Content.ReadAsStringAsync(); - body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject>(body, new JsonSerializerSettings - { - ContractResolver = new IgnoreRequiredAttributesResolver() - }); - Assert.Multiple(() => - { - Assert.IsNotNull(actual); - Assert.AreEqual(totalNumberOfUsers, actual.TotalItems); - Assert.AreEqual(pageSize, actual.Items.Count()); - }); - } - - [Test] - public async Task PostUnlockUsers_When_UserIds_Not_Supplied_Expect_Ok_Response() - { - var url = PrepareUrl(x => x.PostUnlockUsers(Array.Empty())); + userService.Save(user); + } // Act - var response = await Client.PostAsync(url, new StringContent(string.Empty)); + HttpResponseMessage response = await Client.GetAsync(url); + + string body = await response.Content.ReadAsStringAsync(); + body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + PagedResult actual = JsonConvert.DeserializeObject>(body, new JsonSerializerSettings + { + ContractResolver = new IgnoreRequiredAttributesResolver() + }); + Assert.Multiple(() => + { + Assert.IsNotNull(actual); + Assert.AreEqual(totalNumberOfUsers, actual.TotalItems); + Assert.AreEqual(pageSize, actual.Items.Count()); + }); + } + + [Test] + public async Task PostUnlockUsers_When_UserIds_Not_Supplied_Expect_Ok_Response() + { + string url = PrepareUrl(x => x.PostUnlockUsers(Array.Empty())); + + // Act + HttpResponseMessage response = await Client.PostAsync(url, new StringContent(string.Empty)); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } @@ -151,31 +155,28 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostUnlockUsers_When_User_Does_Not_Exist_Expect_Zero_Users_Message() { - var userId = 42; // Must not exist - var url = PrepareUrl(x => x.PostUnlockUsers(new []{userId})); + int userId = 42; // Must not exist + string url = PrepareUrl(x => x.PostUnlockUsers(new[] { userId })); // Act - var response = await Client.PostAsync(url, new StringContent(string.Empty)); - var body = await response.Content.ReadAsStringAsync(); + HttpResponseMessage response = await Client.PostAsync(url, new StringContent(string.Empty)); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings + SimpleNotificationModel actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings { ContractResolver = new IgnoreRequiredAttributesResolver() }); - Assert.Multiple(() => - { - Assert.AreEqual($"Unlocked 0 users", actual.Message); - }); + Assert.Multiple(() => Assert.AreEqual($"Unlocked 0 users", actual.Message)); } [Test] public async Task PostUnlockUsers_When_One_UserId_Supplied_Expect_User_Locked_Out_With_Correct_Response_Message() { - var userService = GetRequiredService(); + IUserService userService = GetRequiredService(); - var user = new UserBuilder() + User user = new UserBuilder() .AddUserGroup() .WithAlias("writer") // Needs to be an existing alias .Done() @@ -183,14 +184,14 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build(); userService.Save(user); - var url = PrepareUrl(x => x.PostUnlockUsers(new []{user.Id})); + string url = PrepareUrl(x => x.PostUnlockUsers(new[] { user.Id })); // Act - var response = await Client.PostAsync(url, new StringContent(string.Empty)); - var body = await response.Content.ReadAsStringAsync(); + HttpResponseMessage response = await Client.PostAsync(url, new StringContent(string.Empty)); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings + SimpleNotificationModel actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings { ContractResolver = new IgnoreRequiredAttributesResolver() }); @@ -205,8 +206,8 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers [Test] public async Task PostUnlockUsers_When_Multiple_UserIds_Supplied_Expect_User_Locked_Out_With_Correct_Response_Message() { - var numberOfUsers = 3; - var userService = GetRequiredService(); + int numberOfUsers = 3; + IUserService userService = GetRequiredService(); var users = new List(); for (int i = 0; i < numberOfUsers; i++) @@ -222,19 +223,19 @@ namespace Umbraco.Tests.Integration.TestServerTest.Controllers .Build()); } - foreach (var user in users) + foreach (IUser user in users) { userService.Save(user); } - var url = PrepareUrl(x => x.PostUnlockUsers(users.Select(x=>x.Id).ToArray())); + string url = PrepareUrl(x => x.PostUnlockUsers(users.Select(x => x.Id).ToArray())); // Act - var response = await Client.PostAsync(url, new StringContent(string.Empty)); - var body = await response.Content.ReadAsStringAsync(); + HttpResponseMessage response = await Client.PostAsync(url, new StringContent(string.Empty)); + string body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings + SimpleNotificationModel actual = JsonConvert.DeserializeObject(body, new JsonSerializerSettings { ContractResolver = new IgnoreRequiredAttributesResolver() }); diff --git a/src/Umbraco.Tests.Integration/TestServerTest/TestAuthHandler.cs b/src/Umbraco.Tests.Integration/TestServerTest/TestAuthHandler.cs index ab5821c81c..22f4b7e989 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/TestAuthHandler.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/TestAuthHandler.cs @@ -1,4 +1,8 @@ -using System.Text.Encodings.Web; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Security.Claims; +using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; @@ -19,21 +23,27 @@ namespace Umbraco.Tests.Integration.TestServerTest private readonly IBackOfficeSignInManager _backOfficeSignInManager; private readonly BackOfficeIdentityUser _fakeUser; - public TestAuthHandler(IOptionsMonitor options, - ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IBackOfficeSignInManager backOfficeSignInManager, IUserService userService, UmbracoMapper umbracoMapper) + + public TestAuthHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock, + IBackOfficeSignInManager backOfficeSignInManager, + IUserService userService, + UmbracoMapper umbracoMapper) : base(options, logger, encoder, clock) { _backOfficeSignInManager = backOfficeSignInManager; - var user = userService.GetUserById(Constants.Security.SuperUserId); + IUser user = userService.GetUserById(Constants.Security.SuperUserId); _fakeUser = umbracoMapper.Map(user); _fakeUser.SecurityStamp = "Needed"; } protected override async Task HandleAuthenticateAsync() { - - var principal = await _backOfficeSignInManager.CreateUserPrincipalAsync(_fakeUser); + ClaimsPrincipal principal = await _backOfficeSignInManager.CreateUserPrincipalAsync(_fakeUser); var ticket = new AuthenticationTicket(principal, TestAuthenticationScheme); return AuthenticateResult.Success(ticket); diff --git a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoBuilderExtensions.cs b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoBuilderExtensions.cs index 796f9a8669..edba48c427 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoBuilderExtensions.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoBuilderExtensions.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using Moq; using Umbraco.Core; using Umbraco.Core.Cache; diff --git a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs index ef3735032e..39d1a0f34c 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Linq.Expressions; using System.Net.Http; @@ -13,6 +16,7 @@ using Microsoft.Extensions.Hosting; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; +using Umbraco.Core.Composing; using Umbraco.Core.DependencyInjection; using Umbraco.Extensions; using Umbraco.Infrastructure.PublishedCache.DependencyInjection; @@ -42,15 +46,13 @@ namespace Umbraco.Tests.Integration.TestServerTest // additional host configuration for web server integration tests Factory = factory.WithWebHostBuilder(builder => - { + // Executes after the standard ConfigureServices method builder.ConfigureTestServices(services => - { + // Add a test auth scheme with a test auth handler to authn and assign the user services.AddAuthentication(TestAuthHandler.TestAuthenticationScheme) - .AddScheme(TestAuthHandler.TestAuthenticationScheme, options => { }); - }); - }); + .AddScheme(TestAuthHandler.TestAuthenticationScheme, options => { }))); Client = Factory.CreateClient(new WebApplicationFactoryClientOptions { @@ -62,21 +64,14 @@ namespace Umbraco.Tests.Integration.TestServerTest public override IHostBuilder CreateHostBuilder() { - var builder = base.CreateHostBuilder(); + IHostBuilder builder = base.CreateHostBuilder(); builder.ConfigureWebHost(builder => { // need to configure the IWebHostEnvironment too - builder.ConfigureServices((c, s) => - { - c.HostingEnvironment = TestHelper.GetWebHostEnvironment(); - }); + builder.ConfigureServices((c, s) => c.HostingEnvironment = TestHelper.GetWebHostEnvironment()); // call startup - builder.Configure(app => - { - Configure(app); - }); - + builder.Configure(app => Configure(app)); }).UseEnvironment(Environments.Development); return builder; @@ -90,11 +85,11 @@ namespace Umbraco.Tests.Integration.TestServerTest protected string PrepareUrl(Expression> methodSelector) where T : UmbracoApiController { - var url = LinkGenerator.GetUmbracoApiService(methodSelector); + string url = LinkGenerator.GetUmbracoApiService(methodSelector); - var backofficeSecurityFactory = GetRequiredService(); - var umbracoContextFactory = GetRequiredService(); - var httpContextAccessor = GetRequiredService(); + IBackOfficeSecurityFactory backofficeSecurityFactory = GetRequiredService(); + IUmbracoContextFactory umbracoContextFactory = GetRequiredService(); + IHttpContextAccessor httpContextAccessor = GetRequiredService(); httpContextAccessor.HttpContext = new DefaultHttpContext { @@ -122,7 +117,7 @@ namespace Umbraco.Tests.Integration.TestServerTest public override void ConfigureServices(IServiceCollection services) { services.AddTransient(); - var typeLoader = services.AddTypeLoader( + TypeLoader typeLoader = services.AddTypeLoader( GetType().Assembly, TestHelper.GetWebHostEnvironment(), TestHelper.GetHostingEnvironment(), diff --git a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoWebApplicationFactory.cs b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoWebApplicationFactory.cs index 256c5c59a9..5d923e583e 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoWebApplicationFactory.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoWebApplicationFactory.cs @@ -1,11 +1,14 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.Hosting; namespace Umbraco.Tests.Integration.TestServerTest { - - public class UmbracoWebApplicationFactory : WebApplicationFactory where TStartup : class + public class UmbracoWebApplicationFactory : WebApplicationFactory + where TStartup : class { private readonly Func _createHostBuilder; private readonly Action _beforeStart; diff --git a/src/Umbraco.Tests.Integration/Testing/BaseTestDatabase.cs b/src/Umbraco.Tests.Integration/Testing/BaseTestDatabase.cs index 52a0778a59..25fbc6ef59 100644 --- a/src/Umbraco.Tests.Integration/Testing/BaseTestDatabase.cs +++ b/src/Umbraco.Tests.Integration/Testing/BaseTestDatabase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -19,7 +22,7 @@ namespace Umbraco.Tests.Integration.Testing protected IUmbracoDatabaseFactory _databaseFactory; protected IList _testDatabases; - protected const int _threadCount = 2; + protected const int ThreadCount = 2; protected UmbracoDatabase.CommandInfo[] _cachedDatabaseInitCommands = new UmbracoDatabase.CommandInfo[0]; @@ -54,45 +57,43 @@ namespace Umbraco.Tests.Integration.Testing _prepareQueue.TryAdd(meta); } - protected void PrepareDatabase() - { + protected void PrepareDatabase() => Retry(10, () => - { - while (_prepareQueue.IsCompleted == false) { - TestDbMeta meta; - try + while (_prepareQueue.IsCompleted == false) { - meta = _prepareQueue.Take(); - } - catch (InvalidOperationException) - { - continue; - } + TestDbMeta meta; + try + { + meta = _prepareQueue.Take(); + } + catch (InvalidOperationException) + { + continue; + } - using (var conn = new SqlConnection(meta.ConnectionString)) - using (var cmd = conn.CreateCommand()) - { - conn.Open(); - ResetTestDatabase(cmd); + using (var conn = new SqlConnection(meta.ConnectionString)) + using (SqlCommand cmd = conn.CreateCommand()) + { + conn.Open(); + ResetTestDatabase(cmd); + + if (!meta.IsEmpty) + { + RebuildSchema(cmd, meta); + } + } if (!meta.IsEmpty) { - RebuildSchema(cmd, meta); + _readySchemaQueue.TryAdd(meta); + } + else + { + _readyEmptyQueue.TryAdd(meta); } } - - if (!meta.IsEmpty) - { - _readySchemaQueue.TryAdd(meta); - } - else - { - _readyEmptyQueue.TryAdd(meta); - } - } - }); - } + }); private void RebuildSchema(IDbCommand command, TestDbMeta meta) { @@ -100,12 +101,12 @@ namespace Umbraco.Tests.Integration.Testing { if (!_cachedDatabaseInitCommands.Any()) { - RebuildSchemaFirstTime(command, meta); + RebuildSchemaFirstTime(meta); return; } } - foreach (var dbCommand in _cachedDatabaseInitCommands) + foreach (UmbracoDatabase.CommandInfo dbCommand in _cachedDatabaseInitCommands) { if (dbCommand.Text.StartsWith("SELECT ")) { @@ -115,7 +116,7 @@ namespace Umbraco.Tests.Integration.Testing command.CommandText = dbCommand.Text; command.Parameters.Clear(); - foreach (var parameterInfo in dbCommand.Parameters) + foreach (UmbracoDatabase.ParameterInfo parameterInfo in dbCommand.Parameters) { AddParameter(command, parameterInfo); } @@ -124,7 +125,7 @@ namespace Umbraco.Tests.Integration.Testing } } - private void RebuildSchemaFirstTime(IDbCommand command, TestDbMeta meta) + private void RebuildSchemaFirstTime(TestDbMeta meta) { _databaseFactory.Configure(meta.ConnectionString, Core.Constants.DatabaseProviders.SqlServer); @@ -132,7 +133,7 @@ namespace Umbraco.Tests.Integration.Testing { database.LogCommands = true; - using (var transaction = database.GetTransaction()) + using (NPoco.ITransaction transaction = database.GetTransaction()) { var schemaCreator = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, new UmbracoVersion()); schemaCreator.InitializeDatabaseSchema(); @@ -150,7 +151,7 @@ namespace Umbraco.Tests.Integration.Testing command.CommandText = sql; command.Parameters.Clear(); - for (var i = 0; i < args.Length; i++) + for (int i = 0; i < args.Length; i++) { command.Parameters.AddWithValue("@" + i, args[i]); } @@ -158,7 +159,7 @@ namespace Umbraco.Tests.Integration.Testing protected static void AddParameter(IDbCommand cmd, UmbracoDatabase.ParameterInfo parameterInfo) { - var p = cmd.CreateParameter(); + IDbDataParameter p = cmd.CreateParameter(); p.ParameterName = parameterInfo.Name; p.Value = parameterInfo.Value; p.DbType = parameterInfo.DbType; @@ -169,7 +170,6 @@ namespace Umbraco.Tests.Integration.Testing protected static void ResetTestDatabase(IDbCommand cmd) { // https://stackoverflow.com/questions/536350 - cmd.CommandType = CommandType.Text; cmd.CommandText = @" declare @n char(1); @@ -196,7 +196,7 @@ namespace Umbraco.Tests.Integration.Testing protected static void Retry(int maxIterations, Action action) { - for (var i = 0; i < maxIterations; i++) + for (int i = 0; i < maxIterations; i++) { try { @@ -205,8 +205,7 @@ namespace Umbraco.Tests.Integration.Testing } catch (SqlException) { - - //Console.Error.WriteLine($"SqlException occured, but we try again {i+1}/{maxIterations}.\n{e}"); + // Console.Error.WriteLine($"SqlException occured, but we try again {i+1}/{maxIterations}.\n{e}"); // This can occur when there's a transaction deadlock which means (i think) that the database is still in use and hasn't been closed properly yet // so we need to just wait a little bit Thread.Sleep(100 * i); diff --git a/src/Umbraco.Tests.Integration/Testing/ITestDatabase.cs b/src/Umbraco.Tests.Integration/Testing/ITestDatabase.cs index 28d7e9c8bc..bdfde8d93b 100644 --- a/src/Umbraco.Tests.Integration/Testing/ITestDatabase.cs +++ b/src/Umbraco.Tests.Integration/Testing/ITestDatabase.cs @@ -1,9 +1,14 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + namespace Umbraco.Tests.Integration.Testing { public interface ITestDatabase { TestDbMeta AttachEmpty(); + TestDbMeta AttachSchema(); + void Detach(TestDbMeta id); } } diff --git a/src/Umbraco.Tests.Integration/Testing/IntegrationTestComponent.cs b/src/Umbraco.Tests.Integration/Testing/IntegrationTestComponent.cs index 69819c9bef..4950f87bd9 100644 --- a/src/Umbraco.Tests.Integration/Testing/IntegrationTestComponent.cs +++ b/src/Umbraco.Tests.Integration/Testing/IntegrationTestComponent.cs @@ -1,4 +1,7 @@ -using Examine; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Examine; using Examine.LuceneEngine.Providers; using Umbraco.Core.Composing; using Umbraco.Examine; @@ -12,15 +15,9 @@ namespace Umbraco.Tests.Integration.Testing { private readonly IExamineManager _examineManager; - public IntegrationTestComponent(IExamineManager examineManager) - { - _examineManager = examineManager; - } + public IntegrationTestComponent(IExamineManager examineManager) => _examineManager = examineManager; - public void Initialize() - { - ConfigureExamineIndexes(); - } + public void Initialize() => ConfigureExamineIndexes(); public void Terminate() { @@ -31,7 +28,7 @@ namespace Umbraco.Tests.Integration.Testing /// private void ConfigureExamineIndexes() { - foreach (var index in _examineManager.Indexes) + foreach (IIndex index in _examineManager.Indexes) { if (index is LuceneIndex luceneIndex) { diff --git a/src/Umbraco.Tests.Integration/Testing/IntegrationTestComposer.cs b/src/Umbraco.Tests.Integration/Testing/IntegrationTestComposer.cs index 39d74f8869..b196ea03bb 100644 --- a/src/Umbraco.Tests.Integration/Testing/IntegrationTestComposer.cs +++ b/src/Umbraco.Tests.Integration/Testing/IntegrationTestComposer.cs @@ -1,20 +1,20 @@ -using Moq; -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; -using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Moq; +using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.DependencyInjection; using Umbraco.Core.Cache; using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Models; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; @@ -24,7 +24,6 @@ using Umbraco.Examine; using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Web.Compose; using Umbraco.Web.PublishedCache.NuCache; -using Umbraco.Web.Scheduling; using Umbraco.Web.Search; namespace Umbraco.Tests.Integration.Testing @@ -65,30 +64,29 @@ namespace Umbraco.Tests.Integration.Testing /// Used to register a replacement for where the file sources are the ones within the netcore project so /// we don't need to copy files /// - /// private ILocalizedTextService GetLocalizedTextService(IServiceProvider factory) { - var globalSettings = factory.GetRequiredService>(); - var loggerFactory = factory.GetRequiredService(); - var appCaches = factory.GetRequiredService(); + IOptions globalSettings = factory.GetRequiredService>(); + ILoggerFactory loggerFactory = factory.GetRequiredService(); + AppCaches appCaches = factory.GetRequiredService(); var localizedTextService = new LocalizedTextService( new Lazy(() => { // get the src folder var currFolder = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); - while(!currFolder.Name.Equals("src", StringComparison.InvariantCultureIgnoreCase)) + while (!currFolder.Name.Equals("src", StringComparison.InvariantCultureIgnoreCase)) { currFolder = currFolder.Parent; } - var netcoreUI = currFolder.GetDirectories("Umbraco.Web.UI.NetCore", SearchOption.TopDirectoryOnly).First(); + + DirectoryInfo netcoreUI = currFolder.GetDirectories("Umbraco.Web.UI.NetCore", SearchOption.TopDirectoryOnly).First(); var mainLangFolder = new DirectoryInfo(Path.Combine(netcoreUI.FullName, globalSettings.Value.UmbracoPath.TrimStart("~/"), "config", "lang")); return new LocalizedTextServiceFileSources( loggerFactory.CreateLogger(), appCaches, mainLangFolder); - }), loggerFactory.CreateLogger()); @@ -98,8 +96,8 @@ namespace Umbraco.Tests.Integration.Testing // replace the default so there is no background index rebuilder private class TestBackgroundIndexRebuilder : BackgroundIndexRebuilder { - public TestBackgroundIndexRebuilder(IMainDom mainDom, IProfilingLogger profilingLogger , ILoggerFactory loggerFactory, IApplicationShutdownRegistry hostingEnvironment, IndexRebuilder indexRebuilder) - : base(mainDom, profilingLogger , loggerFactory, hostingEnvironment, indexRebuilder) + public TestBackgroundIndexRebuilder(IMainDom mainDom, IProfilingLogger profilingLogger, ILoggerFactory loggerFactory, IApplicationShutdownRegistry hostingEnvironment, IndexRebuilder indexRebuilder) + : base(mainDom, profilingLogger, loggerFactory, hostingEnvironment, indexRebuilder) { } @@ -112,48 +110,40 @@ namespace Umbraco.Tests.Integration.Testing private class NoopServerMessenger : IServerMessenger { public NoopServerMessenger() - { } + { + } public void PerformRefresh(ICacheRefresher refresher, TPayload[] payload) { - } public void PerformRefresh(ICacheRefresher refresher, Func getNumericId, params T[] instances) { - } public void PerformRefresh(ICacheRefresher refresher, Func getGuidId, params T[] instances) { - } public void PerformRemove(ICacheRefresher refresher, Func getNumericId, params T[] instances) { - } public void PerformRemove(ICacheRefresher refresher, params int[] numericIds) { - } public void PerformRefresh(ICacheRefresher refresher, params int[] numericIds) { - } public void PerformRefresh(ICacheRefresher refresher, params Guid[] guidIds) { - } public void PerformRefreshAll(ICacheRefresher refresher) { - } } - } } diff --git a/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs b/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs index 59a9b00215..5ae889d8fb 100644 --- a/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs +++ b/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Concurrent; using System.IO; @@ -16,19 +19,19 @@ namespace Umbraco.Tests.Integration.Testing public const string DatabaseName = "UmbracoTests"; private readonly LocalDb _localDb; - private static LocalDb.Instance _localDbInstance; - private static string _filesPath; + private static LocalDb.Instance s_localDbInstance; + private static string s_filesPath; public static LocalDbTestDatabase Instance { get; private set; } - //It's internal because `Umbraco.Core.Persistence.LocalDb` is internal + // It's internal because `Umbraco.Core.Persistence.LocalDb` is internal internal LocalDbTestDatabase(ILoggerFactory loggerFactory, LocalDb localDb, string filesPath, IUmbracoDatabaseFactory dbFactory) { _loggerFactory = loggerFactory; _databaseFactory = dbFactory; _localDb = localDb; - _filesPath = filesPath; + s_filesPath = filesPath; Instance = this; // For GlobalSetupTeardown.cs @@ -43,8 +46,8 @@ namespace Umbraco.Tests.Integration.Testing TestDbMeta.CreateWithoutConnectionString($"{DatabaseName}-4", true), }; - _localDbInstance = _localDb.GetInstance(InstanceName); - if (_localDbInstance != null) + s_localDbInstance = _localDb.GetInstance(InstanceName); + if (s_localDbInstance != null) { return; } @@ -54,30 +57,30 @@ namespace Umbraco.Tests.Integration.Testing throw new Exception("Failed to create a LocalDb instance."); } - _localDbInstance = _localDb.GetInstance(InstanceName); + s_localDbInstance = _localDb.GetInstance(InstanceName); } protected override void Initialize() { - var tempName = Guid.NewGuid().ToString("N"); - _localDbInstance.CreateDatabase(tempName, _filesPath); - _localDbInstance.DetachDatabase(tempName); + string tempName = Guid.NewGuid().ToString("N"); + s_localDbInstance.CreateDatabase(tempName, s_filesPath); + s_localDbInstance.DetachDatabase(tempName); _prepareQueue = new BlockingCollection(); _readySchemaQueue = new BlockingCollection(); _readyEmptyQueue = new BlockingCollection(); - for (var i = 0; i < _testDatabases.Count; i++) + for (int i = 0; i < _testDatabases.Count; i++) { - var meta = _testDatabases[i]; - var isLast = i == _testDatabases.Count - 1; + TestDbMeta meta = _testDatabases[i]; + bool isLast = i == _testDatabases.Count - 1; - _localDb.CopyDatabaseFiles(tempName, _filesPath, targetDatabaseName: meta.Name, overwrite: true, delete: isLast); - meta.ConnectionString = _localDbInstance.GetAttachedConnectionString(meta.Name, _filesPath); + _localDb.CopyDatabaseFiles(tempName, s_filesPath, targetDatabaseName: meta.Name, overwrite: true, delete: isLast); + meta.ConnectionString = s_localDbInstance.GetAttachedConnectionString(meta.Name, s_filesPath); _prepareQueue.Add(meta); } - for (var i = 0; i < _threadCount; i++) + for (int i = 0; i < ThreadCount; i++) { var thread = new Thread(PrepareDatabase); thread.Start(); @@ -93,34 +96,41 @@ namespace Umbraco.Tests.Integration.Testing _prepareQueue.CompleteAdding(); while (_prepareQueue.TryTake(out _)) - { } + { + } _readyEmptyQueue.CompleteAdding(); while (_readyEmptyQueue.TryTake(out _)) - { } + { + } _readySchemaQueue.CompleteAdding(); while (_readySchemaQueue.TryTake(out _)) - { } + { + } - if (_filesPath == null) + if (s_filesPath == null) { return; } - var filename = Path.Combine(_filesPath, DatabaseName).ToUpper(); + string filename = Path.Combine(s_filesPath, DatabaseName).ToUpper(); - foreach (var database in _localDbInstance.GetDatabases()) + foreach (string database in s_localDbInstance.GetDatabases()) { if (database.StartsWith(filename)) { - _localDbInstance.DropDatabase(database); + s_localDbInstance.DropDatabase(database); } } - foreach (var file in Directory.EnumerateFiles(_filesPath)) + foreach (string file in Directory.EnumerateFiles(s_filesPath)) { - if (file.EndsWith(".mdf") == false && file.EndsWith(".ldf") == false) continue; + if (file.EndsWith(".mdf") == false && file.EndsWith(".ldf") == false) + { + continue; + } + try { File.Delete(file); diff --git a/src/Umbraco.Tests.Integration/Testing/SqlDeveloperTestDatabase.cs b/src/Umbraco.Tests.Integration/Testing/SqlDeveloperTestDatabase.cs index 2e1f75cd45..7ab65c1e74 100644 --- a/src/Umbraco.Tests.Integration/Testing/SqlDeveloperTestDatabase.cs +++ b/src/Umbraco.Tests.Integration/Testing/SqlDeveloperTestDatabase.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Concurrent; using System.Data.SqlClient; @@ -6,7 +9,6 @@ using Microsoft.Extensions.Logging; using Umbraco.Core.Persistence; // ReSharper disable ConvertToUsingDeclaration - namespace Umbraco.Tests.Integration.Testing { /// @@ -46,13 +48,13 @@ namespace Umbraco.Tests.Integration.Testing _readySchemaQueue = new BlockingCollection(); _readyEmptyQueue = new BlockingCollection(); - foreach (var meta in _testDatabases) + foreach (TestDbMeta meta in _testDatabases) { CreateDatabase(meta); _prepareQueue.Add(meta); } - for (var i = 0; i < _threadCount; i++) + for (int i = 0; i < ThreadCount; i++) { var thread = new Thread(PrepareDatabase); thread.Start(); @@ -64,7 +66,7 @@ namespace Umbraco.Tests.Integration.Testing using (var connection = new SqlConnection(_masterConnectionString)) { connection.Open(); - using (var command = connection.CreateCommand()) + using (SqlCommand command = connection.CreateCommand()) { SetCommand(command, $@"CREATE DATABASE {LocalDb.QuotedName(meta.Name)}"); command.ExecuteNonQuery(); @@ -77,13 +79,13 @@ namespace Umbraco.Tests.Integration.Testing using (var connection = new SqlConnection(_masterConnectionString)) { connection.Open(); - using (var command = connection.CreateCommand()) + using (SqlCommand command = connection.CreateCommand()) { - SetCommand(command, $@" + string sql = $@" ALTER DATABASE{LocalDb.QuotedName(meta.Name)} SET SINGLE_USER - WITH ROLLBACK IMMEDIATE - "); + WITH ROLLBACK IMMEDIATE"; + SetCommand(command, sql); command.ExecuteNonQuery(); SetCommand(command, $@"DROP DATABASE {LocalDb.QuotedName(meta.Name)}"); @@ -95,18 +97,26 @@ namespace Umbraco.Tests.Integration.Testing public void Finish() { if (_prepareQueue == null) + { return; + } _prepareQueue.CompleteAdding(); - while (_prepareQueue.TryTake(out _)) { } + while (_prepareQueue.TryTake(out _)) + { + } _readyEmptyQueue.CompleteAdding(); - while (_readyEmptyQueue.TryTake(out _)) { } + while (_readyEmptyQueue.TryTake(out _)) + { + } _readySchemaQueue.CompleteAdding(); - while (_readySchemaQueue.TryTake(out _)) { } + while (_readySchemaQueue.TryTake(out _)) + { + } - foreach (var testDatabase in _testDatabases) + foreach (TestDbMeta testDatabase in _testDatabases) { Drop(testDatabase); } diff --git a/src/Umbraco.Tests.Integration/Testing/TestDatabaseFactory.cs b/src/Umbraco.Tests.Integration/Testing/TestDatabaseFactory.cs index 60c767e17e..6d7e88b5b0 100644 --- a/src/Umbraco.Tests.Integration/Testing/TestDatabaseFactory.cs +++ b/src/Umbraco.Tests.Integration/Testing/TestDatabaseFactory.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.IO; using Microsoft.Extensions.Logging; @@ -9,7 +12,7 @@ namespace Umbraco.Tests.Integration.Testing { public static ITestDatabase Create(string filesPath, ILoggerFactory loggerFactory, TestUmbracoDatabaseFactoryProvider dbFactory) { - var connectionString = Environment.GetEnvironmentVariable("UmbracoIntegrationTestConnectionString"); + string connectionString = Environment.GetEnvironmentVariable("UmbracoIntegrationTestConnectionString"); return string.IsNullOrEmpty(connectionString) ? CreateLocalDb(filesPath, loggerFactory, dbFactory) diff --git a/src/Umbraco.Tests.Integration/Testing/TestDbMeta.cs b/src/Umbraco.Tests.Integration/Testing/TestDbMeta.cs index 83702db8e5..ea6f7d1c72 100644 --- a/src/Umbraco.Tests.Integration/Testing/TestDbMeta.cs +++ b/src/Umbraco.Tests.Integration/Testing/TestDbMeta.cs @@ -1,10 +1,12 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Text.RegularExpressions; namespace Umbraco.Tests.Integration.Testing { public class TestDbMeta { - public string Name { get; } public bool IsEmpty { get; } @@ -20,20 +22,16 @@ namespace Umbraco.Tests.Integration.Testing private static string ConstructConnectionString(string masterConnectionString, string databaseName) { - var prefix = Regex.Replace(masterConnectionString, "Database=.+?;", string.Empty); - var connectionString = $"{prefix};Database={databaseName};"; + string prefix = Regex.Replace(masterConnectionString, "Database=.+?;", string.Empty); + string connectionString = $"{prefix};Database={databaseName};"; return connectionString.Replace(";;", ";"); } - public static TestDbMeta CreateWithMasterConnectionString(string name, bool isEmpty, string masterConnectionString) - { - return new TestDbMeta(name, isEmpty, ConstructConnectionString(masterConnectionString, name)); - } + public static TestDbMeta CreateWithMasterConnectionString(string name, bool isEmpty, string masterConnectionString) => + new TestDbMeta(name, isEmpty, ConstructConnectionString(masterConnectionString, name)); // LocalDb mdf funtimes - public static TestDbMeta CreateWithoutConnectionString(string name, bool isEmpty) - { - return new TestDbMeta(name, isEmpty, null); - } + public static TestDbMeta CreateWithoutConnectionString(string name, bool isEmpty) => + new TestDbMeta(name, isEmpty, null); } } diff --git a/src/Umbraco.Tests.Integration/Testing/TestUmbracoDatabaseFactoryProvider.cs b/src/Umbraco.Tests.Integration/Testing/TestUmbracoDatabaseFactoryProvider.cs index 3eb3757207..3eb70331b1 100644 --- a/src/Umbraco.Tests.Integration/Testing/TestUmbracoDatabaseFactoryProvider.cs +++ b/src/Umbraco.Tests.Integration/Testing/TestUmbracoDatabaseFactoryProvider.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; diff --git a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs index d8f27d27a7..cfb940e158 100644 --- a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs +++ b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Data.Common; @@ -36,7 +39,6 @@ using Umbraco.Web.Common.DependencyInjection; namespace Umbraco.Tests.Integration.Testing { - /// /// Abstract class for integration tests /// @@ -48,7 +50,7 @@ namespace Umbraco.Tests.Integration.Testing public abstract class UmbracoIntegrationTest { private List _testTeardown = null; - private List _fixtureTeardown = new List(); + private readonly List _fixtureTeardown = new List(); public void OnTestTearDown(Action tearDown) { @@ -65,7 +67,7 @@ namespace Umbraco.Tests.Integration.Testing [OneTimeTearDown] public void FixtureTearDown() { - foreach (var a in _fixtureTeardown) + foreach (Action a in _fixtureTeardown) { a(); } @@ -76,7 +78,7 @@ namespace Umbraco.Tests.Integration.Testing { if (_testTeardown != null) { - foreach (var a in _testTeardown) + foreach (Action a in _testTeardown) { a(); } @@ -93,22 +95,18 @@ namespace Umbraco.Tests.Integration.Testing } [TearDown] - public virtual void TearDown_Logging() - { + public virtual void TearDown_Logging() => TestContext.Progress.Write($" {TestContext.CurrentContext.Result.Outcome.Status}"); - } [SetUp] - public virtual void SetUp_Logging() - { + public virtual void SetUp_Logging() => TestContext.Progress.Write($"Start test {TestCount++}: {TestContext.CurrentContext.Test.Name}"); - } [SetUp] public virtual void Setup() { InMemoryConfiguration[Constants.Configuration.ConfigGlobal + ":" + nameof(GlobalSettings.InstallEmptyDatabase)] = "true"; - var hostBuilder = CreateHostBuilder(); + IHostBuilder hostBuilder = CreateHostBuilder(); IHost host = hostBuilder.Build(); BeforeHostStart(host); @@ -124,8 +122,6 @@ namespace Umbraco.Tests.Integration.Testing UseTestDatabase(Services); } - #region Generic Host Builder and Runtime - private ILoggerFactory CreateLoggerFactory() { try @@ -137,7 +133,7 @@ namespace Umbraco.Tests.Integration.Testing case UmbracoTestOptions.Logger.Serilog: return Microsoft.Extensions.Logging.LoggerFactory.Create(builder => { - var path = Path.Combine(TestHelper.WorkingDirectory, "logs", "umbraco_integration_tests_.txt"); + string path = Path.Combine(TestHelper.WorkingDirectory, "logs", "umbraco_integration_tests_.txt"); Log.Logger = new LoggerConfiguration() .WriteTo.File(path, rollingInterval: RollingInterval.Day) @@ -146,7 +142,7 @@ namespace Umbraco.Tests.Integration.Testing builder.AddSerilog(Log.Logger); }); case UmbracoTestOptions.Logger.Console: - return Microsoft.Extensions.Logging.LoggerFactory.Create(builder => { builder.AddConsole(); }); + return Microsoft.Extensions.Logging.LoggerFactory.Create(builder => builder.AddConsole()); } } catch @@ -162,12 +158,13 @@ namespace Umbraco.Tests.Integration.Testing /// public virtual IHostBuilder CreateHostBuilder() { - var hostBuilder = Host.CreateDefaultBuilder() + IHostBuilder hostBuilder = Host.CreateDefaultBuilder() + // IMPORTANT: We Cannot use UseStartup, there's all sorts of threads about this with testing. Although this can work // if you want to setup your tests this way, it is a bit annoying to do that as the WebApplicationFactory will // create separate Host instances. So instead of UseStartup, we just call ConfigureServices/Configure ourselves, // and in the case of the UmbracoTestServerTestBase it will use the ConfigureWebHost to Configure the IApplicationBuilder directly. - //.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(GetType()); }) + // .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(GetType()); }) .ConfigureAppConfiguration((context, configBuilder) => { context.HostingEnvironment = TestHelper.GetWebHostEnvironment(); @@ -191,18 +188,15 @@ namespace Umbraco.Tests.Integration.Testing return hostBuilder; } - #endregion - public virtual void ConfigureServices(IServiceCollection services) { services.AddSingleton(TestHelper.DbProviderFactoryCreator); services.AddTransient(); - var webHostEnvironment = TestHelper.GetWebHostEnvironment(); + Microsoft.AspNetCore.Hosting.IWebHostEnvironment webHostEnvironment = TestHelper.GetWebHostEnvironment(); services.AddRequiredNetCoreServices(TestHelper, webHostEnvironment); // Add it! - - var typeLoader = services.AddTypeLoader( + Core.Composing.TypeLoader typeLoader = services.AddTypeLoader( GetType().Assembly, webHostEnvironment, TestHelper.GetHostingEnvironment(), @@ -212,7 +206,6 @@ namespace Umbraco.Tests.Integration.Testing TestHelper.Profiler); var builder = new UmbracoBuilder(services, Configuration, typeLoader, TestHelper.ConsoleLoggerFactory); - builder.Services.AddLogger(TestHelper.GetHostingEnvironment(), TestHelper.GetLoggingConfiguration(), Configuration); builder.AddConfiguration() @@ -236,11 +229,10 @@ namespace Umbraco.Tests.Integration.Testing CustomTestSetup(builder); } - protected virtual AppCaches GetAppCaches() - { + protected virtual AppCaches GetAppCaches() => + // Disable caches for integration tests - return AppCaches.NoCache; - } + AppCaches.NoCache; public virtual void Configure(IApplicationBuilder app) { @@ -253,18 +245,16 @@ namespace Umbraco.Tests.Integration.Testing app.UseUmbracoCore(); // This no longer starts CoreRuntime, it's very fast } - #region LocalDb - - private static readonly object _dbLocker = new object(); - private static ITestDatabase _dbInstance; - private static TestDbMeta _fixtureDbMeta; + private static readonly object s_dbLocker = new object(); + private static ITestDatabase s_dbInstance; + private static TestDbMeta s_fixtureDbMeta; protected void UseTestDatabase(IServiceProvider serviceProvider) { - var state = serviceProvider.GetRequiredService(); - var testDatabaseFactoryProvider = serviceProvider.GetRequiredService(); - var databaseFactory = serviceProvider.GetRequiredService(); - var loggerFactory = serviceProvider.GetRequiredService(); + IRuntimeState state = serviceProvider.GetRequiredService(); + TestUmbracoDatabaseFactoryProvider testDatabaseFactoryProvider = serviceProvider.GetRequiredService(); + IUmbracoDatabaseFactory databaseFactory = serviceProvider.GetRequiredService(); + ILoggerFactory loggerFactory = serviceProvider.GetRequiredService(); // This will create a db, install the schema and ensure the app is configured to run SetupTestDatabase(testDatabaseFactoryProvider, databaseFactory, loggerFactory, state, TestHelper.WorkingDirectory); @@ -278,16 +268,16 @@ namespace Umbraco.Tests.Integration.Testing /// private static ITestDatabase GetOrCreateDatabase(string filesPath, ILoggerFactory loggerFactory, TestUmbracoDatabaseFactoryProvider dbFactory) { - lock (_dbLocker) + lock (s_dbLocker) { - if (_dbInstance != null) + if (s_dbInstance != null) { - return _dbInstance; + return s_dbInstance; } - _dbInstance = TestDatabaseFactory.Create(filesPath, loggerFactory, dbFactory); + s_dbInstance = TestDatabaseFactory.Create(filesPath, loggerFactory, dbFactory); - return _dbInstance; + return s_dbInstance; } } @@ -309,9 +299,9 @@ namespace Umbraco.Tests.Integration.Testing // need to manually register this factory DbProviderFactories.RegisterFactory(Constants.DbProviderNames.SqlServer, SqlClientFactory.Instance); - var dbFilePath = Path.Combine(workingDirectory, "LocalDb"); + string dbFilePath = Path.Combine(workingDirectory, "LocalDb"); - var db = GetOrCreateDatabase(dbFilePath, loggerFactory, testUmbracoDatabaseFactoryProvider); + ITestDatabase db = GetOrCreateDatabase(dbFilePath, loggerFactory, testUmbracoDatabaseFactoryProvider); switch (TestOptions.Database) { @@ -347,13 +337,13 @@ namespace Umbraco.Tests.Integration.Testing { // New DB + Schema TestDbMeta newSchemaFixtureDbMeta = db.AttachSchema(); - _fixtureDbMeta = newSchemaFixtureDbMeta; + s_fixtureDbMeta = newSchemaFixtureDbMeta; // Add teardown callback OnFixtureTearDown(() => db.Detach(newSchemaFixtureDbMeta)); } - ConfigureTestDatabaseFactory(_fixtureDbMeta, databaseFactory, runtimeState); + ConfigureTestDatabaseFactory(s_fixtureDbMeta, databaseFactory, runtimeState); break; case UmbracoTestOptions.Database.NewEmptyPerFixture: @@ -364,13 +354,13 @@ namespace Umbraco.Tests.Integration.Testing { // New DB + Schema TestDbMeta newEmptyFixtureDbMeta = db.AttachEmpty(); - _fixtureDbMeta = newEmptyFixtureDbMeta; + s_fixtureDbMeta = newEmptyFixtureDbMeta; // Add teardown callback OnFixtureTearDown(() => db.Detach(newEmptyFixtureDbMeta)); } - ConfigureTestDatabaseFactory(_fixtureDbMeta, databaseFactory, runtimeState); + ConfigureTestDatabaseFactory(s_fixtureDbMeta, databaseFactory, runtimeState); break; default: @@ -391,8 +381,6 @@ namespace Umbraco.Tests.Integration.Testing log.LogInformation($"ConfigureTestDatabaseFactory - Determined RuntimeLevel: [{state.Level}]"); } - #endregion - protected UmbracoTestAttribute TestOptions => TestOptionAttributeBase.GetTestOptions(); protected virtual T GetRequiredService() => Services.GetRequiredService(); @@ -406,22 +394,22 @@ namespace Umbraco.Tests.Integration.Testing protected virtual void CustomTestSetup(IUmbracoBuilder builder) { } /// - /// Returns the DI container + /// Gets or sets the DI container. /// protected IServiceProvider Services { get; set; } /// - /// Returns the + /// Gets the /// protected IScopeProvider ScopeProvider => Services.GetRequiredService(); /// - /// Returns the + /// Gets the /// protected IScopeAccessor ScopeAccessor => Services.GetRequiredService(); /// - /// Returns the + /// Gets the /// protected ILoggerFactory LoggerFactory => Services.GetRequiredService(); @@ -435,13 +423,9 @@ namespace Umbraco.Tests.Integration.Testing protected IMapperCollection Mappers => Services.GetRequiredService(); - #region Builders - protected UserBuilder UserBuilderInstance = new UserBuilder(); protected UserGroupBuilder UserGroupBuilderInstance = new UserGroupBuilder(); - #endregion - protected static bool FirstTestInSession = true; protected bool FirstTestInFixture = true; diff --git a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTestWithContent.cs b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTestWithContent.cs index 2feccbcccb..af8822ad19 100644 --- a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTestWithContent.cs +++ b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTestWithContent.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using NUnit.Framework; using Umbraco.Core.Models; @@ -21,8 +24,7 @@ namespace Umbraco.Tests.Integration.Testing public virtual void CreateTestData() { // NOTE Maybe not the best way to create/save test data as we are using the services, which are being tested. - - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // Create and Save ContentType "umbTextpage" -> 1051 (template), 1052 (content type) diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/IO/FileSystemsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/IO/FileSystemsTests.cs index 4474b95584..e3339ecbb7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/IO/FileSystemsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/IO/FileSystemsTests.cs @@ -1,56 +1,49 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.IO; using System.Text; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; -using Moq; using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Core.Composing.CompositionExtensions; -using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.IO.MediaPathSchemes; -using Umbraco.Core.Services; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; -using FileSystems = Umbraco.Core.IO.FileSystems; namespace Umbraco.Tests.IO { [TestFixture] - [UmbracoTest()] + [UmbracoTest] public class FileSystemsTests : UmbracoIntegrationTest { [Test] public void Can_Get_MediaFileSystem() { - var fileSystem = GetRequiredService(); + IMediaFileSystem fileSystem = GetRequiredService(); Assert.NotNull(fileSystem); } [Test] public void Can_Get_IMediaFileSystem() { - var fileSystem = GetRequiredService(); + IMediaFileSystem fileSystem = GetRequiredService(); Assert.NotNull(fileSystem); } [Test] public void IMediaFileSystem_Is_Singleton() { - var fileSystem1 = GetRequiredService(); - var fileSystem2 = GetRequiredService(); + IMediaFileSystem fileSystem1 = GetRequiredService(); + IMediaFileSystem fileSystem2 = GetRequiredService(); Assert.AreSame(fileSystem1, fileSystem2); } [Test] public void Can_Unwrap_MediaFileSystem() { - var fileSystem = GetRequiredService(); - var unwrapped = fileSystem.Unwrap(); + IMediaFileSystem fileSystem = GetRequiredService(); + IFileSystem unwrapped = fileSystem.Unwrap(); Assert.IsNotNull(unwrapped); var physical = unwrapped as PhysicalFileSystem; Assert.IsNotNull(physical); @@ -59,21 +52,21 @@ namespace Umbraco.Tests.IO [Test] public void Can_Delete_MediaFiles() { - var fs = GetRequiredService(); + IMediaFileSystem fs = GetRequiredService(); var ms = new MemoryStream(Encoding.UTF8.GetBytes("test")); - var virtPath = fs.GetMediaPath("file.txt", Guid.NewGuid(), Guid.NewGuid()); + string virtPath = fs.GetMediaPath("file.txt", Guid.NewGuid(), Guid.NewGuid()); fs.AddFile(virtPath, ms); // ~/media/1234/file.txt exists - var hostingEnvironment = GetRequiredService(); - var physPath = hostingEnvironment.MapPathWebRoot(Path.Combine("media", virtPath)); + IHostingEnvironment hostingEnvironment = GetRequiredService(); + string physPath = hostingEnvironment.MapPathWebRoot(Path.Combine("media", virtPath)); Assert.IsTrue(File.Exists(physPath)); // ~/media/1234/file.txt is gone fs.DeleteMediaFiles(new[] { virtPath }); Assert.IsFalse(File.Exists(physPath)); - var scheme = GetRequiredService(); + IMediaPathScheme scheme = GetRequiredService(); if (scheme is UniqueMediaPathScheme) { // ~/media/1234 is *not* gone @@ -92,7 +85,6 @@ namespace Umbraco.Tests.IO Assert.IsTrue(Directory.Exists(physPath)); } - // FIXME: don't make sense anymore /* [Test] diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/ContentTypeModelMappingTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/ContentTypeModelMappingTests.cs index fb34c7b467..77b82a22bf 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/ContentTypeModelMappingTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/ContentTypeModelMappingTests.cs @@ -1,4 +1,8 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; +using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; @@ -37,23 +41,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void MemberTypeSave_To_IMemberType() { - //Arrange - //TODO use builder + // Arrange + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" }; _dataTypeService.Save(dataType); - var display = CreateMemberTypeSave(dataType.Id); + MemberTypeSave display = CreateMemberTypeSave(dataType.Id); + // Act + IMemberType result = _sut.Map(display); - //Act - - var result = _sut.Map(display); - - //Assert - + // Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); @@ -69,13 +70,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); - for (var i = 0; i < display.Groups.Count(); i++) + for (int i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); - var propTypes = display.Groups.ElementAt(i).Properties; + IEnumerable propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); @@ -86,7 +87,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < display.AllowedContentTypes.Count(); i++) + for (int i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } @@ -95,22 +96,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void MediaTypeSave_To_IMediaType() { - //Arrange - //TODO use builder + // Arrange + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" }; _dataTypeService.Save(dataType); - var display = CreateMediaTypeSave(dataType.Id); + MediaTypeSave display = CreateMediaTypeSave(dataType.Id); - //Act - - var result = _sut.Map(display); - - //Assert + // Act + IMediaType result = _sut.Map(display); + // Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); @@ -126,13 +125,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); - for (var i = 0; i < display.Groups.Count(); i++) + for (int i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); - var propTypes = display.Groups.ElementAt(i).Properties; + IEnumerable propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); @@ -140,7 +139,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < display.AllowedContentTypes.Count(); i++) + for (int i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } @@ -149,8 +148,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void ContentTypeSave_To_IContentType() { - //Arrange - //TODO use builder + // Arrange + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" @@ -159,25 +158,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping var templates = new ITemplate[] { - //Note the aliases is important - TODO use builder + // Note the aliases is important - TODO use builder new Template(Services.GetRequiredService(), "Name 1", "test"), new Template(Services.GetRequiredService(), "Name 2", "template1"), new Template(Services.GetRequiredService(), "Name 3", "template2"), }; - foreach (var template in templates) + foreach (ITemplate template in templates) { _fileService.SaveTemplate(template); } - var display = CreateContentTypeSave(dataType.Id); + DocumentTypeSave display = CreateContentTypeSave(dataType.Id); - //Act - - var result = _sut.Map(display); - - //Assert + // Act + IContentType result = _sut.Map(display); + // Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); @@ -193,13 +190,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); - for (var i = 0; i < display.Groups.Count(); i++) + for (int i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); - var propTypes = display.Groups.ElementAt(i).Properties; + IEnumerable propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); @@ -207,18 +204,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } } - var allowedTemplateAliases = display.AllowedTemplates - .Concat(new[] {display.DefaultTemplate}) + IEnumerable allowedTemplateAliases = display.AllowedTemplates + .Concat(new[] { display.DefaultTemplate }) .Distinct(); Assert.AreEqual(allowedTemplateAliases.Count(), result.AllowedTemplates.Count()); - for (var i = 0; i < display.AllowedTemplates.Count(); i++) + for (int i = 0; i < display.AllowedTemplates.Count(); i++) { Assert.AreEqual(display.AllowedTemplates.ElementAt(i), result.AllowedTemplates.ElementAt(i).Alias); } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < display.AllowedContentTypes.Count(); i++) + for (int i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } @@ -227,47 +224,43 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void MediaTypeSave_With_Composition_To_IMediaType() { - //Arrange - //TODO use builder + // Arrange + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" }; _dataTypeService.Save(dataType); + MediaTypeSave display = CreateCompositionMediaTypeSave(dataType.Id); - var display = CreateCompositionMediaTypeSave(dataType.Id); + // Act + IMediaType result = _sut.Map(display); - //Act - - var result = _sut.Map(display); - - //Assert + // Assert + Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } [Test] public void ContentTypeSave_With_Composition_To_IContentType() { - //Arrange + // Arrange - //TODO use builder + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" }; _dataTypeService.Save(dataType); - var display = CreateCompositionContentTypeSave(dataType.Id); + DocumentTypeSave display = CreateCompositionContentTypeSave(dataType.Id); - //Act - - var result = _sut.Map(display); - - //Assert + // Act + IContentType result = _sut.Map(display); + // Assert // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } @@ -275,20 +268,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void IMemberType_To_MemberTypeDisplay() { - //Arrange - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); - var alias = memberType.PropertyTypes.Last().Alias; + // Arrange + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); + string alias = memberType.PropertyTypes.Last().Alias; memberType.SetIsSensitiveProperty(alias, true); memberType.SetMemberCanEditProperty(alias, true); memberType.SetMemberCanViewProperty(alias, true); MemberTypeBuilder.EnsureAllIds(memberType, 8888); - //Act - - var result = _sut.Map(memberType); - - //Assert + // Act + MemberTypeDisplay result = _sut.Map(memberType); + // Assert Assert.AreEqual(memberType.Alias, result.Alias); Assert.AreEqual(memberType.Description, result.Description); Assert.AreEqual(memberType.Icon, result.Icon); @@ -301,17 +292,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(memberType.CreateDate, result.CreateDate); Assert.AreEqual(memberType.UpdateDate, result.UpdateDate); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(memberType.PropertyGroups.Count(), result.Groups.Count()); - for (var i = 0; i < memberType.PropertyGroups.Count(); i++) + for (int i = 0; i < memberType.PropertyGroups.Count(); i++) { Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); - var propTypes = memberType.PropertyGroups.ElementAt(i).PropertyTypes; + PropertyTypeCollection propTypes = memberType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); @@ -322,28 +311,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(memberType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < memberType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < memberType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(memberType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } - } - [Test] public void IMediaType_To_MediaTypeDisplay() { - //Arrange - - var mediaType = MediaTypeBuilder.CreateImageMediaType(); + // Arrange + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType(); MediaTypeBuilder.EnsureAllIds(mediaType, 8888); - //Act - - var result = _sut.Map(mediaType); - - //Assert + // Act + MediaTypeDisplay result = _sut.Map(mediaType); + // Assert Assert.AreEqual(mediaType.Alias, result.Alias); Assert.AreEqual(mediaType.Description, result.Description); Assert.AreEqual(mediaType.Icon, result.Icon); @@ -356,17 +340,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(mediaType.CreateDate, result.CreateDate); Assert.AreEqual(mediaType.UpdateDate, result.UpdateDate); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(mediaType.PropertyGroups.Count(), result.Groups.Count()); - for (var i = 0; i < mediaType.PropertyGroups.Count(); i++) + for (int i = 0; i < mediaType.PropertyGroups.Count(); i++) { Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); - var propTypes = mediaType.PropertyGroups.ElementAt(i).PropertyTypes; + PropertyTypeCollection propTypes = mediaType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); - for (var j = 0; j < propTypes.Count(); j++) + for (int j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); @@ -374,31 +356,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(mediaType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < mediaType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < mediaType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(mediaType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } - } [Test] public void IContentType_To_ContentTypeDisplay() { - //Arrange - // _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) - // .Returns(new DataType(new VoidEditor(Mock.Of(), Mock.Of(), Mock.Of(),Mock.Of(), Mock.Of()))); + // Arrange + //// _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) + //// .Returns(new DataType(new VoidEditor(Mock.Of(), Mock.Of(), Mock.Of(),Mock.Of(), Mock.Of()))); // - // // setup the mocks to return the data we want to test against... - - var contentType = ContentTypeBuilder.CreateTextPageContentType(); + // setup the mocks to return the data we want to test against... + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(); ContentTypeBuilder.EnsureAllIds(contentType, 8888); - //Act - - var result = _sut.Map(contentType); - - //Assert + // Act + DocumentTypeDisplay result = _sut.Map(contentType); + // Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); @@ -412,17 +390,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(contentType.PropertyGroups.Count, result.Groups.Count()); - for (var i = 0; i < contentType.PropertyGroups.Count; i++) + for (int i = 0; i < contentType.PropertyGroups.Count; i++) { Assert.AreEqual(contentType.PropertyGroups[i].Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(contentType.PropertyGroups[i].Name, result.Groups.ElementAt(i).Name); - var propTypes = contentType.PropertyGroups[i].PropertyTypes; + PropertyTypeCollection propTypes = contentType.PropertyGroups[i].PropertyTypes; Assert.AreEqual(propTypes.Count, result.Groups.ElementAt(i).Properties.Count()); - for (var j = 0; j < propTypes.Count; j++) + for (int j = 0; j < propTypes.Count; j++) { Assert.AreEqual(propTypes[j].Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes[j].DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); @@ -431,23 +407,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); - for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) + for (int i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } - } [Test] public void MemberPropertyGroupBasic_To_MemberPropertyGroup() { - //TODO use builder + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" @@ -510,8 +485,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such - //var result = Mapper.Map(basic); - var result = _sut.Map(contentType).PropertyGroups[0]; + // var result = Mapper.Map(basic); + PropertyGroup result = _sut.Map(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); @@ -579,8 +554,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such - //var result = Mapper.Map(basic); - var result = _sut.Map(contentType).PropertyGroups[0]; + // var result = Mapper.Map(basic); + PropertyGroup result = _sut.Map(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); @@ -609,7 +584,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } }; - var result = _sut.Map(basic); + IPropertyType result = _sut.Map(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); @@ -627,7 +602,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void PropertyTypeBasic_To_PropertyType() { - //TODO use builder + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" @@ -652,7 +627,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } }; - var result = _sut.Map(basic); + IPropertyType result = _sut.Map(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); @@ -670,50 +645,50 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void IMediaTypeComposition_To_MediaTypeDisplay() { - //Arrange - var ctMain = MediaTypeBuilder.CreateSimpleMediaType("parent", "Parent"); - //not assigned to tab + // Arrange + MediaType ctMain = MediaTypeBuilder.CreateSimpleMediaType("parent", "Parent"); + + // not assigned to tab ctMain.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlName", Name = "Slug", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MediaTypeBuilder.EnsureAllIds(ctMain, 8888); - var ctChild1 = MediaTypeBuilder.CreateSimpleMediaType("child1", "Child 1", ctMain, true); - ctChild1.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) - { - Alias = "someProperty", - Name = "Some Property", - Description = "", - Mandatory = false, - SortOrder = 1, - DataTypeId = -88 - }, "Another tab"); + MediaType ctChild1 = MediaTypeBuilder.CreateSimpleMediaType("child1", "Child 1", ctMain, true); + ctChild1.AddPropertyType( + new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) + { + Alias = "someProperty", + Name = "Some Property", + Description = string.Empty, + Mandatory = false, + SortOrder = 1, + DataTypeId = -88 + }, "Another tab"); MediaTypeBuilder.EnsureAllIds(ctChild1, 7777); - var contentType = MediaTypeBuilder.CreateSimpleMediaType("child2", "Child 2", ctChild1, true, "CustomGroup"); - //not assigned to tab + MediaType contentType = MediaTypeBuilder.CreateSimpleMediaType("child2", "Child 2", ctChild1, true, "CustomGroup"); + + // not assigned to tab contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlAlias", Name = "AltUrl", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MediaTypeBuilder.EnsureAllIds(contentType, 6666); + // Act + MediaTypeDisplay result = _sut.Map(contentType); - //Act - - var result = _sut.Map(contentType); - - //Assert - + // Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); @@ -726,15 +701,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); - var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); - var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); - var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); + PropertyTypeDisplay[] allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); + int[] allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); + int[] allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); @@ -743,9 +716,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] { ctMain.Id, ctChild1.Id })); - Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } @@ -754,41 +726,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void IContentTypeComposition_To_ContentTypeDisplay() { - //Arrange + // Arrange + ContentType ctMain = ContentTypeBuilder.CreateSimpleContentType(); - var ctMain = ContentTypeBuilder.CreateSimpleContentType(); - //not assigned to tab + // not assigned to tab ctMain.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { - Alias = "umbracoUrlName", Name = "Slug", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Alias = "umbracoUrlName", Name = "Slug", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); ContentTypeBuilder.EnsureAllIds(ctMain, 8888); - var ctChild1 = ContentTypeBuilder.CreateSimpleContentType("child1", "Child 1", ctMain, randomizeAliases: true); - ctChild1.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) - { - Alias = "someProperty", - Name = "Some Property", - Description = "", - Mandatory = false, - SortOrder = 1, - DataTypeId = -88 - }, "Another tab"); + ContentType ctChild1 = ContentTypeBuilder.CreateSimpleContentType("child1", "Child 1", ctMain, randomizeAliases: true); + ctChild1.AddPropertyType( + new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) + { + Alias = "someProperty", + Name = "Some Property", + Description = string.Empty, + Mandatory = false, + SortOrder = 1, + DataTypeId = -88 + }, "Another tab"); ContentTypeBuilder.EnsureAllIds(ctChild1, 7777); - var contentType = ContentTypeBuilder.CreateSimpleContentType("child2", "Child 2", ctChild1, randomizeAliases: true, propertyGroupName: "CustomGroup"); - //not assigned to tab + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("child2", "Child 2", ctChild1, randomizeAliases: true, propertyGroupName: "CustomGroup"); + + // not assigned to tab contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { - Alias = "umbracoUrlAlias", Name = "AltUrl", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Alias = "umbracoUrlAlias", Name = "AltUrl", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); ContentTypeBuilder.EnsureAllIds(contentType, 6666); + // Act + DocumentTypeDisplay result = _sut.Map(contentType); - //Act - - var result = _sut.Map(contentType); - - //Assert - + // Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); @@ -802,35 +773,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); - // TODO: Now we need to assert all of the more complicated parts - Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); - var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); - var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); - var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); + PropertyTypeDisplay[] allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); + int[] allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); + int[] allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds)); Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); - Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] {ctMain.Id, ctChild1.Id})); + Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] { ctMain.Id, ctChild1.Id })); Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); - for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) + for (int i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); - for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) + for (int i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } - } [Test] @@ -855,7 +823,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } }; - var result = _sut.Map(basic); + MemberPropertyTypeDisplay result = _sut.Map(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); @@ -873,7 +841,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void PropertyTypeBasic_To_PropertyTypeDisplay() { - //TODO use builder + // TODO use builder var dataType = new DataType(Services.GetRequiredService(), _serializer) { Name = "TODO" @@ -895,7 +863,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping } }; - var result = _sut.Map(basic); + PropertyTypeDisplay result = _sut.Map(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); @@ -907,9 +875,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.AreEqual(basic.Validation, result.Validation); } - private MemberTypeSave CreateMemberTypeSave(int dataTypeId) - { - return new MemberTypeSave + private MemberTypeSave CreateMemberTypeSave(int dataTypeId) => + new MemberTypeSave { Alias = "test", AllowAsRoot = true, @@ -924,41 +891,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] - { - new PropertyGroupBasic() { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] + new PropertyGroupBasic() { - new MemberPropertyTypeBasic + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] { - MemberCanEditProperty = true, - MemberCanViewProperty = true, - IsSensitiveData = true, - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation + new MemberPropertyTypeBasic { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - DataTypeId = dataTypeId + MemberCanEditProperty = true, + MemberCanViewProperty = true, + IsSensitiveData = true, + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + DataTypeId = dataTypeId + } } } } - } }; - } - private MediaTypeSave CreateMediaTypeSave(int dataTypeId) - { - return new MediaTypeSave + private MediaTypeSave CreateMediaTypeSave(int dataTypeId) => + new MediaTypeSave { Alias = "test", AllowAsRoot = true, @@ -973,173 +938,44 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] - { - new PropertyGroupBasic() { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] + new PropertyGroupBasic() { - new PropertyTypeBasic + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] { - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation + new PropertyTypeBasic { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - DataTypeId = dataTypeId + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + DataTypeId = dataTypeId + } } } } - } }; - } - private DocumentTypeSave CreateContentTypeSave(int dataTypeId) - { - return new DocumentTypeSave - { - Alias = "test", - AllowAsRoot = true, - AllowedTemplates = new [] - { - "template1", - "template2" - }, - AllowedContentTypes = new [] {666, 667}, - DefaultTemplate = "test", - Description = "hello world", - Icon = "tree-icon", - Id = 1234, - Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), - Name = "My content type", - Path = "-1,1234", - ParentId = -1, - Thumbnail = "tree-thumb", - IsContainer = true, - Groups = new [] - { - new PropertyGroupBasic() - { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] - { - new PropertyTypeBasic - { - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation - { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = true, - DataTypeId = dataTypeId - } - } - } - } - }; - } - - private MediaTypeSave CreateCompositionMediaTypeSave(int dataTypeId) - { - return new MediaTypeSave - { - Alias = "test", - AllowAsRoot = true, - AllowedContentTypes = new[] { 666, 667 }, - Description = "hello world", - Icon = "tree-icon", - Id = 1234, - Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), - Name = "My content type", - Path = "-1,1234", - ParentId = -1, - Thumbnail = "tree-thumb", - IsContainer = true, - Groups = new[] - { - new PropertyGroupBasic() - { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] - { - new PropertyTypeBasic - { - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation - { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = true, - DataTypeId = dataTypeId - } - } - }, - new PropertyGroupBasic() - { - Id = 894, - Name = "Tab 2", - SortOrder = 0, - Inherited = true, - Properties = new[] - { - new PropertyTypeBasic - { - Alias = "parentProperty", - Description = "this is a property from the parent", - Inherited = true, - Label = "Parent property", - Validation = new PropertyTypeValidation - { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = false, - DataTypeId = dataTypeId - } - } - - } - } - - }; - } - - private DocumentTypeSave CreateCompositionContentTypeSave(int dataTypeId) - { - return new DocumentTypeSave + private DocumentTypeSave CreateContentTypeSave(int dataTypeId) => + new DocumentTypeSave { Alias = "test", AllowAsRoot = true, AllowedTemplates = new[] - { - "template1", - "template2" - }, + { + "template1", + "template2" + }, AllowedContentTypes = new[] { 666, 667 }, DefaultTemplate = "test", Description = "hello world", @@ -1152,61 +988,179 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] - { - new PropertyGroupBasic() { - Id = 987, - Name = "Tab 1", - SortOrder = 0, - Inherited = false, - Properties = new[] + new PropertyGroupBasic() { - new PropertyTypeBasic + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] { - Alias = "property1", - Description = "this is property 1", - Inherited = false, - Label = "Property 1", - Validation = new PropertyTypeValidation + new PropertyTypeBasic { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = true, - DataTypeId = dataTypeId + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = true, + DataTypeId = dataTypeId + } + } + } + } + }; + + private MediaTypeSave CreateCompositionMediaTypeSave(int dataTypeId) => + new MediaTypeSave + { + Alias = "test", + AllowAsRoot = true, + AllowedContentTypes = new[] { 666, 667 }, + Description = "hello world", + Icon = "tree-icon", + Id = 1234, + Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), + Name = "My content type", + Path = "-1,1234", + ParentId = -1, + Thumbnail = "tree-thumb", + IsContainer = true, + Groups = new[] + { + new PropertyGroupBasic() + { + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] + { + new PropertyTypeBasic + { + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = true, + DataTypeId = dataTypeId + } + } + }, + new PropertyGroupBasic() + { + Id = 894, + Name = "Tab 2", + SortOrder = 0, + Inherited = true, + Properties = new[] + { + new PropertyTypeBasic + { + Alias = "parentProperty", + Description = "this is a property from the parent", + Inherited = true, + Label = "Parent property", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = false, + DataTypeId = dataTypeId + } + } + } + } + }; + + private DocumentTypeSave CreateCompositionContentTypeSave(int dataTypeId) => + new DocumentTypeSave + { + Alias = "test", + AllowAsRoot = true, + AllowedTemplates = new[] + { + "template1", + "template2" + }, + AllowedContentTypes = new[] { 666, 667 }, + DefaultTemplate = "test", + Description = "hello world", + Icon = "tree-icon", + Id = 1234, + Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), + Name = "My content type", + Path = "-1,1234", + ParentId = -1, + Thumbnail = "tree-thumb", + IsContainer = true, + Groups = new[] + { + new PropertyGroupBasic() + { + Id = 987, + Name = "Tab 1", + SortOrder = 0, + Inherited = false, + Properties = new[] + { + new PropertyTypeBasic + { + Alias = "property1", + Description = "this is property 1", + Inherited = false, + Label = "Property 1", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = true, + DataTypeId = dataTypeId + } + } + }, + new PropertyGroupBasic() + { + Id = 894, + Name = "Tab 2", + SortOrder = 0, + Inherited = true, + Properties = new[] + { + new PropertyTypeBasic + { + Alias = "parentProperty", + Description = "this is a property from the parent", + Inherited = true, + Label = "Parent property", + Validation = new PropertyTypeValidation + { + Mandatory = false, + Pattern = string.Empty + }, + SortOrder = 0, + LabelOnTop = false, + DataTypeId = dataTypeId + } } } - }, - new PropertyGroupBasic() - { - Id = 894, - Name = "Tab 2", - SortOrder = 0, - Inherited = true, - Properties = new[] - { - new PropertyTypeBasic - { - Alias = "parentProperty", - Description = "this is a property from the parent", - Inherited = true, - Label = "Parent property", - Validation = new PropertyTypeValidation - { - Mandatory = false, - Pattern = string.Empty - }, - SortOrder = 0, - LabelOnTop = false, - DataTypeId = dataTypeId - } - } - } - } - }; - } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UmbracoMapperTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UmbracoMapperTests.cs index 4028889b01..204b27dded 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UmbracoMapperTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UmbracoMapperTests.cs @@ -1,4 +1,7 @@ -using System.Globalization; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Globalization; using System.Linq; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; @@ -42,11 +45,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping private IContentTypeService _contentTypeService; private ILocalizedTextService _localizedTextService; - [Test] public void To_Media_Item_Simple() { - var content = _mediaBuilder + Media content = _mediaBuilder .AddMediaType() .AddPropertyGroup() .AddPropertyType() @@ -56,11 +58,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map>(content); + ContentItemBasic result = _sut.Map>(content); AssertBasics(result, content); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertBasicProperty(result, p); } @@ -69,7 +71,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Content_Item_Simple() { - var content = _contentBuilder + Content content = _contentBuilder .AddContentType() .AddPropertyGroup() .AddPropertyType() @@ -79,11 +81,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map>(content); + ContentItemBasic result = _sut.Map>(content); AssertBasics(result, content); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertBasicProperty(result, p); } @@ -92,7 +94,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Content_Item_Dto() { - var content = _contentBuilder + Content content = _contentBuilder .AddContentType() .AddPropertyGroup() .AddPropertyType() @@ -102,9 +104,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map(content); + ContentPropertyCollectionDto result = _sut.Map(content); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertProperty(result, p); } @@ -113,7 +115,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Media_Item_Dto() { - var content = _mediaBuilder + Media content = _mediaBuilder .AddMediaType() .AddPropertyGroup() .AddPropertyType() @@ -122,35 +124,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .Done() .Build(); - var result = _sut.Map(content); + ContentPropertyCollectionDto result = _sut.Map(content); Assert.GreaterOrEqual(result.Properties.Count(), 1); Assert.AreEqual(content.Properties.Count, result.Properties.Count()); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertProperty(result, p); } } - #region Assertions - private void AssertDisplayProperty(IContentProperties result, IProperty p) where T : ContentPropertyBasic { - var pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); + T pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); Assert.IsNotNull(pDto); - //pDto.Alias = p.Alias; - //pDto.Description = p.PropertyType.Description; - //pDto.Label = p.PropertyType.Name; - //pDto.Config = applicationContext.Services.DataTypeService.GetPreValuesByDataTypeId(p.PropertyType.DataTypeDefinitionId); - + // pDto.Alias = p.Alias; + // pDto.Description = p.PropertyType.Description; + // pDto.Label = p.PropertyType.Name; + // pDto.Config = applicationContext.Services.DataTypeService.GetPreValuesByDataTypeId(p.PropertyType.DataTypeDefinitionId); } [Test] public void To_Display_Model() { - var contentType = _contentTypeBuilder + IContentType contentType = _contentTypeBuilder .WithId(0) .AddPropertyGroup() .WithId(1) @@ -175,17 +174,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .Build(); _contentTypeService.Save(contentType); - var content = _contentBuilder + Content content = _contentBuilder .WithContentType(contentType) .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map(content); + ContentItemDisplay result = _sut.Map(content); AssertBasics(result, content); - var invariantContent = result.Variants.First(); - foreach (var p in content.Properties) + ContentVariantDisplay invariantContent = result.Variants.First(); + foreach (IProperty p in content.Properties) { AssertBasicProperty(invariantContent, p); AssertDisplayProperty(invariantContent, p); @@ -199,22 +198,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Display_Model_No_Tabs() { - var contentType = _contentTypeBuilder + IContentType contentType = _contentTypeBuilder .WithId(0) .Build(); _contentTypeService.Save(contentType); - var content = _contentBuilder + Content content = _contentBuilder .WithContentType(contentType) .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map(content); + ContentItemDisplay result = _sut.Map(content); AssertBasics(result, content); - var invariantContent = result.Variants.First(); - foreach (var p in content.Properties) + ContentVariantDisplay invariantContent = result.Variants.First(); + foreach (IProperty p in content.Properties) { AssertBasicProperty(invariantContent, p); AssertDisplayProperty(invariantContent, p); @@ -226,7 +225,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping [Test] public void To_Display_Model_With_Non_Grouped_Properties() { - var contentType = _contentTypeBuilder + IContentType contentType = _contentTypeBuilder .WithId(0) .AddPropertyType() .WithId(1) @@ -243,17 +242,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping .Build(); _contentTypeService.Save(contentType); - var content = _contentBuilder + Content content = _contentBuilder .WithContentType(contentType) .WithCreatorId(Constants.Security.SuperUserId) .Build(); - var result = _sut.Map(content); + ContentItemDisplay result = _sut.Map(content); AssertBasics(result, content); - var invariantContent = result.Variants.First(); - foreach (var p in content.Properties) + ContentVariantDisplay invariantContent = result.Variants.First(); + foreach (IProperty p in content.Properties) { AssertBasicProperty(invariantContent, p); AssertDisplayProperty(invariantContent, p); @@ -268,7 +267,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping { Assert.AreEqual(content.Id, result.Id); - var ownerId = content.CreatorId; + int ownerId = content.CreatorId; if (ownerId != 0) { Assert.IsNotNull(result.Owner); @@ -280,13 +279,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping Assert.IsNull(result.Owner); // because, 0 is no user } - var invariantContent = result.Variants.First(); + ContentVariantDisplay invariantContent = result.Variants.First(); Assert.AreEqual(content.ParentId, result.ParentId); Assert.AreEqual(content.UpdateDate, invariantContent.UpdateDate); Assert.AreEqual(content.CreateDate, invariantContent.CreateDate); Assert.AreEqual(content.Name, invariantContent.Name); - Assert.AreEqual(content.Properties.Count(), + Assert.AreEqual( + content.Properties.Count(), ((IContentProperties)invariantContent).Properties.Count(x => x.Alias.StartsWith("_umb_") == false)); } @@ -296,7 +296,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping { Assert.AreEqual(content.Id, result.Id); - var ownerId = content.CreatorId; + int ownerId = content.CreatorId; if (ownerId != 0) { Assert.IsNotNull(result.Owner); @@ -318,24 +318,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping private void AssertBasicProperty(IContentProperties result, IProperty p) where T : ContentPropertyBasic { - var pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); + T pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); Assert.IsNotNull(pDto); Assert.AreEqual(p.Alias, pDto.Alias); Assert.AreEqual(p.Id, pDto.Id); if (p.GetValue() == null) + { Assert.AreEqual(pDto.Value, string.Empty); - else if (p.GetValue() is decimal) - Assert.AreEqual(pDto.Value, ((decimal) p.GetValue()).ToString(NumberFormatInfo.InvariantInfo)); + } + else if (p.GetValue() is decimal decimalValue) + { + Assert.AreEqual(pDto.Value, decimalValue.ToString(NumberFormatInfo.InvariantInfo)); + } else + { Assert.AreEqual(pDto.Value, p.GetValue().ToString()); + } } private void AssertProperty(IContentProperties result, IProperty p) { AssertBasicProperty(result, p); - var pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); + ContentPropertyDto pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias); Assert.IsNotNull(pDto); Assert.AreEqual(p.PropertyType.Mandatory, pDto.IsRequired); Assert.AreEqual(p.PropertyType.ValidationRegExp, pDto.ValidationRegExp); @@ -350,11 +356,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping { AssertBasics(result, content); - foreach (var p in content.Properties) + foreach (IProperty p in content.Properties) { AssertProperty(result, p); } } - #endregion } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UserModelMapperTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UserModelMapperTests.cs index f8c276d429..ac7c248058 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UserModelMapperTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Mapping/UserModelMapperTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using NUnit.Framework; @@ -12,29 +15,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Mapping { [TestFixture] [UmbracoTest(Mapper = true, Database = UmbracoTestOptions.Database.NewSchemaPerTest)] - public class UserModelMapperTests: UmbracoIntegrationTest + public class UserModelMapperTests : UmbracoIntegrationTest { private UmbracoMapper _sut; [SetUp] - public void Setup() - { - _sut = Services.GetRequiredService(); - } + public void Setup() => _sut = Services.GetRequiredService(); [Test] public void Map_UserGroupSave_To_IUserGroup() { - IUserGroup userGroup = new UserGroup(ShortStringHelper, 0, "alias", "name", new List { "c" }, "icon"); - userGroup.Id = 42; + IUserGroup userGroup = new UserGroup(ShortStringHelper, 0, "alias", "name", new List { "c" }, "icon") + { + Id = 42 + }; - // userGroup.permissions is System.Collections.Generic.List`1[System.String] + // userGroup.permissions is List`1[System.String] // userGroup.permissions is System.Linq.Enumerable+WhereSelectArrayIterator`2[System.Char, System.String] - // fixed: now System.Collections.Generic.List`1[System.String] - + // fixed: now List`1[System.String] const string json = "{\"id\":@@@ID@@@,\"alias\":\"perm1\",\"name\":\"Perm1\",\"icon\":\"icon-users\",\"sections\":[\"content\"],\"users\":[],\"defaultPermissions\":[\"F\",\"C\",\"A\"],\"assignedPermissions\":{},\"startContentId\":-1,\"startMediaId\":-1,\"action\":\"save\",\"parentId\":-1}"; - var userGroupSave = JsonConvert.DeserializeObject(json.Replace("@@@ID@@@", userGroup.Id.ToString())); + UserGroupSave userGroupSave = JsonConvert.DeserializeObject(json.Replace("@@@ID@@@", userGroup.Id.ToString())); // failed, AutoMapper complained, "Unable to cast object of type 'WhereSelectArrayIterator`2[System.Char,System.String]' to type 'System.Collections.IList'". // FIXME: added ToList() in UserGroupFactory diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs index e3ec2d872b..603d5a87b3 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; @@ -24,41 +27,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging private Guid _testBaseFolder; [SetUp] - public void SetupTestData() - { - _testBaseFolder = Guid.NewGuid(); - } + public void SetupTestData() => _testBaseFolder = Guid.NewGuid(); [TearDown] - public void DeleteTestFolder() - { - //clear out files/folders + public void DeleteTestFolder() => Directory.Delete(HostingEnvironment.MapPathContentRoot("~/" + _testBaseFolder), true); - } private IContentService ContentService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IMacroService MacroService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IEntityXmlSerializer EntityXmlSerializer => GetRequiredService(); + private IHostingEnvironment HostingEnvironment => GetRequiredService(); + private IUmbracoVersion UmbracoVersion => GetRequiredService(); + private IMediaService MediaService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); public ICreatedPackagesRepository PackageBuilder => new PackagesRepository( - ContentService, ContentTypeService, DataTypeService, - FileService, MacroService, LocalizationService, + ContentService, + ContentTypeService, + DataTypeService, + FileService, + MacroService, + LocalizationService, HostingEnvironment, - EntityXmlSerializer, LoggerFactory, + EntityXmlSerializer, + LoggerFactory, UmbracoVersion, Microsoft.Extensions.Options.Options.Create(new GlobalSettings()), MediaService, MediaTypeService, "createdPackages.config", - //temp paths + + // temp paths tempFolderPath: "~/" + _testBaseFolder + "/temp", packagesFolderPath: "~/" + _testBaseFolder + "/packages", mediaFolderPath: "~/" + _testBaseFolder + "/media"); @@ -74,7 +87,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging AuthorUrl = "http://test.com" }; - var result = PackageBuilder.SavePackage(def1); + bool result = PackageBuilder.SavePackage(def1); Assert.IsTrue(result); PackageBuilder.Delete(def1.Id); @@ -94,7 +107,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging AuthorUrl = "http://test.com" }; - var result = PackageBuilder.SavePackage(def1); + bool result = PackageBuilder.SavePackage(def1); Assert.IsTrue(result); Assert.AreEqual(1, def1.Id); @@ -120,14 +133,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging { var def = new PackageDefinition { - Id = 3, //doesn't exist + Id = 3, // doesn't exist Name = "test", Url = "http://test.com", Author = "Someone", AuthorUrl = "http://test.com" }; - var result = PackageBuilder.SavePackage(def); + bool result = PackageBuilder.SavePackage(def); Assert.IsFalse(result); } @@ -142,28 +155,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging Author = "Someone", AuthorUrl = "http://test.com" }; - var result = PackageBuilder.SavePackage(def); + bool result = PackageBuilder.SavePackage(def); def.Name = "updated"; - def.Files = new List {"hello.txt", "world.png"}; + def.Files = new List { "hello.txt", "world.png" }; result = PackageBuilder.SavePackage(def); Assert.IsTrue(result); - //re-get + // re-get def = PackageBuilder.GetById(def.Id); Assert.AreEqual("updated", def.Name); Assert.AreEqual(2, def.Files.Count); - // TODO: There's a whole lot more assertions to be done + // TODO: There's a whole lot more assertions to be done } [Test] public void Export() { - var file1 = $"~/{_testBaseFolder}/App_Plugins/MyPlugin/package.manifest"; - var file2 = $"~/{_testBaseFolder}/App_Plugins/MyPlugin/styles.css"; - var mappedFile1 = HostingEnvironment.MapPathContentRoot(file1); - var mappedFile2 = HostingEnvironment.MapPathContentRoot(file2); + string file1 = $"~/{_testBaseFolder}/App_Plugins/MyPlugin/package.manifest"; + string file2 = $"~/{_testBaseFolder}/App_Plugins/MyPlugin/styles.css"; + string mappedFile1 = HostingEnvironment.MapPathContentRoot(file1); + string mappedFile2 = HostingEnvironment.MapPathContentRoot(file2); Directory.CreateDirectory(Path.GetDirectoryName(mappedFile1)); Directory.CreateDirectory(Path.GetDirectoryName(mappedFile2)); File.WriteAllText(mappedFile1, "hello world"); @@ -178,28 +191,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Packaging Files = new List { file1, file2 }, Actions = "" }; - var result = PackageBuilder.SavePackage(def); + bool result = PackageBuilder.SavePackage(def); Assert.IsTrue(result); Assert.IsTrue(def.PackagePath.IsNullOrWhiteSpace()); - var zip = PackageBuilder.ExportPackage(def); + string zip = PackageBuilder.ExportPackage(def); - def = PackageBuilder.GetById(def.Id); //re-get + def = PackageBuilder.GetById(def.Id); // re-get Assert.IsNotNull(def.PackagePath); - using (var archive = ZipFile.OpenRead(HostingEnvironment.MapPathWebRoot(zip))) + using (ZipArchive archive = ZipFile.OpenRead(HostingEnvironment.MapPathWebRoot(zip))) { Assert.AreEqual(3, archive.Entries.Count); - //the 2 files we manually added + // the 2 files we manually added Assert.IsNotNull(archive.Entries.Where(x => x.Name == "package.manifest")); Assert.IsNotNull(archive.Entries.Where(x => x.Name == "styles.css")); - //this is the actual package definition/manifest (not the developer manifest!) - var packageXml = archive.Entries.FirstOrDefault(x => x.Name == "package.xml"); + // this is the actual package definition/manifest (not the developer manifest!) + ZipArchiveEntry packageXml = archive.Entries.FirstOrDefault(x => x.Name == "package.xml"); Assert.IsNotNull(packageXml); - using (var stream = packageXml.Open()) + using (Stream stream = packageXml.Open()) { var xml = XDocument.Load(stream); Assert.AreEqual("umbPackage", xml.Root.Name.ToString()); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageDataInstallationTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageDataInstallationTests.cs index f250a43b7f..defdf1b25c 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageDataInstallationTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageDataInstallationTests.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 System.Threading; using System.Xml.Linq; @@ -13,6 +16,7 @@ using Umbraco.Core.Models.Packaging; using Umbraco.Core.Packaging; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Core.Strings; @@ -29,6 +33,7 @@ namespace Umbraco.Tests.Packaging public class PackageDataInstallationTests : UmbracoIntegrationTestWithContent { private ILocalizationService LocalizationService => GetRequiredService(); + private IMacroService MacroService => GetRequiredService(); [HideFromTypeFinder] @@ -46,40 +51,39 @@ namespace Umbraco.Tests.Packaging public class Editor2 : DataEditor { public Editor2(ILoggerFactory loggerFactory) - : base(loggerFactory, Mock.Of(), Mock.Of(), Mock.Of(),Mock.Of(), new JsonNetSerializer()) + : base(loggerFactory, Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), new JsonNetSerializer()) { } } - // protected override void Compose() - // { - // base.Compose(); - // - // // the packages that are used by these tests reference totally bogus property - // // editors that must exist - so they are defined here - and in order not to - // // pollute everything, they are ignored by the type finder and explicitely - // // added to the editors collection - // - // Builder.WithCollectionBuilder() - // .Add() - // .Add(); - // } - // - // protected override void ComposeApplication(bool withApplication) - // { - // base.ComposeApplication(withApplication); - // - // if (!withApplication) return; - // - // // re-register with actual media fs - // Builder.ComposeFileSystems(); - // } + //// protected override void Compose() + //// { + //// base.Compose(); + //// + //// // the packages that are used by these tests reference totally bogus property + //// // editors that must exist - so they are defined here - and in order not to + //// // pollute everything, they are ignored by the type finder and explicitely + //// // added to the editors collection + //// + //// Builder.WithCollectionBuilder() + //// .Add() + //// .Add(); + //// } + //// + //// protected override void ComposeApplication(bool withApplication) + //// { + //// base.ComposeApplication(withApplication); + //// + //// if (!withApplication) return; + //// + //// // re-register with actual media fs + //// Builder.ComposeFileSystems(); + //// } private PackageDataInstallation PackageDataInstallation => GetRequiredService(); - private IContentService ContentService => GetRequiredService(); - private IContentTypeService ContentTypeService => GetRequiredService(); private IMediaService MediaService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); [Test] @@ -88,17 +92,17 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.uBlogsy_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + int numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(dataTypes.Any(), Is.True); @@ -107,11 +111,11 @@ namespace Umbraco.Tests.Packaging Assert.That(contentTypes.Any(), Is.True); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); - var uBlogsyBaseDocType = contentTypes.First(x => x.Alias == "uBlogsyBaseDocType"); + IContentType uBlogsyBaseDocType = contentTypes.First(x => x.Alias == "uBlogsyBaseDocType"); Assert.That(uBlogsyBaseDocType.PropertyTypes.Count(), Is.EqualTo(5)); Assert.That(uBlogsyBaseDocType.PropertyGroups.Any(), Is.False); - var uBlogsyBasePage = contentTypes.First(x => x.Alias == "uBlogsyBasePage"); + IContentType uBlogsyBasePage = contentTypes.First(x => x.Alias == "uBlogsyBasePage"); Assert.That(uBlogsyBasePage.ContentTypeCompositionExists("uBlogsyBaseDocType"), Is.True); Assert.That(uBlogsyBasePage.PropertyTypes.Count(), Is.EqualTo(7)); Assert.That(uBlogsyBasePage.PropertyGroups.Count, Is.EqualTo(3)); @@ -120,7 +124,7 @@ namespace Umbraco.Tests.Packaging Assert.That(uBlogsyBasePage.PropertyGroups["Navigation"].PropertyTypes.Count(), Is.EqualTo(1)); Assert.That(uBlogsyBasePage.CompositionPropertyTypes.Count(), Is.EqualTo(12)); - var uBlogsyLanding = contentTypes.First(x => x.Alias == "uBlogsyLanding"); + IContentType uBlogsyLanding = contentTypes.First(x => x.Alias == "uBlogsyLanding"); Assert.That(uBlogsyLanding.ContentTypeCompositionExists("uBlogsyBasePage"), Is.True); Assert.That(uBlogsyLanding.ContentTypeCompositionExists("uBlogsyBaseDocType"), Is.True); Assert.That(uBlogsyLanding.PropertyTypes.Count(), Is.EqualTo(5)); @@ -133,23 +137,23 @@ namespace Umbraco.Tests.Packaging public void Can_Import_Inherited_ContentTypes_And_Verify_PropertyTypes_UniqueIds() { // Arrange - var strXml = ImportResources.InheritedDocTypes_Package; + string strXml = ImportResources.InheritedDocTypes_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); // Assert - var mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage"); - using (var scope = ScopeProvider.CreateScope()) - foreach (var propertyType in mRBasePage.PropertyTypes) + IContentType mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage"); + using IScope scope = ScopeProvider.CreateScope(); + foreach (IPropertyType propertyType in mRBasePage.PropertyTypes) { - var propertyTypeDto = scope.Database.First("WHERE id = @id", new { id = propertyType.Id }); + PropertyTypeDto propertyTypeDto = scope.Database.First("WHERE id = @id", new { id = propertyType.Id }); Assert.AreEqual(propertyTypeDto.UniqueId, propertyType.Key); } } @@ -160,16 +164,16 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.InheritedDocTypes_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypes = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(dataTypes.Any(), Is.False); @@ -177,18 +181,18 @@ namespace Umbraco.Tests.Packaging Assert.That(contentTypes.Any(), Is.True); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); - var mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage"); + IContentType mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage"); Assert.That(mRBasePage.PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(mRBasePage.PropertyGroups.Count(), Is.EqualTo(1)); Assert.That(mRBasePage.PropertyGroups["Metadaten"].PropertyTypes.Count(), Is.EqualTo(2)); - var mRStartPage = contentTypes.First(x => x.Alias == "MRStartPage"); + IContentType mRStartPage = contentTypes.First(x => x.Alias == "MRStartPage"); Assert.That(mRStartPage.ContentTypeCompositionExists("MRBasePage"), Is.True); Assert.That(mRStartPage.PropertyTypes.Count(), Is.EqualTo(28)); Assert.That(mRStartPage.PropertyGroups.Count(), Is.EqualTo(7)); - var propertyGroups = mRStartPage.CompositionPropertyGroups.Where(x => x.Name == "Metadaten"); - var propertyTypes = propertyGroups.SelectMany(x => x.PropertyTypes); + IEnumerable propertyGroups = mRStartPage.CompositionPropertyGroups.Where(x => x.Name == "Metadaten"); + IEnumerable propertyTypes = propertyGroups.SelectMany(x => x.PropertyTypes); Assert.That(propertyGroups.Count(), Is.EqualTo(2)); Assert.That(propertyTypes.Count(), Is.EqualTo(6)); } @@ -199,14 +203,14 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var element = xml.Descendants("Templates").First(); + XElement element = xml.Descendants("Templates").First(); - var init = FileService.GetTemplates().Count(); + int init = FileService.GetTemplates().Count(); // Act - var templates = PackageDataInstallation.ImportTemplates(element.Elements("Template").ToList(), 0); - var numberOfTemplates = (from doc in element.Elements("Template") select doc).Count(); - var allTemplates = FileService.GetTemplates(); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(element.Elements("Template").ToList(), 0); + int numberOfTemplates = (from doc in element.Elements("Template") select doc).Count(); + IEnumerable allTemplates = FileService.GetTemplates(); // Assert Assert.That(templates, Is.Not.Null); @@ -223,11 +227,10 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var element = xml.Descendants("Templates").First(); - + XElement element = xml.Descendants("Templates").First(); // Act - var templates = PackageDataInstallation.ImportTemplate(element.Elements("Template").First(), 0); + IEnumerable templates = PackageDataInstallation.ImportTemplate(element.Elements("Template").First(), 0); // Assert Assert.That(templates, Is.Not.Null); @@ -241,16 +244,15 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); - + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -261,13 +263,13 @@ namespace Umbraco.Tests.Packaging Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); Assert.That(contentTypes.Count(x => x.ParentId == -1), Is.EqualTo(1)); - var contentMaster = contentTypes.First(x => x.Alias == "ContentMaster"); + IContentType contentMaster = contentTypes.First(x => x.Alias == "ContentMaster"); Assert.That(contentMaster.PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(contentMaster.PropertyGroups.Count(), Is.EqualTo(1)); Assert.That(contentMaster.PropertyGroups["SEO"].PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(contentMaster.ContentTypeCompositionExists("Base"), Is.True); - var propertyGroupId = contentMaster.PropertyGroups["SEO"].Id; + int propertyGroupId = contentMaster.PropertyGroups["SEO"].Id; Assert.That(contentMaster.PropertyGroups["SEO"].PropertyTypes.Any(x => x.PropertyGroupId.Value != propertyGroupId), Is.False); } @@ -277,17 +279,17 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); - //Assert - Re-Import contenttypes doesn't throw + // Assert - Re-Import contenttypes doesn't throw Assert.DoesNotThrow(() => PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0)); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -301,17 +303,17 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.Fanoe_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); - //Assert - Re-Import contenttypes doesn't throw + // Assert - Re-Import contenttypes doesn't throw Assert.DoesNotThrow(() => PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0)); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -325,18 +327,18 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.StandardMvc_Package; var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var docTypesElement = xml.Descendants("DocumentTypes").First(); - var element = xml.Descendants("DocumentSet").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement docTypesElement = xml.Descendants("DocumentTypes").First(); + XElement element = xml.Descendants("DocumentSet").First(); var packageDocument = CompiledPackageContentBase.Create(element); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypesElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypesElement.Elements("DocumentType"), 0); var importedContentTypes = contentTypes.ToDictionary(x => x.Alias, x => x); - var contents = PackageDataInstallation.ImportContentBase(packageDocument.Yield(), importedContentTypes, 0, ContentTypeService, ContentService); - var numberOfDocs = (from doc in element.Descendants() - where (string) doc.Attribute("isDoc") == "" + IReadOnlyList contents = PackageDataInstallation.ImportContentBase(packageDocument.Yield(), importedContentTypes, 0, ContentTypeService, ContentService); + int numberOfDocs = (from doc in element.Descendants() + where (string)doc.Attribute("isDoc") == string.Empty select doc).Count(); // Assert @@ -354,16 +356,16 @@ namespace Umbraco.Tests.Packaging Core.Services.Implement.MediaTypeService.ClearScopeEvents(); string strXml = ImportResources.MediaTypesAndMedia_Package_xml; var xml = XElement.Parse(strXml); - var mediaTypesElement = xml.Descendants("MediaTypes").First(); - var element = xml.Descendants("MediaSet").First(); + XElement mediaTypesElement = xml.Descendants("MediaTypes").First(); + XElement element = xml.Descendants("MediaSet").First(); var packageMedia = CompiledPackageContentBase.Create(element); // Act - var mediaTypes = PackageDataInstallation.ImportMediaTypes(mediaTypesElement.Elements("MediaType"), 0); + IReadOnlyList mediaTypes = PackageDataInstallation.ImportMediaTypes(mediaTypesElement.Elements("MediaType"), 0); var importedMediaTypes = mediaTypes.ToDictionary(x => x.Alias, x => x); - var medias = PackageDataInstallation.ImportContentBase(packageMedia.Yield(), importedMediaTypes, 0, MediaTypeService, MediaService); - var numberOfDocs = (from doc in element.Descendants() - where (string) doc.Attribute("isDoc") == "" + IReadOnlyList medias = PackageDataInstallation.ImportContentBase(packageMedia.Yield(), importedMediaTypes, 0, MediaTypeService, MediaService); + int numberOfDocs = (from doc in element.Descendants() + where (string)doc.Attribute("isDoc") == string.Empty select doc).Count(); // Assert @@ -374,35 +376,31 @@ namespace Umbraco.Tests.Packaging } [Test] - public void Can_Import_CheckboxList_Content_Package_Xml_With_Property_Editor_Aliases() - { + public void Can_Import_CheckboxList_Content_Package_Xml_With_Property_Editor_Aliases() => AssertCheckBoxListTests(ImportResources.CheckboxList_Content_Package); - } - - private void AssertCheckBoxListTests(string strXml) { // Arrange var xml = XElement.Parse(strXml); - var dataTypeElement = xml.Descendants("DataTypes").First(); - var docTypesElement = xml.Descendants("DocumentTypes").First(); - var element = xml.Descendants("DocumentSet").First(); + XElement dataTypeElement = xml.Descendants("DataTypes").First(); + XElement docTypesElement = xml.Descendants("DocumentTypes").First(); + XElement element = xml.Descendants("DocumentSet").First(); var packageDocument = CompiledPackageContentBase.Create(element); // Act - var dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypesElement.Elements("DocumentType"), 0); + IReadOnlyList dataTypeDefinitions = PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypesElement.Elements("DocumentType"), 0); var importedContentTypes = contentTypes.ToDictionary(x => x.Alias, x => x); - var contents = PackageDataInstallation.ImportContentBase(packageDocument.Yield(), importedContentTypes, 0, ContentTypeService, ContentService); - var numberOfDocs = (from doc in element.Descendants() - where (string)doc.Attribute("isDoc") == "" + IReadOnlyList contents = PackageDataInstallation.ImportContentBase(packageDocument.Yield(), importedContentTypes, 0, ContentTypeService, ContentService); + int numberOfDocs = (from doc in element.Descendants() + where (string)doc.Attribute("isDoc") == string.Empty select doc).Count(); string configuration; - using (var scope = ScopeProvider.CreateScope()) + using (Core.Scoping.IScope scope = ScopeProvider.CreateScope()) { - var dtos = scope.Database.Fetch("WHERE nodeId = @Id", new { dataTypeDefinitions.First().Id }); + List dtos = scope.Database.Fetch("WHERE nodeId = @Id", new { dataTypeDefinitions.First().Id }); configuration = dtos.Single().Configuration; } @@ -423,12 +421,11 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.XsltSearch_Package; var xml = XElement.Parse(strXml); - var templateElement = xml.Descendants("Templates").First(); - + XElement templateElement = xml.Descendants("Templates").First(); // Act - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + int numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); // Assert Assert.That(templates.Any(), Is.True); @@ -442,9 +439,8 @@ namespace Umbraco.Tests.Packaging string strXml = ImportResources.SingleDocType; var docTypeElement = XElement.Parse(strXml); - // Act - var contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); // Assert Assert.That(contentTypes.Any(), Is.True); @@ -459,12 +455,12 @@ namespace Umbraco.Tests.Packaging string strXml = ImportResources.SingleDocType; var docTypeElement = XElement.Parse(strXml); - var serializer = GetRequiredService(); + IEntityXmlSerializer serializer = GetRequiredService(); // Act - var contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); - var contentType = contentTypes.FirstOrDefault(); - var element = serializer.Serialize(contentType); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); + IContentType contentType = contentTypes.FirstOrDefault(); + XElement element = serializer.Serialize(contentType); // Assert Assert.That(element, Is.Not.Null); @@ -472,8 +468,9 @@ namespace Umbraco.Tests.Packaging Assert.That(element.Element("Structure"), Is.Not.Null); Assert.That(element.Element("GenericProperties"), Is.Not.Null); Assert.That(element.Element("Tabs"), Is.Not.Null); - //Can't compare this XElement because the templates are not imported (they don't exist) - //Assert.That(XNode.DeepEquals(docTypeElement, element), Is.True); + + // Can't compare this XElement because the templates are not imported (they don't exist) + //// Assert.That(XNode.DeepEquals(docTypeElement, element), Is.True); } [Test] @@ -484,8 +481,8 @@ namespace Umbraco.Tests.Packaging var docTypeElement = XElement.Parse(strXml); // Act - var contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); - var contentTypesUpdated = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); + IReadOnlyList contentTypesUpdated = PackageDataInstallation.ImportDocumentType(docTypeElement, 0); // Assert Assert.That(contentTypes.Any(), Is.True); @@ -505,19 +502,19 @@ namespace Umbraco.Tests.Packaging var newPackageXml = XElement.Parse(ImportResources.TemplateOnly_Package); var updatedPackageXml = XElement.Parse(ImportResources.TemplateOnly_Updated_Package); - var templateElement = newPackageXml.Descendants("Templates").First(); - var templateElementUpdated = updatedPackageXml.Descendants("Templates").First(); + XElement templateElement = newPackageXml.Descendants("Templates").First(); + XElement templateElementUpdated = updatedPackageXml.Descendants("Templates").First(); - var fileService = FileService; + IFileService fileService = FileService; // kill default test data fileService.DeleteTemplate("Textpage"); // Act - var numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var templatesAfterUpdate = PackageDataInstallation.ImportTemplates(templateElementUpdated.Elements("Template").ToList(), 0); - var allTemplates = fileService.GetTemplates(); + int numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count(); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList templatesAfterUpdate = PackageDataInstallation.ImportTemplates(templateElementUpdated.Elements("Template").ToList(), 0); + IEnumerable allTemplates = fileService.GetTemplates(); // Assert Assert.That(templates.Any(), Is.True); @@ -537,7 +534,7 @@ namespace Umbraco.Tests.Packaging const string expectedNorwegianChildValue = "BarnVerdi"; var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); AddLanguages(); @@ -559,19 +556,19 @@ namespace Umbraco.Tests.Packaging const string childKey = "Child"; var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); AddLanguages(); // Act - var dictionaryItems = PackageDataInstallation.ImportDictionaryItems(dictionaryItemsElement.Elements("DictionaryItem"), 0); + IReadOnlyList dictionaryItems = PackageDataInstallation.ImportDictionaryItems(dictionaryItemsElement.Elements("DictionaryItem"), 0); // Assert Assert.That(LocalizationService.DictionaryItemExists(parentKey), "DictionaryItem parentKey does not exist"); Assert.That(LocalizationService.DictionaryItemExists(childKey), "DictionaryItem childKey does not exist"); - var parentDictionaryItem = LocalizationService.GetDictionaryItemByKey(parentKey); - var childDictionaryItem = LocalizationService.GetDictionaryItemByKey(childKey); + IDictionaryItem parentDictionaryItem = LocalizationService.GetDictionaryItemByKey(parentKey); + IDictionaryItem childDictionaryItem = LocalizationService.GetDictionaryItemByKey(childKey); Assert.That(parentDictionaryItem.ParentId, Is.Not.EqualTo(childDictionaryItem.ParentId)); Assert.That(childDictionaryItem.ParentId, Is.EqualTo(parentDictionaryItem.Key)); @@ -587,7 +584,7 @@ namespace Umbraco.Tests.Packaging const string expectedNorwegianChildValue = "BarnVerdi"; var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); AddLanguages(); AddExistingEnglishAndNorwegianParentDictionaryItem(expectedEnglishParentValue, expectedNorwegianParentValue); @@ -612,7 +609,7 @@ namespace Umbraco.Tests.Packaging const string expectedNorwegianChildValue = "BarnVerdi"; var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); AddLanguages(); AddExistingEnglishParentDictionaryItem(expectedEnglishParentValue); @@ -632,15 +629,15 @@ namespace Umbraco.Tests.Packaging { // Arrange var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var LanguageItemsElement = newPackageXml.Elements("Languages").First(); + XElement languageItemsElement = newPackageXml.Elements("Languages").First(); // Act - var languages = PackageDataInstallation.ImportLanguages(LanguageItemsElement.Elements("Language"), 0); - var allLanguages = LocalizationService.GetAllLanguages(); + IReadOnlyList languages = PackageDataInstallation.ImportLanguages(languageItemsElement.Elements("Language"), 0); + IEnumerable allLanguages = LocalizationService.GetAllLanguages(); // Assert Assert.That(languages.Any(x => x.HasIdentity == false), Is.False); - foreach (var language in languages) + foreach (ILanguage language in languages) { Assert.That(allLanguages.Any(x => x.IsoCode == language.IsoCode), Is.True); } @@ -652,8 +649,7 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.uBlogsy_Package; var xml = XElement.Parse(strXml); - var macrosElement = xml.Descendants("Macros").First(); - + XElement macrosElement = xml.Descendants("Macros").First(); // Act var macros = PackageDataInstallation.ImportMacros(macrosElement.Elements("macro"), 0).ToList(); @@ -662,7 +658,7 @@ namespace Umbraco.Tests.Packaging Assert.That(macros.Any(), Is.True); var allMacros = MacroService.GetAll().ToList(); - foreach (var macro in macros) + foreach (IMacro macro in macros) { Assert.That(allMacros.Any(x => x.Alias == macro.Alias), Is.True); } @@ -674,8 +670,7 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.XsltSearch_Package; var xml = XElement.Parse(strXml); - var macrosElement = xml.Descendants("Macros").First(); - + XElement macrosElement = xml.Descendants("Macros").First(); // Act var macros = PackageDataInstallation.ImportMacros(macrosElement.Elements("macro"), 0).ToList(); @@ -685,7 +680,7 @@ namespace Umbraco.Tests.Packaging Assert.That(macros.First().Properties.Values.Any(), Is.True); var allMacros = MacroService.GetAll().ToList(); - foreach (var macro in macros) + foreach (IMacro macro in macros) { Assert.That(allMacros.Any(x => x.Alias == macro.Alias), Is.True); } @@ -697,14 +692,13 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.CompositionsTestPackage; var xml = XElement.Parse(strXml); - var templateElement = xml.Descendants("Templates").First(); - var docTypeElement = xml.Descendants("DocumentTypes").First(); - + XElement templateElement = xml.Descendants("Templates").First(); + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList templates = PackageDataInstallation.ImportTemplates(templateElement.Elements("Template").ToList(), 0); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(contentTypes, Is.Not.Null); @@ -712,7 +706,7 @@ namespace Umbraco.Tests.Packaging Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); Assert.That(contentTypes.Count(x => x.ParentId == -1), Is.EqualTo(3)); - var textpage = contentTypes.First(x => x.Alias.Equals("umbTextyPage")); + IContentType textpage = contentTypes.First(x => x.Alias.Equals("umbTextyPage")); Assert.That(textpage.ParentId, Is.Not.EqualTo(-1)); Assert.That(textpage.ContentTypeComposition.Count(), Is.EqualTo(3)); Assert.That(textpage.ContentTypeCompositionExists("umbMaster"), Is.True); @@ -726,19 +720,18 @@ namespace Umbraco.Tests.Packaging // Arrange string strXml = ImportResources.CompositionsTestPackage_Random; var xml = XElement.Parse(strXml); - var docTypeElement = xml.Descendants("DocumentTypes").First(); - + XElement docTypeElement = xml.Descendants("DocumentTypes").First(); // Act - var contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); - var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); + IReadOnlyList contentTypes = PackageDataInstallation.ImportDocumentTypes(docTypeElement.Elements("DocumentType"), 0); + int numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count(); // Assert Assert.That(contentTypes, Is.Not.Null); Assert.That(contentTypes.Any(), Is.True); Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes)); - var testContentType = contentTypes.First(x => x.Alias.Equals("CompositeTest")); + IContentType testContentType = contentTypes.First(x => x.Alias.Equals("CompositeTest")); Assert.That(testContentType.ContentTypeComposition.Count(), Is.EqualTo(3)); Assert.That(testContentType.ContentTypeCompositionExists("Content"), Is.True); Assert.That(testContentType.ContentTypeCompositionExists("Meta"), Is.True); @@ -757,17 +750,17 @@ namespace Umbraco.Tests.Packaging private void AssertDictionaryItem(string key, string expectedValue, string cultureCode) { Assert.That(LocalizationService.DictionaryItemExists(key), "DictionaryItem key does not exist"); - var dictionaryItem = LocalizationService.GetDictionaryItemByKey(key); - var translation = dictionaryItem.Translations.SingleOrDefault(i => i.Language.IsoCode == cultureCode); + IDictionaryItem dictionaryItem = LocalizationService.GetDictionaryItemByKey(key); + IDictionaryTranslation translation = dictionaryItem.Translations.SingleOrDefault(i => i.Language.IsoCode == cultureCode); Assert.IsNotNull(translation, "Translation to {0} was not added", cultureCode); - var value = translation.Value; + string value = translation.Value; Assert.That(value, Is.EqualTo(expectedValue), "Translation value was not set"); } private void AddExistingEnglishParentDictionaryItem(string expectedEnglishParentValue) { var languages = LocalizationService.GetAllLanguages().ToList(); - var englishLanguage = languages.Single(l => l.IsoCode == "en-GB"); + ILanguage englishLanguage = languages.Single(l => l.IsoCode == "en-GB"); LocalizationService.Save( new DictionaryItem("Parent") { @@ -775,15 +768,14 @@ namespace Umbraco.Tests.Packaging { new DictionaryTranslation(englishLanguage, expectedEnglishParentValue), } - } - ); + }); } private void AddExistingEnglishAndNorwegianParentDictionaryItem(string expectedEnglishParentValue, string expectedNorwegianParentValue) { var languages = LocalizationService.GetAllLanguages().ToList(); - var englishLanguage = languages.Single(l => l.IsoCode == "en-GB"); - var norwegianLanguage = languages.Single(l => l.IsoCode == "nb-NO"); + ILanguage englishLanguage = languages.Single(l => l.IsoCode == "en-GB"); + ILanguage norwegianLanguage = languages.Single(l => l.IsoCode == "nb-NO"); LocalizationService.Save( new DictionaryItem("Parent") { @@ -792,8 +784,7 @@ namespace Umbraco.Tests.Packaging new DictionaryTranslation(englishLanguage, expectedEnglishParentValue), new DictionaryTranslation(norwegianLanguage, expectedNorwegianParentValue), } - } - ); + }); } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageInstallationTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageInstallationTest.cs index 93a6ef010b..867a770097 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageInstallationTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Packaging/PackageInstallationTest.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -16,6 +19,7 @@ namespace Umbraco.Tests.Packaging public class PackageInstallationTest : UmbracoIntegrationTest { private IHostingEnvironment HostingEnvironment => GetRequiredService(); + private IPackageInstallation PackageInstallation => GetRequiredService(); private const string DocumentTypePickerPackage = "Document_Type_Picker_1.1.umb"; @@ -24,9 +28,8 @@ namespace Umbraco.Tests.Packaging [Test] public void Can_Read_Compiled_Package_1() { - var package = PackageInstallation.ReadPackage( - //this is where our test zip file is - new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage))); + var testPackageFile = new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage)); + CompiledPackage package = PackageInstallation.ReadPackage(testPackageFile); Assert.IsNotNull(package); Assert.AreEqual(1, package.Files.Count); Assert.AreEqual("095e064b-ba4d-442d-9006-3050983c13d8.dll", package.Files[0].UniqueFileName); @@ -47,9 +50,8 @@ namespace Umbraco.Tests.Packaging [Test] public void Can_Read_Compiled_Package_2() { - var package = PackageInstallation.ReadPackage( - //this is where our test zip file is - new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), HelloPackage))); + var testPackageFile = new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), HelloPackage)); + CompiledPackage package = PackageInstallation.ReadPackage(testPackageFile); Assert.IsNotNull(package); Assert.AreEqual(0, package.Files.Count); Assert.AreEqual("Hello", package.Name); @@ -73,18 +75,17 @@ namespace Umbraco.Tests.Packaging [Test] public void Can_Read_Compiled_Package_Warnings() { - //copy a file to the same path that the package will install so we can detect file conflicts - - var filePath = Path.Combine(HostingEnvironment.MapPathContentRoot("~/"), "bin", "Auros.DocumentTypePicker.dll"); + // Copy a file to the same path that the package will install so we can detect file conflicts. + string filePath = Path.Combine(HostingEnvironment.MapPathContentRoot("~/"), "bin", "Auros.DocumentTypePicker.dll"); Directory.CreateDirectory(Path.GetDirectoryName(filePath)); File.WriteAllText(filePath, "test"); - //this is where our test zip file is - var packageFile = Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage); + // this is where our test zip file is + string packageFile = Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage); Console.WriteLine(packageFile); - var package = PackageInstallation.ReadPackage(new FileInfo(packageFile)); - var preInstallWarnings = package.Warnings; + CompiledPackage package = PackageInstallation.ReadPackage(new FileInfo(packageFile)); + PreInstallWarnings preInstallWarnings = package.Warnings; Assert.IsNotNull(preInstallWarnings); Assert.AreEqual(1, preInstallWarnings.FilesReplaced.Count()); @@ -96,14 +97,13 @@ namespace Umbraco.Tests.Packaging [Test] public void Install_Files() { - var package = PackageInstallation.ReadPackage( - //this is where our test zip file is - new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage))); + var testPackageFile = new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage)); + CompiledPackage package = PackageInstallation.ReadPackage(testPackageFile); var def = PackageDefinition.FromCompiledPackage(package); def.Id = 1; def.PackageId = Guid.NewGuid(); - def.Files = new List(); //clear out the files of the def for testing, this should be populated by the install + def.Files = new List(); // clear out the files of the def for testing, this should be populated by the install var result = PackageInstallation.InstallPackageFiles(def, package, -1).ToList(); @@ -111,26 +111,24 @@ namespace Umbraco.Tests.Packaging Assert.AreEqual(Path.Combine("bin", "Auros.DocumentTypePicker.dll"), result[0]); Assert.IsTrue(File.Exists(Path.Combine(HostingEnvironment.MapPathContentRoot("~/"), result[0]))); - //make sure the def is updated too + // make sure the def is updated too Assert.AreEqual(result.Count, def.Files.Count); } [Test] public void Install_Data() { - var package = PackageInstallation.ReadPackage( - //this is where our test zip file is - new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage))); + var testPackageFile = new FileInfo(Path.Combine(HostingEnvironment.MapPathContentRoot("~/TestData/Packages"), DocumentTypePickerPackage)); + CompiledPackage package = PackageInstallation.ReadPackage(testPackageFile); var def = PackageDefinition.FromCompiledPackage(package); def.Id = 1; def.PackageId = Guid.NewGuid(); - var summary = PackageInstallation.InstallPackageData(def, package, -1); + InstallationSummary summary = PackageInstallation.InstallPackageData(def, package, -1); Assert.AreEqual(1, summary.DataTypesInstalled.Count()); - - //make sure the def is updated too + // make sure the def is updated too Assert.AreEqual(summary.DataTypesInstalled.Count(), def.DataTypes.Count); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Core/Services/SectionServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Core/Services/SectionServiceTests.cs index 24a4e8d772..dd91f3ad55 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Core/Services/SectionServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Core/Services/SectionServiceTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using System.Threading; using NUnit.Framework; using Umbraco.Core.Configuration.Models; @@ -19,13 +22,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Services public class SectionServiceTests : UmbracoIntegrationTest { private ISectionService SectionService => GetRequiredService(); + private IUserService UserService => GetRequiredService(); [Test] public void SectionService_Can_Get_Allowed_Sections_For_User() { // Arrange - var user = CreateTestUser(); + IUser user = CreateTestUser(); // Act var result = SectionService.GetAllowedSections(user.Id).ToList(); @@ -52,6 +56,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Core.Services }; userGroupA.AddAllowedSection("media"); userGroupA.AddAllowedSection("settings"); + // TODO: This is failing the test UserService.Save(userGroupA, new[] { user.Id }, false); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Migrations/AdvancedMigrationTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Migrations/AdvancedMigrationTests.cs index ac502ddf80..92280fde43 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Migrations/AdvancedMigrationTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Migrations/AdvancedMigrationTests.cs @@ -1,20 +1,21 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; using NUnit.Framework; -using Microsoft.Extensions.Logging; using Umbraco.Core.Configuration; using Umbraco.Core.Migrations; using Umbraco.Core.Migrations.Install; using Umbraco.Core.Migrations.Upgrade; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; -using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; -using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; namespace Umbraco.Tests.Migrations @@ -23,24 +24,27 @@ namespace Umbraco.Tests.Migrations [UmbracoTest(Database = UmbracoTestOptions.Database.NewEmptyPerTest)] public class AdvancedMigrationTests : UmbracoIntegrationTest { - private ILoggerFactory _loggerFactory = NullLoggerFactory.Instance; + private readonly ILoggerFactory _loggerFactory = NullLoggerFactory.Instance; private IUmbracoVersion UmbracoVersion => GetRequiredService(); [Test] public void CreateTableOfTDto() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => { if (t != typeof(CreateTableOfTDtoMigration)) + { throw new NotSupportedException(); + } + return new CreateTableOfTDtoMigration(c); }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -50,7 +54,7 @@ namespace Umbraco.Tests.Migrations upgrader.Execute(ScopeProvider, builder, Mock.Of(), _loggerFactory.CreateLogger(), _loggerFactory); var helper = new DatabaseSchemaCreator(scope.Database, LoggerFactory.CreateLogger(), LoggerFactory, UmbracoVersion); - var exists = helper.TableExists("umbracoUser"); + bool exists = helper.TableExists("umbracoUser"); Assert.IsTrue(exists); scope.Complete(); @@ -60,7 +64,7 @@ namespace Umbraco.Tests.Migrations [Test] public void DeleteKeysAndIndexesOfTDto() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => @@ -76,7 +80,7 @@ namespace Umbraco.Tests.Migrations } }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -92,7 +96,7 @@ namespace Umbraco.Tests.Migrations [Test] public void CreateKeysAndIndexesOfTDto() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => @@ -110,7 +114,7 @@ namespace Umbraco.Tests.Migrations } }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -127,7 +131,7 @@ namespace Umbraco.Tests.Migrations [Test] public void CreateKeysAndIndexes() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => @@ -145,7 +149,7 @@ namespace Umbraco.Tests.Migrations } }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -162,7 +166,7 @@ namespace Umbraco.Tests.Migrations [Test] public void CreateColumn() { - var builder = Mock.Of(); + IMigrationBuilder builder = Mock.Of(); Mock.Get(builder) .Setup(x => x.Build(It.IsAny(), It.IsAny())) .Returns((t, c) => @@ -178,7 +182,7 @@ namespace Umbraco.Tests.Migrations } }); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var upgrader = new Upgrader( new MigrationPlan("test") @@ -195,32 +199,38 @@ namespace Umbraco.Tests.Migrations { public CreateTableOfTDtoMigration(IMigrationContext context) : base(context) - { } - - public override void Migrate() { - // creates User table with keys, indexes, etc - Create.Table().Do(); } + + public override void Migrate() => + + // Create User table with keys, indexes, etc. + Create.Table().Do(); } public class DeleteKeysAndIndexesMigration : MigrationBase { public DeleteKeysAndIndexesMigration(IMigrationContext context) : base(context) - { } + { + } public override void Migrate() { // drops User table keys and indexes - //Execute.DropKeysAndIndexes("umbracoUser"); + // Execute.DropKeysAndIndexes("umbracoUser"); // drops *all* tables keys and indexes var tables = SqlSyntax.GetTablesInSchema(Context.Database).ToList(); - foreach (var table in tables) + foreach (string table in tables) + { Delete.KeysAndIndexes(table, false, true).Do(); - foreach (var table in tables) + } + + foreach (string table in tables) + { Delete.KeysAndIndexes(table, true, false).Do(); + } } } @@ -228,28 +238,32 @@ namespace Umbraco.Tests.Migrations { public CreateKeysAndIndexesOfTDtoMigration(IMigrationContext context) : base(context) - { } - - public override void Migrate() { - // creates Node table keys and indexes - Create.KeysAndIndexes().Do(); } + + public override void Migrate() => + + // Create User table keys and indexes. + Create.KeysAndIndexes().Do(); } public class CreateKeysAndIndexesMigration : MigrationBase { public CreateKeysAndIndexesMigration(IMigrationContext context) : base(context) - { } + { + } public override void Migrate() { - // creates *all* tables keys and indexes - foreach (var x in DatabaseSchemaCreator.OrderedTables) + // Creates *all* tables keys and indexes + foreach (Type x in DatabaseSchemaCreator.OrderedTables) { // ok - for tests, restrict to Node - if (x != typeof(UserDto)) continue; + if (x != typeof(UserDto)) + { + continue; + } Create.KeysAndIndexes(x).Do(); } @@ -260,7 +274,8 @@ namespace Umbraco.Tests.Migrations { public CreateColumnMigration(IMigrationContext context) : base(context) - { } + { + } public override void Migrate() { @@ -269,9 +284,9 @@ namespace Umbraco.Tests.Migrations Delete.Column("id").FromTable("umbracoUser").Do(); - var table = DefinitionFactory.GetTableDefinition(typeof(UserDto), SqlSyntax); - var column = table.Columns.First(x => x.Name == "id"); - var create = SqlSyntax.Format(column); // returns [id] INTEGER NOT NULL IDENTITY(1060,1) + TableDefinition table = DefinitionFactory.GetTableDefinition(typeof(UserDto), SqlSyntax); + ColumnDefinition column = table.Columns.First(x => x.Name == "id"); + string create = SqlSyntax.Format(column); // returns [id] INTEGER NOT NULL IDENTITY(1060,1) Database.Execute($"ALTER TABLE {SqlSyntax.GetQuotedTableName("umbracoUser")} ADD " + create); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs index dd66efb47a..cf60557ba5 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs @@ -1,28 +1,30 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text.RegularExpressions; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; +using NPoco; using NUnit.Framework; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Implementations; using Umbraco.Tests.Integration.Testing; -using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTests { // FIXME: npoco - is this still appropriate? - // [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class NPocoBulkInsertTests : UmbracoIntegrationTest { - private TestHelper _testHelper = new TestHelper(); + private readonly TestHelper _testHelper = new TestHelper(); + private IProfilingLogger ProfilingLogger => _testHelper.ProfilingLogger; [NUnit.Framework.Ignore("Ignored because you need to configure your own SQL Server to test this with")] @@ -33,15 +35,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // prob not what we want, this is not a real database, but hey, the test is ignored anyways // we'll fix this when we have proper testing infrastructure // var dbSqlServer = TestObjects.GetUmbracoSqlServerDatabase(new NullLogger()); - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { // Still no what we want, but look above. - var dbSqlServer = scope.Database; - //drop the table + IUmbracoDatabase dbSqlServer = scope.Database; + + // drop the table dbSqlServer.Execute("DROP TABLE [umbracoServer]"); - //re-create it + // re-create it dbSqlServer.Execute(@"CREATE TABLE [umbracoServer]( [id] [int] IDENTITY(1,1) NOT NULL, [address] [nvarchar](500) NOT NULL, @@ -56,7 +58,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] )"); var data = new List(); - for (var i = 0; i < 1000; i++) + for (int i = 0; i < 1000; i++) { data.Add(new ServerRegistrationDto { @@ -68,7 +70,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest }); } - using (var tr = dbSqlServer.GetTransaction()) + using (ITransaction tr = dbSqlServer.GetTransaction()) { dbSqlServer.BulkInsertRecords(data); tr.Complete(); @@ -83,7 +85,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest public void Can_Bulk_Insert_Native_Sql_Bulk_Inserts() { var servers = new List(); - for (var i = 0; i < 1000; i++) + for (int i = 0; i < 1000; i++) { servers.Add(new ServerRegistrationDto { @@ -98,7 +100,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // Act using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.BulkInsertRecords(servers); scope.Complete(); @@ -106,7 +108,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest } // Assert - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { Assert.That(scope.Database.ExecuteScalar("SELECT COUNT(*) FROM umbracoServer"), Is.EqualTo(1000)); } @@ -116,7 +118,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest public void Can_Bulk_Insert_Native_Sql_Bulk_Inserts_Transaction_Rollback() { var servers = new List(); - for (var i = 0; i < 1000; i++) + for (int i = 0; i < 1000; i++) { servers.Add(new ServerRegistrationDto { @@ -131,15 +133,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // Act using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.BulkInsertRecords(servers); - //don't call complete here - the trans will be rolled back + + // Don't call complete here - the transaction will be rolled back. } } // Assert - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { Assert.That(scope.Database.ExecuteScalar("SELECT COUNT(*) FROM umbracoServer"), Is.EqualTo(0)); } @@ -149,7 +152,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest public void Generate_Bulk_Import_Sql() { var servers = new List(); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { servers.Add(new ServerRegistrationDto { @@ -162,23 +165,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest } IDbCommand[] commands; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { commands = scope.Database.GenerateBulkInsertCommands(servers.ToArray()); scope.Complete(); } // Assert - Assert.That(commands[0].CommandText, - Is.EqualTo("INSERT INTO [umbracoServer] ([umbracoServer].[address], [umbracoServer].[computerName], [umbracoServer].[registeredDate], [umbracoServer].[lastNotifiedDate], [umbracoServer].[isActive], [umbracoServer].[isMaster]) VALUES (@0,@1,@2,@3,@4,@5), (@6,@7,@8,@9,@10,@11)")); + Assert.That( + commands[0].CommandText, + Is.EqualTo("INSERT INTO [umbracoServer] ([umbracoServer].[address], [umbracoServer].[computerName], [umbracoServer].[registeredDate], [umbracoServer].[lastNotifiedDate], [umbracoServer].[isActive], [umbracoServer].[isMaster]) VALUES (@0,@1,@2,@3,@4,@5), (@6,@7,@8,@9,@10,@11)")); } - [Test] public void Generate_Bulk_Import_Sql_Exceeding_Max_Params() { var servers = new List(); - for (var i = 0; i < 1500; i++) + for (int i = 0; i < 1500; i++) { servers.Add(new ServerRegistrationDto { @@ -192,7 +195,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest } IDbCommand[] commands; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { commands = scope.Database.GenerateBulkInsertCommands(servers.ToArray()); scope.Complete(); @@ -200,7 +203,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // Assert Assert.That(commands.Length, Is.EqualTo(5)); - foreach (var s in commands.Select(x => x.CommandText)) + foreach (string s in commands.Select(x => x.CommandText)) { Assert.LessOrEqual(Regex.Matches(s, "@\\d+").Count, 2000); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoFetchTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoFetchTests.cs index 58429ed80e..ca248a1c80 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoFetchTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoFetchTests.cs @@ -1,9 +1,13 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using NPoco; using NUnit.Framework; using Umbraco.Core.Persistence; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -16,7 +20,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [SetUp] protected void SeedDatabase() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { InsertData(scope.Database); scope.Complete(); @@ -154,20 +158,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestSimple() { - // fetching a simple POCO - - using (var scope = ScopeProvider.CreateScope()) + // Fetching a simple POCO + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing1.id, zbThing1.name // FROM zbThing1"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select() .From(); - var dtos = scope.Database.Fetch(sql); + List dtos = scope.Database.Fetch(sql); Assert.AreEqual(2, dtos.Count); Assert.AreEqual("one", dtos.First(x => x.Id == 1).Name); } @@ -176,24 +178,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestOneToOne() { - // fetching a POCO that contains the ID of another POCO, - // and fetching that other POCO at the same time - - using (var scope = ScopeProvider.CreateScope()) + // Fetching a POCO that contains the ID of another POCO, + // and fetching that other POCO at the same time. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing2.id, zbThing2.name, zbThing2.thingId, // zbThing1.id Thing__id, zbThing1.name Thing__name // FROM zbThing2 // JOIN zbThing1 ON zbThing2.thingId=zbThing1.id"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select(r => r.Select(x => x.Thing)) .From() .InnerJoin().On((t2, t1) => t2.ThingId == t1.Id); - var dtos = scope.Database.Fetch(sql); + List dtos = scope.Database.Fetch(sql); Assert.AreEqual(3, dtos.Count); Assert.AreEqual("uno", dtos.First(x => x.Id == 1).Name); Assert.IsNotNull(dtos.First(x => x.Id == 1).Thing); @@ -204,37 +204,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestOneToManyOnOne() { - // fetching a POCO that has a list of other POCOs, + // Fetching a POCO that has a list of other POCOs, // and fetching these POCOs at the same time, // with a pk/fk relationship - // for one single POCO - - using (var scope = ScopeProvider.CreateScope()) + // for one single POCO. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, @" // SELECT zbThing1.id AS Id, zbThing1.name AS Name, // zbThing2.id AS Things__Id, zbThing2.name AS Things__Name, zbThing2.thingId AS Things__ThingId // FROM zbThing1 // JOIN zbThing2 ON zbThing1.id=zbThing2.thingId // WHERE zbThing1.id=1"); - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select(r => r.Select(x => x.Things)) .From() .InnerJoin().On(left => left.Id, right => right.ThingId) .Where(x => x.Id == 1); - //var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, sql); - var dtos = scope.Database.FetchOneToMany(x => x.Things, sql); + // var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, sql); + List dtos = scope.Database.FetchOneToMany(x => x.Things, sql); Assert.AreEqual(1, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing3Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.IsNotNull(dto1.Things); Assert.AreEqual(2, dto1.Things.Count); - var dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); + Thing2Dto dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto2); Assert.AreEqual("uno", dto2.Name); } @@ -243,39 +241,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestOneToManyOnMany() { - // fetching a POCO that has a list of other POCOs, + // Fetching a POCO that has a list of other POCOs, // and fetching these POCOs at the same time, // with a pk/fk relationship - // for several POCOs + // for several POCOs. // - // the ORDER BY clause (matching x => x.Id) is required - // for proper aggregation to take place - - using (var scope = ScopeProvider.CreateScope()) + // The ORDER BY clause (matching x => x.Id) is required + // for proper aggregation to take place. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing1.id AS Id, zbThing1.name AS Name, // zbThing2.id AS Things__Id, zbThing2.name AS Things__Name, zbThing2.thingId AS Things__ThingId // FROM zbThing1 // JOIN zbThing2 ON zbThing1.id=zbThing2.thingId // ORDER BY zbThing1.id"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select(r => r.Select(x => x.Things)) // select Thing3Dto, and Thing2Dto for Things .From() .InnerJoin().On(left => left.Id, right => right.ThingId) .OrderBy(x => x.Id); - var dtos = scope.Database.FetchOneToMany(x => x.Things, /*x => x.Id,*/ sql); + List dtos = scope.Database.FetchOneToMany(x => x.Things, /*x => x.Id,*/ sql); Assert.AreEqual(2, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing3Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.IsNotNull(dto1.Things); Assert.AreEqual(2, dto1.Things.Count); - var dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); + Thing2Dto dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto2); Assert.AreEqual("uno", dto2.Name); } @@ -284,11 +280,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestOneToManyOnManyTemplate() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.SqlContext.Templates.Clear(); - var sql = scope.SqlContext.Templates.Get("xxx", s => s + Sql sql = scope.SqlContext.Templates.Get("xxx", s => s .Select(r => r.Select(x => x.Things)) // select Thing3Dto, and Thing2Dto for Things .From() .InnerJoin().On(left => left.Id, right => right.ThingId) @@ -297,15 +293,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest // cached sql = scope.SqlContext.Templates.Get("xxx", s => throw new InvalidOperationException()).Sql(); - var dtos = scope.Database.FetchOneToMany(x => x.Things, /*x => x.Id,*/ sql); + List dtos = scope.Database.FetchOneToMany(x => x.Things, /*x => x.Id,*/ sql); Assert.AreEqual(2, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing3Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.IsNotNull(dto1.Things); Assert.AreEqual(2, dto1.Things.Count); - var dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); + Thing2Dto dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto2); Assert.AreEqual("uno", dto2.Name); } @@ -314,39 +310,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestManyToMany() { - // fetching a POCO that has a list of other POCOs, + // Fetching a POCO that has a list of other POCOs, // and fetching these POCOs at the same time, - // with an n-to-n intermediate table + // with an n-to-n intermediate table. // - // the ORDER BY clause (matching x => x.Id) is required - // for proper aggregation to take place - - using (var scope = ScopeProvider.CreateScope()) + // The ORDER BY clause (matching x => x.Id) is required + // for proper aggregation to take place. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing1.id, zbThing1.name, zbThingGroup.id, zbThingGroup.name // FROM zbThing1 // JOIN zbThing2Group ON zbThing1.id=zbThing2Group.thingId // JOIN zbThingGroup ON zbThing2Group.groupId=zbThingGroup.id // ORDER BY zbThing1.id"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select(r => r.Select(x => x.Groups)) .From() .InnerJoin().On((t, t2g) => t.Id == t2g.ThingId) .InnerJoin().On((t2g, tg) => t2g.GroupId == tg.Id) .OrderBy(x => x.Id); - var dtos = scope.Database.FetchOneToMany(x => x.Groups, /*x => x.Id,*/ sql); + List dtos = scope.Database.FetchOneToMany(x => x.Groups, /*x => x.Id,*/ sql); Assert.AreEqual(2, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing4Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.IsNotNull(dto1.Groups); Assert.AreEqual(2, dto1.Groups.Count); - var dto2 = dto1.Groups.FirstOrDefault(x => x.Id == 1); + ThingGroupDto dto2 = dto1.Groups.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto2); Assert.AreEqual("g-one", dto2.Name); } @@ -355,33 +349,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestCalculated() { - // fetching a POCO that has a countof other POCOs, - // with an n-to-n intermediate table - - using (var scope = ScopeProvider.CreateScope()) + // Fetching a POCO that has a countof other POCOs, + // with an n-to-n intermediate table. + using (IScope scope = ScopeProvider.CreateScope()) { - // this is the raw SQL, but it's better to use expressions and no magic strings! - //var sql = @" + // This is the raw SQL, but it's better to use expressions and no magic strings! + // var sql = @" // SELECT zbThing1.id, zbThing1.name, COUNT(zbThing2Group.groupId) as groupCount // FROM zbThing1 // JOIN zbThing2Group ON zbThing1.id=zbThing2Group.thingId // GROUP BY zbThing1.id, zbThing1.name"; - - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .Select() .Append(", COUNT(zbThing2Group.groupId) AS groupCount") // FIXME: .From() .InnerJoin().On((t, t2g) => t.Id == t2g.ThingId) .GroupBy(x => x.Id, x => x.Name); - var dtos = scope.Database.Fetch(sql); + List dtos = scope.Database.Fetch(sql); Assert.AreEqual(2, dtos.Count); - var dto1 = dtos.FirstOrDefault(x => x.Id == 1); + Thing5Dto dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); Assert.AreEqual("one", dto1.Name); Assert.AreEqual(2, dto1.GroupCount); - var dto2 = dtos.FirstOrDefault(x => x.Id == 2); + Thing5Dto dto2 = dtos.FirstOrDefault(x => x.Id == 2); Assert.IsNotNull(dto2); Assert.AreEqual("two", dto2.Name); Assert.AreEqual(1, dto2.GroupCount); @@ -395,22 +387,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestSql() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var sql = scope.SqlContext.Sql() + Sql sql = scope.SqlContext.Sql() .SelectAll() .From() .Where(x => x.Id == 1); - var dto = scope.Database.Fetch(sql).FirstOrDefault(); + Thing1Dto dto = scope.Database.Fetch(sql).FirstOrDefault(); Assert.IsNotNull(dto); Assert.AreEqual("one", dto.Name); - //var sql2 = new Sql(sql.SQL, new { id = 1 }); - //WriteSql(sql2); - //dto = Database.Fetch(sql2).FirstOrDefault(); - //Assert.IsNotNull(dto); - //Assert.AreEqual("one", dto.Name); + //// var sql2 = new Sql(sql.SQL, new { id = 1 }); + //// WriteSql(sql2); + //// dto = Database.Fetch(sql2).FirstOrDefault(); + //// Assert.IsNotNull(dto); + //// Assert.AreEqual("one", dto.Name); var sql3 = new Sql(sql.SQL, 1); dto = scope.Database.Fetch(sql3).FirstOrDefault(); @@ -422,7 +414,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest [Test] public void TestMultipleOneToOne() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { var tA1A = new ThingA1Dto { Id = 1, Name = "a1_a" }; scope.Database.Insert(tA1A); @@ -448,7 +440,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.NPocoTest var k2 = new ThingA12Dto { Name = "B", Thing1Id = tA1A.Id, Thing2Id = tA2B.Id }; scope.Database.Insert(k2); - var sql = @"SELECT a1.id, a1.name, + string sql = @"SELECT a1.id, a1.name, a2.id AS T2A__Id, a2.name AS T2A__Name, a3.id AS T2A__T3__Id, a3.name AS T2A__T3__Name, a2x.id AS T2B__Id, a2x.name AS T2B__Name, a3x.id AS T2B__T3__Id, a3x.name AS T2B__T3__Name FROM zbThingA1 a1 @@ -460,10 +452,10 @@ JOIN zbThingA2 a2x ON a12x.thing2id=a2x.id JOIN zbThingA3 a3x ON a2x.id=a3x.id "; - var ts = scope.Database.Fetch(sql); + List ts = scope.Database.Fetch(sql); Assert.AreEqual(1, ts.Count); - var t = ts.First(); + ThingA1Dto t = ts.First(); Assert.AreEqual("a1_a", t.Name); Assert.AreEqual("a2_a", t.T2A.Name); Assert.AreEqual("a2_b", t.T2B.Name); @@ -578,7 +570,6 @@ JOIN zbThingA3 a3x ON a2x.id=a3x.id [Column("groupCount")] [ResultColumn] // not included in insert/update, not sql-generated - //[ComputedColumn] // not included in insert/update, sql-generated public int GroupCount { get; set; } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/AuditRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/AuditRepositoryTest.cs index d62e0623b1..10e89bc83a 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/AuditRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/AuditRepositoryTest.cs @@ -1,14 +1,19 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; +using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; -using Microsoft.Extensions.Logging; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories { @@ -19,21 +24,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private ILogger _logger; [SetUp] - public void Prepare() - { - _logger = LoggerFactory.CreateLogger(); - } + public void Prepare() => _logger = LoggerFactory.CreateLogger(); [Test] public void Can_Add_Audit_Entry() { - var sp = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); repo.Save(new AuditItem(-1, AuditType.System, -1, UmbracoObjectTypes.Document.GetName(), "This is a System audit trail")); - var dtos = scope.Database.Fetch("WHERE id > -1"); + List dtos = scope.Database.Fetch("WHERE id > -1"); Assert.That(dtos.Any(), Is.True); Assert.That(dtos.First().Comment, Is.EqualTo("This is a System audit trail")); @@ -43,12 +45,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Items() { - var sp = ScopeProvider; - using (var scope = sp.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - for (var i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { repo.Save(new AuditItem(i, AuditType.New, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} created")); repo.Save(new AuditItem(i, AuditType.Publish, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} published")); @@ -57,11 +59,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); } - using (var scope = sp.CreateScope()) + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - var page = repo.GetPagedResultsByQuery(sp.SqlContext.Query(), 0, 10, out var total, Direction.Descending, null, null); + IEnumerable page = repo.GetPagedResultsByQuery(sp.SqlContext.Query(), 0, 10, out long total, Direction.Descending, null, null); Assert.AreEqual(10, page.Count()); Assert.AreEqual(200, total); @@ -71,12 +73,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Items_By_User_Id_With_Query_And_Filter() { - var sp = ScopeProvider; - using (var scope = sp.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - for (var i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { repo.Save(new AuditItem(i, AuditType.New, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} created")); repo.Save(new AuditItem(i, AuditType.Publish, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} published")); @@ -85,20 +87,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); } - using (var scope = sp.CreateScope()) + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - var query = sp.SqlContext.Query().Where(x => x.UserId == -1); + IQuery query = sp.SqlContext.Query().Where(x => x.UserId == -1); try { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var page = repo.GetPagedResultsByQuery(query, 0, 10, out var total, Direction.Descending, + IEnumerable page = repo.GetPagedResultsByQuery( + query, + 0, + 10, + out long total, + Direction.Descending, new[] { AuditType.Publish }, - sp.SqlContext.Query().Where(x => x.UserId > -2)); + sp.SqlContext.Query() + .Where(x => x.UserId > -2)); Assert.AreEqual(10, page.Count()); Assert.AreEqual(100, total); @@ -114,12 +122,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Items_With_AuditType_Filter() { - var sp = ScopeProvider; - using (var scope = sp.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - for (var i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { repo.Save(new AuditItem(i, AuditType.New, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} created")); repo.Save(new AuditItem(i, AuditType.Publish, -1, UmbracoObjectTypes.Document.GetName(), $"Content {i} published")); @@ -128,12 +136,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); } - using (var scope = sp.CreateScope()) + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - var page = repo.GetPagedResultsByQuery(sp.SqlContext.Query(), 0, 9, out var total, Direction.Descending, - new[] { AuditType.Publish }, null) + IAuditItem[] page = repo.GetPagedResultsByQuery( + sp.SqlContext.Query(), + 0, + 9, + out long total, + Direction.Descending, + new[] { AuditType.Publish }, + null) .ToArray(); Assert.AreEqual(9, page.Length); @@ -145,12 +159,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Items_With_Custom_Filter() { - var sp = ScopeProvider; - using (var scope = sp.CreateScope()) + IScopeProvider sp = ScopeProvider; + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - for (var i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { repo.Save(new AuditItem(i, AuditType.New, -1, UmbracoObjectTypes.Document.GetName(), "Content created")); repo.Save(new AuditItem(i, AuditType.Publish, -1, UmbracoObjectTypes.Document.GetName(), "Content published")); @@ -159,12 +173,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); } - using (var scope = sp.CreateScope()) + using (IScope scope = sp.CreateScope()) { var repo = new AuditRepository((IScopeAccessor)sp, _logger); - var page = repo.GetPagedResultsByQuery(sp.SqlContext.Query(), 0, 8, out var total, Direction.Descending, - null, sp.SqlContext.Query().Where(item => item.Comment == "Content created")) + IAuditItem[] page = repo.GetPagedResultsByQuery( + sp.SqlContext.Query(), + 0, + 8, + out long total, + Direction.Descending, + null, + sp.SqlContext.Query() + .Where(item => item.Comment == "Content created")) .ToArray(); Assert.AreEqual(8, page.Length); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs index 5013823540..b297594e2d 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ContentTypeRepositoryTest.cs @@ -1,26 +1,23 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; -using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; -using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; using Umbraco.Web.Models.ContentEditing; @@ -32,31 +29,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { private ContentType _simpleContentType; private ContentType _textpageContentType; - private IFileSystems FileSystems => GetRequiredService(); - private UmbracoMapper Mapper => GetRequiredService(); - private IContentTypeService ContentTypeService => GetRequiredService(); - private IDocumentTypeContainerRepository DocumentTypeContainerRepository => GetRequiredService(); - private IMediaTypeContainerRepository MediaTypeContainerRepository => GetRequiredService(); - private IMediaTypeRepository MediaTypeRepository => GetRequiredService(); - private IDocumentRepository DocumentRepository => GetRequiredService(); - private ContentTypeRepository ContentTypeRepository => (ContentTypeRepository) GetRequiredService(); + private IFileSystems FileSystems => GetRequiredService(); + + private UmbracoMapper Mapper => GetRequiredService(); + + private IContentTypeService ContentTypeService => GetRequiredService(); + + private IDocumentTypeContainerRepository DocumentTypeContainerRepository => GetRequiredService(); + + private IMediaTypeContainerRepository MediaTypeContainerRepository => GetRequiredService(); + + private IMediaTypeRepository MediaTypeRepository => GetRequiredService(); + + private IDocumentRepository DocumentRepository => GetRequiredService(); + + private ContentTypeRepository ContentTypeRepository => (ContentTypeRepository)GetRequiredService(); [SetUp] - public void SetUpData() - { - CreateTestData(); - } + public void SetUpData() => CreateTestData(); public void CreateTestData() { - //Create and Save ContentType "umbTextpage" -> (_simpleContentType.Id) + // Create and Save ContentType "umbTextpage" -> (_simpleContentType.Id) _simpleContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: 0); ContentTypeService.Save(_simpleContentType); - //Create and Save ContentType "textPage" -> (_textpageContentType.Id) - _textpageContentType = ContentTypeBuilder.CreateTextPageContentType( defaultTemplateId: 0); + // Create and Save ContentType "textPage" -> (_textpageContentType.Id) + _textpageContentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: 0); ContentTypeService.Save(_textpageContentType); } @@ -66,60 +67,53 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Maps_Templates_Correctly() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var templateRepo = new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); - var repository = ContentTypeRepository; - var templates = new[] + var templateRepo = new TemplateRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); + ContentTypeRepository repository = ContentTypeRepository; + Template[] templates = new[] { new Template(ShortStringHelper, "test1", "test1"), new Template(ShortStringHelper, "test2", "test2"), new Template(ShortStringHelper, "test3", "test3") }; - foreach (var template in templates) + foreach (Template template in templates) { templateRepo.Save(template); } - - var contentType = ContentTypeBuilder.CreateSimpleContentType(); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(); contentType.AllowedTemplates = new[] { templates[0], templates[1] }; contentType.SetDefaultTemplate(templates[0]); repository.Save(contentType); - - //re-get - var result = repository.Get(contentType.Id); + // re-get + IContentType result = repository.Get(contentType.Id); Assert.AreEqual(2, result.AllowedTemplates.Count()); Assert.AreEqual(templates[0].Id, result.DefaultTemplate.Id); } - } [Test] public void Can_Move() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; var container1 = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "blah1" }; DocumentTypeContainerRepository.Save(container1); - var container2 = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "blah2", ParentId = container1.Id }; DocumentTypeContainerRepository.Save(container2); - var contentType = (IContentType)ContentTypeBuilder.CreateBasicContentType("asdfasdf"); contentType.ParentId = container2.Id; repository.Save(contentType); - - //create a + // create a var contentType2 = (IContentType)new ContentType(ShortStringHelper, contentType, "hello") { Name = "Blahasdfsadf" @@ -127,13 +121,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor contentType.ParentId = contentType.Id; repository.Save(contentType2); - - var result = repository.Move(contentType, container1).ToArray(); - + global::Umbraco.Core.Events.MoveEventInfo[] result = repository.Move(contentType, container1).ToArray(); Assert.AreEqual(2, result.Count()); - //re-get + // re-get contentType = repository.Get(contentType.Id); contentType2 = repository.Get(contentType2.Id); @@ -141,22 +133,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType.Id).OriginalPath, contentType.Path); Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType2.Id).OriginalPath, contentType2.Path); } - } [Test] public void Can_Create_Container() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var container = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "blah" }; DocumentTypeContainerRepository.Save(container); Assert.That(container.Id, Is.GreaterThan(0)); - var found = DocumentTypeContainerRepository.Get(container.Id); + EntityContainer found = DocumentTypeContainerRepository.Get(container.Id); Assert.IsNotNull(found); } } @@ -166,10 +156,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { EntityContainer container1, container2, container3; - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - container1 = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "container1" }; DocumentTypeContainerRepository.Save(container1); container2 = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "container2" }; @@ -181,13 +170,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(container2.Id, Is.GreaterThan(0)); Assert.That(container3.Id, Is.GreaterThan(0)); - var found1 = DocumentTypeContainerRepository.Get(container1.Id); + EntityContainer found1 = DocumentTypeContainerRepository.Get(container1.Id); Assert.IsNotNull(found1); - var found2 = DocumentTypeContainerRepository.Get(container2.Id); + EntityContainer found2 = DocumentTypeContainerRepository.Get(container2.Id); Assert.IsNotNull(found2); - var found3 = DocumentTypeContainerRepository.Get(container3.Id); + EntityContainer found3 = DocumentTypeContainerRepository.Get(container3.Id); Assert.IsNotNull(found3); - var allContainers = DocumentTypeContainerRepository.GetMany(); + IEnumerable allContainers = DocumentTypeContainerRepository.GetMany(); Assert.AreEqual(3, allContainers.Count()); } } @@ -195,18 +184,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete_Container() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var container = new EntityContainer(Constants.ObjectTypes.DocumentType) { Name = "blah" }; DocumentTypeContainerRepository.Save(container); - // Act DocumentTypeContainerRepository.Delete(container); - - var found = DocumentTypeContainerRepository.Get(container.Id); + EntityContainer found = DocumentTypeContainerRepository.Get(container.Id); Assert.IsNull(found); } } @@ -214,19 +201,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_Container_Containing_Media_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; MediaTypeContainerRepository.Save(container); - - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", propertyGroupName: "testGroup", defaultTemplateId:0); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", propertyGroupName: "testGroup", defaultTemplateId: 0); contentType.ParentId = container.Id; repository.Save(contentType); - Assert.AreEqual(container.Id, contentType.ParentId); } } @@ -234,24 +219,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete_Container_Containing_Media_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; MediaTypeContainerRepository.Save(container); - IMediaType contentType = MediaTypeBuilder.CreateSimpleMediaType("test", "Test", propertyGroupName: "testGroup"); contentType.ParentId = container.Id; MediaTypeRepository.Save(contentType); - // Act MediaTypeContainerRepository.Delete(container); - - var found = MediaTypeContainerRepository.Get(container.Id); + EntityContainer found = MediaTypeContainerRepository.Get(container.Id); Assert.IsNull(found); contentType = MediaTypeRepository.Get(contentType.Id); @@ -264,16 +245,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - // Act - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", propertyGroupName: "testGroup"); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", propertyGroupName: "testGroup"); ContentTypeRepository.Save(contentType); - - var fetched = ContentTypeRepository.Get(contentType.Id); + IContentType fetched = ContentTypeRepository.Get(contentType.Id); // Assert Assert.That(contentType.HasIdentity, Is.True); @@ -283,15 +262,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.SortOrder, Is.GreaterThan(0)); Assert.That(contentType.PropertyGroups.ElementAt(0).Name == "testGroup", Is.True); - var groupId = contentType.PropertyGroups.ElementAt(0).Id; + int groupId = contentType.PropertyGroups.ElementAt(0).Id; Assert.That(contentType.PropertyTypes.All(x => x.PropertyGroupId.Value == groupId), Is.True); - foreach (var propertyType in contentType.PropertyTypes) + foreach (IPropertyType propertyType in contentType.PropertyTypes) { Assert.AreNotEqual(propertyType.Key, Guid.Empty); } - TestHelper.AssertPropertyValuesAreEqual(fetched, contentType, "yyyy-MM-dd HH:mm:ss", ignoreProperties: new [] { "DefaultTemplate", "AllowedTemplates", "UpdateDate" }); + TestHelper.AssertPropertyValuesAreEqual(fetched, contentType, ignoreProperties: new[] { "DefaultTemplate", "AllowedTemplates", "UpdateDate" }); } } @@ -299,10 +278,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_ContentTypeRepository_After_Model_Mapping() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act var contentType = (IContentType)ContentTypeBuilder.CreateSimpleContentType2("test", "Test", propertyGroupName: "testGroup"); @@ -313,18 +293,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // there is NO mapping from display to contentType, but only from save // to contentType, so if we want to test, let's to it properly! - var display = Mapper.Map(contentType); - var save = MapToContentTypeSave(display); - var mapped = Mapper.Map(save); + DocumentTypeDisplay display = Mapper.Map(contentType); + DocumentTypeSave save = MapToContentTypeSave(display); + IContentType mapped = Mapper.Map(save); Assert.AreEqual(4, mapped.PropertyTypes.Count()); repository.Save(mapped); - Assert.AreEqual(4, mapped.PropertyTypes.Count()); - //re-get + // re-get contentType = repository.Get(mapped.Id); Assert.AreEqual(4, contentType.PropertyTypes.Count()); @@ -336,29 +315,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.Path.Contains(","), Is.True); Assert.That(contentType.SortOrder, Is.GreaterThan(0)); - Assert.That(contentType.PropertyGroups.ElementAt(0).Name == "testGroup", Is.True); - var groupId = contentType.PropertyGroups.ElementAt(0).Id; + int groupId = contentType.PropertyGroups.ElementAt(0).Id; - var propertyTypes = contentType.PropertyTypes.ToArray(); + IPropertyType[] propertyTypes = contentType.PropertyTypes.ToArray(); Assert.AreEqual("gen", propertyTypes[0].Alias); // just to be sure Assert.IsNull(propertyTypes[0].PropertyGroupId); - Assert.IsTrue(propertyTypes.Skip(1).All((x => x.PropertyGroupId.Value == groupId))); - Assert.That(propertyTypes.Single(x=> x.Alias == "title").LabelOnTop, Is.True); + Assert.IsTrue(propertyTypes.Skip(1).All(x => x.PropertyGroupId.Value == groupId)); + Assert.That(propertyTypes.Single(x => x.Alias == "title").LabelOnTop, Is.True); } - } [Test] public void Can_Perform_Update_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); contentType.Thumbnail = "Doc2.png"; contentType.PropertyGroups["Content"].PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "subtitle") @@ -372,8 +350,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }); repository.Save(contentType); - - var dirty = contentType.IsDirty(); + bool dirty = contentType.IsDirty(); // Assert Assert.That(contentType.HasIdentity, Is.True); @@ -381,17 +358,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.Thumbnail, Is.EqualTo("Doc2.png")); Assert.That(contentType.PropertyTypes.Any(x => x.Alias == "subtitle"), Is.True); Assert.That(contentType.PropertyTypes.Single(x => x.Alias == "subtitle").LabelOnTop, Is.True); - } - - } // this is for tests only because it makes no sense at all to have such a // mapping defined, we only need it for the weird tests that use it - private DocumentTypeSave MapToContentTypeSave(DocumentTypeDisplay display) - { - return new DocumentTypeSave + private DocumentTypeSave MapToContentTypeSave(DocumentTypeDisplay display) => + new DocumentTypeSave { // EntityBasic Name = display.Name, @@ -399,9 +372,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Trashed = display.Trashed, Key = display.Key, ParentId = display.ParentId, - //Alias = display.Alias, + //// Alias = display.Alias, Path = display.Path, - //AdditionalData = display.AdditionalData, + //// AdditionalData = display.AdditionalData, // ContentTypeBasic Alias = display.Alias, @@ -416,7 +389,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor AllowAsRoot = display.AllowAsRoot, AllowedTemplates = display.AllowedTemplates.Select(x => x.Alias), AllowedContentTypes = display.AllowedContentTypes, - DefaultTemplate = display.DefaultTemplate == null ? null : display.DefaultTemplate.Alias, + DefaultTemplate = display.DefaultTemplate?.Alias, Groups = display.Groups.Select(x => new PropertyGroupBasic { Inherited = x.Inherited, @@ -426,27 +399,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Name = x.Name }).ToArray() }; - } [Test] public void Can_Perform_Update_On_ContentTypeRepository_After_Model_Mapping() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); // there is NO mapping from display to contentType, but only from save // to contentType, so if we want to test, let's to it properly! - var display = Mapper.Map(contentType); - var save = MapToContentTypeSave(display); + DocumentTypeDisplay display = Mapper.Map(contentType); + DocumentTypeSave save = MapToContentTypeSave(display); // modify... save.Thumbnail = "Doc2.png"; - var contentGroup = save.Groups.Single(x => x.Name == "Content"); + PropertyGroupBasic contentGroup = save.Groups.Single(x => x.Name == "Content"); contentGroup.Properties = contentGroup.Properties.Concat(new[] { new PropertyTypeBasic @@ -457,7 +430,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Validation = new PropertyTypeValidation { Mandatory = false, - Pattern = "" + Pattern = string.Empty }, SortOrder = 1, DataTypeId = -88, @@ -465,7 +438,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } }); - var mapped = Mapper.Map(save, contentType); + IContentType mapped = Mapper.Map(save, contentType); // just making sure Assert.AreEqual(mapped.Thumbnail, "Doc2.png"); @@ -474,10 +447,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(mapped); + bool dirty = mapped.IsDirty(); - var dirty = mapped.IsDirty(); - - //re-get + // re-get contentType = repository.Get(_textpageContentType.Id); // Assert @@ -488,7 +460,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.PropertyTypes.Single(x => x.Alias == "subtitle").LabelOnTop, Is.True); - foreach (var propertyType in contentType.PropertyTypes) + foreach (IPropertyType propertyType in contentType.PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); Assert.Greater(propertyType.Id, 0); @@ -500,20 +472,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId:0); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: 0); repository.Save(contentType); - - var contentType2 = repository.Get(contentType.Id); + IContentType contentType2 = repository.Get(contentType.Id); repository.Delete(contentType2); - - var exists = repository.Exists(contentType.Id); + bool exists = repository.Exists(contentType.Id); // Assert Assert.That(exists, Is.False); @@ -524,25 +495,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_With_Heirarchy_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var ctMain = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId:0); - var ctChild1 = ContentTypeBuilder.CreateSimpleContentType("child1", "Child 1", ctMain, randomizeAliases: true, defaultTemplateId: 0); - var ctChild2 = ContentTypeBuilder.CreateSimpleContentType("child2", "Child 2", ctChild1, randomizeAliases: true, defaultTemplateId: 0); + ContentTypeRepository repository = ContentTypeRepository; + ContentType ctMain = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: 0); + ContentType ctChild1 = ContentTypeBuilder.CreateSimpleContentType("child1", "Child 1", ctMain, randomizeAliases: true, defaultTemplateId: 0); + ContentType ctChild2 = ContentTypeBuilder.CreateSimpleContentType("child2", "Child 2", ctChild1, randomizeAliases: true, defaultTemplateId: 0); repository.Save(ctMain); repository.Save(ctChild1); repository.Save(ctChild2); - // Act - - var resolvedParent = repository.Get(ctMain.Id); + IContentType resolvedParent = repository.Get(ctMain.Id); repository.Delete(resolvedParent); - // Assert Assert.That(repository.Exists(ctMain.Id), Is.False); Assert.That(repository.Exists(ctChild1.Id), Is.False); @@ -556,27 +524,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor IContentType contentType; // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; contentType = repository.Get(_textpageContentType.Id); - var child1 = ContentTypeBuilder.CreateSimpleContentType("abc", "abc", contentType, randomizeAliases: true, defaultTemplateId:0); + ContentType child1 = ContentTypeBuilder.CreateSimpleContentType("abc", "abc", contentType, randomizeAliases: true, defaultTemplateId: 0); repository.Save(child1); - var child3 = ContentTypeBuilder.CreateSimpleContentType("zyx", "zyx", contentType, randomizeAliases: true, defaultTemplateId:0); + ContentType child3 = ContentTypeBuilder.CreateSimpleContentType("zyx", "zyx", contentType, randomizeAliases: true, defaultTemplateId: 0); repository.Save(child3); - var child2 = ContentTypeBuilder.CreateSimpleContentType("a123", "a123", contentType, randomizeAliases: true, defaultTemplateId:0); + ContentType child2 = ContentTypeBuilder.CreateSimpleContentType("a123", "a123", contentType, randomizeAliases: true, defaultTemplateId: 0); repository.Save(child2); scope.Complete(); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var contentTypes = repository.Get(scope.SqlContext.Query().Where(x => x.ParentId == contentType.Id)); + IEnumerable contentTypes = repository.Get(scope.SqlContext.Query().Where(x => x.ParentId == contentType.Id)); // Assert Assert.That(contentTypes.Count(), Is.EqualTo(3)); @@ -584,20 +552,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual("abc", contentTypes.ElementAt(1).Name); Assert.AreEqual("zyx", contentTypes.ElementAt(2).Name); } - } [Test] public void Can_Perform_Get_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); // Assert Assert.That(contentType, Is.Not.Null); @@ -609,17 +576,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_By_Guid_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); - var childContentType = ContentTypeBuilder.CreateSimpleContentType("blah", "Blah", contentType, randomizeAliases:true, defaultTemplateId:0); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); + ContentType childContentType = ContentTypeBuilder.CreateSimpleContentType("blah", "Blah", contentType, randomizeAliases: true, defaultTemplateId: 0); repository.Save(childContentType); - // Act - var result = repository.Get(childContentType.Key); + IContentType result = repository.Get(childContentType.Key); // Assert Assert.That(result, Is.Not.Null); @@ -631,12 +597,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_By_Missing_Guid_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; + // Act - var result = repository.Get(Guid.NewGuid()); + IContentType result = repository.Get(Guid.NewGuid()); // Assert Assert.That(result, Is.Null); @@ -647,17 +614,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var repository = (ContentTypeRepository)ContentTypeRepository; // Act - var contentTypes = repository.GetMany(); + IEnumerable contentTypes = repository.GetMany(); int count = scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM umbracoNode WHERE nodeObjectType = @NodeObjectType", - new {NodeObjectType = Constants.ObjectTypes.DocumentType}); + new { NodeObjectType = Constants.ObjectTypes.DocumentType }); // Assert Assert.That(contentTypes.Any(), Is.True); @@ -669,14 +636,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_By_Guid_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var repository = (ContentTypeRepository)ContentTypeRepository; - var allGuidIds = repository.GetMany().Select(x => x.Key).ToArray(); + Guid[] allGuidIds = repository.GetMany().Select(x => x.Key).ToArray(); // Act - var contentTypes = ((IReadRepository)repository).GetMany(allGuidIds); + IEnumerable contentTypes = ((IReadRepository)repository).GetMany(allGuidIds); int count = scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM umbracoNode WHERE nodeObjectType = @NodeObjectType", @@ -692,13 +659,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_ContentTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var exists = repository.Exists(_simpleContentType.Id); + bool exists = repository.Exists(_simpleContentType.Id); // Assert Assert.That(exists, Is.True); @@ -709,18 +676,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_ContentType_With_PropertyType_Removed() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); // Act contentType.PropertyGroups["Meta"].PropertyTypes.Remove("description"); repository.Save(contentType); - - var result = repository.Get(_textpageContentType.Id); + IContentType result = repository.Get(_textpageContentType.Id); // Assert Assert.That(result.PropertyTypes.Any(x => x.Alias == "description"), Is.False); @@ -733,13 +699,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyTypes_On_SimpleTextpage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var contentType = repository.Get(_simpleContentType.Id); + IContentType contentType = repository.Get(_simpleContentType.Id); // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(3)); @@ -751,13 +717,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyTypes_On_Textpage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; // Act - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(4)); @@ -769,11 +735,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyType_With_No_Group() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); Assert.That(contentType.PropertyGroups.Count, Is.EqualTo(2)); Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(4)); @@ -782,22 +748,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var urlAlias = new PropertyType(ShortStringHelper, "test", ValueStorageType.Nvarchar, "urlAlias") { Name = "Url Alias", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var addedPropertyType = contentType.AddPropertyType(urlAlias); + bool addedPropertyType = contentType.AddPropertyType(urlAlias); Assert.That(contentType.PropertyGroups.Count, Is.EqualTo(2)); Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(5)); repository.Save(contentType); - // Assert - var updated = repository.Get(_textpageContentType.Id); + IContentType updated = repository.Get(_textpageContentType.Id); Assert.That(addedPropertyType, Is.True); Assert.That(updated.PropertyGroups.Count, Is.EqualTo(2)); Assert.That(updated.PropertyTypes.Count(), Is.EqualTo(5)); @@ -810,19 +775,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_AllowedChildContentTypes_On_ContentType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; - var subpageContentType = ContentTypeBuilder.CreateSimpleContentType("umbSubpage", "Subpage"); - var simpleSubpageContentType = ContentTypeBuilder.CreateSimpleContentType("umbSimpleSubpage", "Simple Subpage"); + ContentType subpageContentType = ContentTypeBuilder.CreateSimpleContentType("umbSubpage", "Subpage"); + ContentType simpleSubpageContentType = ContentTypeBuilder.CreateSimpleContentType("umbSimpleSubpage", "Simple Subpage"); repository.Save(subpageContentType); repository.Save(simpleSubpageContentType); - // Act - var contentType = repository.Get(_simpleContentType.Id); + IContentType contentType = repository.Get(_simpleContentType.Id); contentType.AllowedContentTypes = new List { new ContentTypeSort(new Lazy(() => subpageContentType.Id), 0, subpageContentType.Alias), @@ -830,9 +794,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; repository.Save(contentType); - - //Assert - var updated = repository.Get(_simpleContentType.Id); + // Assert + IContentType updated = repository.Get(_simpleContentType.Id); Assert.That(updated.AllowedContentTypes.Any(), Is.True); Assert.That(updated.AllowedContentTypes.Any(x => x.Alias == subpageContentType.Alias), Is.True); @@ -844,21 +807,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Removal_Of_Used_PropertyType_From_ContentType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); DocumentRepository.Save(subpage); - // Act contentType.RemovePropertyType("keywords"); repository.Save(contentType); - // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(contentType.PropertyTypes.Any(x => x.Alias == "keywords"), Is.False); @@ -870,57 +831,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Addition_Of_PropertyType_After_ContentType_Is_Used() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + ContentTypeRepository repository = ContentTypeRepository; + IContentType contentType = repository.Get(_textpageContentType.Id); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); DocumentRepository.Save(subpage); - // Act - var propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); - propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + PropertyGroup propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); + propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); repository.Save(contentType); - // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(5)); Assert.That(contentType.PropertyTypes.Any(x => x.Alias == "metaAuthor"), Is.True); } - } [Test] public void Can_Verify_Usage_Of_New_PropertyType_On_Content() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); DocumentRepository.Save(subpage); - - var propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); - propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + PropertyGroup propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); + propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); repository.Save(contentType); - // Act - var content = DocumentRepository.Get(subpage.Id); + IContent content = DocumentRepository.Get(subpage.Id); content.SetValue("metaAuthor", "John Doe"); DocumentRepository.Save(content); - - //Assert - var updated = DocumentRepository.Get(subpage.Id); + // Assert + IContent updated = DocumentRepository.Get(subpage.Id); Assert.That(updated.GetValue("metaAuthor").ToString(), Is.EqualTo("John Doe")); Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(5)); Assert.That(contentType.PropertyTypes.Any(x => x.Alias == "metaAuthor"), Is.True); @@ -931,33 +886,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_That_A_Combination_Of_Adding_And_Deleting_PropertyTypes_Doesnt_Cause_Issues_For_Content_And_ContentType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; - var contentType = repository.Get(_textpageContentType.Id); + IContentType contentType = repository.Get(_textpageContentType.Id); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Text Page 1", contentType.Id); DocumentRepository.Save(subpage); - - //Remove PropertyType + // Remove PropertyType contentType.RemovePropertyType("keywords"); - //Add PropertyType - var propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); - propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + + // Add PropertyType + PropertyGroup propertyGroup = contentType.PropertyGroups.First(x => x.Name == "Meta"); + propertyGroup.PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "metaAuthor") { Name = "Meta Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }); repository.Save(contentType); - // Act - var content = DocumentRepository.Get(subpage.Id); + IContent content = DocumentRepository.Get(subpage.Id); content.SetValue("metaAuthor", "John Doe"); DocumentRepository.Save(content); - - //Assert - var updated = DocumentRepository.Get(subpage.Id); + // Assert + IContent updated = DocumentRepository.Get(subpage.Id); Assert.That(updated.GetValue("metaAuthor").ToString(), Is.EqualTo("John Doe")); Assert.That(updated.Properties.First(x => x.Alias == "description").GetValue(), Is.EqualTo("This is the meta description for a textpage")); @@ -971,28 +924,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Content_Type_Has_Content_Nodes() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = ContentTypeRepository; + ContentTypeRepository repository = ContentTypeRepository; - var contentTypeId = _textpageContentType.Id; - var contentType = repository.Get(contentTypeId); + int contentTypeId = _textpageContentType.Id; + IContentType contentType = repository.Get(contentTypeId); // Act - var result = repository.HasContentNodes(contentTypeId); + bool result = repository.HasContentNodes(contentTypeId); - var subpage = ContentBuilder.CreateTextpageContent(contentType, "Test Page 1", contentType.Id); + Content subpage = ContentBuilder.CreateTextpageContent(contentType, "Test Page 1", contentType.Id); DocumentRepository.Save(subpage); - var result2 = repository.HasContentNodes(contentTypeId); + bool result2 = repository.HasContentNodes(contentTypeId); // Assert Assert.That(result, Is.False); Assert.That(result2, Is.True); } } - - } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs index c94b708ff9..699e22746f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs @@ -1,9 +1,16 @@ -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.Events; using Umbraco.Core.Models; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Tests.Integration.Testing; @@ -17,12 +24,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class DataTypeDefinitionRepositoryTest : UmbracoIntegrationTest { private IDataTypeService DataTypeService => GetRequiredService(); + private ILocalizedTextService LocalizedTextService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IContentTypeRepository ContentTypeRepository => GetRequiredService(); + private IDataTypeContainerRepository DataTypeContainerRepository => GetRequiredService(); + private IDataTypeRepository DataTypeRepository => GetRequiredService(); + private IConfigurationEditorJsonSerializer ConfigurationEditorJsonSerializer => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); [Test] @@ -66,9 +80,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; ContentTypeRepository.Save(ct); - var usages = DataTypeRepository.FindUsages(dataType1.Id); + IReadOnlyDictionary> usages = DataTypeRepository.FindUsages(dataType1.Id); - var key = usages.First().Key; + Udi key = usages.First().Key; Assert.AreEqual(ct.Key, ((GuidUdi)key).Guid); Assert.AreEqual(2, usages[key].Count()); Assert.AreEqual("pt1", usages[key].ElementAt(0)); @@ -88,31 +102,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { using (ScopeProvider.CreateScope()) { - var container1 = new EntityContainer(Constants.ObjectTypes.DataType) { Name = "blah1" }; DataTypeContainerRepository.Save(container1); var container2 = new EntityContainer(Constants.ObjectTypes.DataType) { Name = "blah2", ParentId = container1.Id }; DataTypeContainerRepository.Save(container2); - var dataType = (IDataType) new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer, container2.Id) + var dataType = (IDataType)new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer, container2.Id) { Name = "dt1" }; DataTypeRepository.Save(dataType); - //create a + // create a var dataType2 = (IDataType)new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer, dataType.Id) { Name = "dt2" }; DataTypeRepository.Save(dataType2); - var result = DataTypeRepository.Move(dataType, container1).ToArray(); + MoveEventInfo[] result = DataTypeRepository.Move(dataType, container1).ToArray(); Assert.AreEqual(2, result.Length); - //re-get + // re-get dataType = DataTypeRepository.Get(dataType.Id); dataType2 = DataTypeRepository.Get(dataType2.Id); @@ -132,7 +145,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(container.Id, Is.GreaterThan(0)); - var found = DataTypeContainerRepository.Get(container.Id); + EntityContainer found = DataTypeContainerRepository.Get(container.Id); Assert.IsNotNull(found); } } @@ -148,7 +161,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act DataTypeContainerRepository.Delete(container); - var found = DataTypeContainerRepository.Get(container.Id); + EntityContainer found = DataTypeContainerRepository.Get(container.Id); Assert.IsNull(found); } } @@ -182,7 +195,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act DataTypeContainerRepository.Delete(container); - var found = DataTypeContainerRepository.Get(container.Id); + EntityContainer found = DataTypeContainerRepository.Get(container.Id); Assert.IsNull(found); dataType = DataTypeRepository.Get(dataType.Id); @@ -196,11 +209,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { using (ScopeProvider.CreateScope()) { - IDataType dataType = new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) {Name = "test"}; + IDataType dataType = new DataType(new RadioButtonsPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { Name = "test" }; DataTypeRepository.Save(dataType); - var id = dataType.Id; + int id = dataType.Id; Assert.That(id, Is.GreaterThan(0)); // Act @@ -212,14 +225,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - [Test] public void Can_Perform_Get_On_DataTypeDefinitionRepository() { using (ScopeProvider.CreateScope()) { // Act - var dataTypeDefinition = DataTypeRepository.Get(Constants.DataTypes.DropDownSingle); + IDataType dataTypeDefinition = DataTypeRepository.Get(Constants.DataTypes.DropDownSingle); // Assert Assert.That(dataTypeDefinition, Is.Not.Null); @@ -234,7 +246,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (ScopeProvider.CreateScope()) { // Act - var dataTypeDefinitions = DataTypeRepository.GetMany().ToArray(); + IDataType[] dataTypeDefinitions = DataTypeRepository.GetMany().ToArray(); // Assert Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -250,7 +262,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (ScopeProvider.CreateScope()) { // Act - var dataTypeDefinitions = DataTypeRepository.GetMany(-40, -41, -42).ToArray(); + IDataType[] dataTypeDefinitions = DataTypeRepository.GetMany(-40, -41, -42).ToArray(); // Assert Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -263,12 +275,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_GetByQuery_On_DataTypeDefinitionRepository() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - // Act - var query = scope.SqlContext.Query().Where(x => x.EditorAlias == Constants.PropertyEditors.Aliases.RadioButtonList); - var result = DataTypeRepository.Get(query).ToArray(); + IQuery query = scope.SqlContext.Query().Where(x => x.EditorAlias == Constants.PropertyEditors.Aliases.RadioButtonList); + IDataType[] result = DataTypeRepository.Get(query).ToArray(); // Assert Assert.That(result, Is.Not.Null); @@ -280,10 +291,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Count_On_DataTypeDefinitionRepository() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { // Act - var query = scope.SqlContext.Query().Where(x => x.Name.StartsWith("D")); + IQuery query = scope.SqlContext.Query().Where(x => x.Name.StartsWith("D")); int count = DataTypeRepository.Count(query); // Assert @@ -307,15 +318,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act DataTypeRepository.Save(dataTypeDefinition); - var exists = DataTypeRepository.Exists(dataTypeDefinition.Id); - var fetched = DataTypeRepository.Get(dataTypeDefinition.Id); + bool exists = DataTypeRepository.Exists(dataTypeDefinition.Id); + IDataType fetched = DataTypeRepository.Get(dataTypeDefinition.Id); // Assert Assert.That(dataTypeDefinition.HasIdentity, Is.True); Assert.That(exists, Is.True); // cannot compare 'configuration' as it's two different objects - TestHelper.AssertPropertyValuesAreEqual(dataTypeDefinition, fetched, "yyyy-MM-dd HH:mm:ss", ignoreProperties: new [] { "Configuration" }); + TestHelper.AssertPropertyValuesAreEqual(dataTypeDefinition, fetched, ignoreProperties: new[] { "Configuration" }); // still, can compare explicitely Assert.IsNotNull(dataTypeDefinition.Configuration); @@ -340,12 +351,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor DataTypeRepository.Save(dataTypeDefinition); // Act - var definition = DataTypeRepository.Get(dataTypeDefinition.Id); + IDataType definition = DataTypeRepository.Get(dataTypeDefinition.Id); definition.Name = "AgeDataType Updated"; - definition.Editor = new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer); //change + definition.Editor = new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer); // change DataTypeRepository.Save(definition); - var definitionUpdated = DataTypeRepository.Get(dataTypeDefinition.Id); + IDataType definitionUpdated = DataTypeRepository.Get(dataTypeDefinition.Id); // Assert Assert.That(definitionUpdated, Is.Not.Null); @@ -359,7 +370,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { using (ScopeProvider.CreateScope()) { - var dataTypeDefinition = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService,LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) + var dataTypeDefinition = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { DatabaseType = ValueStorageType.Integer, Name = "AgeDataType", @@ -369,11 +380,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act DataTypeRepository.Save(dataTypeDefinition); - var existsBefore = DataTypeRepository.Exists(dataTypeDefinition.Id); + bool existsBefore = DataTypeRepository.Exists(dataTypeDefinition.Id); DataTypeRepository.Delete(dataTypeDefinition); - var existsAfter = DataTypeRepository.Exists(dataTypeDefinition.Id); + bool existsAfter = DataTypeRepository.Exists(dataTypeDefinition.Id); // Assert Assert.That(existsBefore, Is.True); @@ -387,8 +398,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (ScopeProvider.CreateScope()) { // Act - var exists = DataTypeRepository.Exists(1046); //Content picker - var doesntExist = DataTypeRepository.Exists(-80); + bool exists = DataTypeRepository.Exists(1046); // Content picker + bool doesntExist = DataTypeRepository.Exists(-80); // Assert Assert.That(exists, Is.True); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DictionaryRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DictionaryRepositoryTest.cs index 105d7520fd..edbeac263e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DictionaryRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DictionaryRepositoryTest.cs @@ -1,10 +1,15 @@ -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.Configuration.Models; using Umbraco.Core.Models; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -16,25 +21,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class DictionaryRepositoryTest : UmbracoIntegrationTest { [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); - private IDictionaryRepository CreateRepository() - { - return GetRequiredService(); - } + private IDictionaryRepository CreateRepository() => GetRequiredService(); [Test] public void Can_Perform_Get_By_Key_On_DictionaryRepository() { // Arrange - var localizationService = GetRequiredService(); - var provider = ScopeProvider; + ILocalizationService localizationService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); var dictionaryItem = (IDictionaryItem)new DictionaryItem("Testing1235") { Translations = new List @@ -45,7 +44,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(dictionaryItem); - //re-get + // re-get dictionaryItem = repository.Get("Testing1235"); // Assert @@ -61,11 +60,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_By_UniqueId_On_DictionaryRepository() { // Arrange - var localizationService = GetRequiredService(); - var provider = ScopeProvider; + ILocalizationService localizationService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); var dictionaryItem = (IDictionaryItem)new DictionaryItem("Testing1235") { Translations = new List @@ -76,7 +75,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(dictionaryItem); - //re-get + // re-get dictionaryItem = repository.Get(dictionaryItem.Key); // Assert @@ -92,11 +91,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_DictionaryRepository() { // Arrange - var localizationService = GetRequiredService(); - var provider = ScopeProvider; + ILocalizationService localizationService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); var dictionaryItem = (IDictionaryItem)new DictionaryItem("Testing1235") { Translations = new List @@ -107,10 +106,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(dictionaryItem); - //re-get + // re-get dictionaryItem = repository.Get(dictionaryItem.Id); - // Assert Assert.That(dictionaryItem, Is.Not.Null); Assert.That(dictionaryItem.ItemKey, Is.EqualTo("Testing1235")); @@ -124,18 +122,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_DictionaryRepository_When_No_Language_Assigned() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); - var dictionaryItem = (IDictionaryItem) new DictionaryItem("Testing1235"); + IDictionaryRepository repository = CreateRepository(); + var dictionaryItem = (IDictionaryItem)new DictionaryItem("Testing1235"); repository.Save(dictionaryItem); - //re-get + // re-get dictionaryItem = repository.Get(dictionaryItem.Id); - // Assert Assert.That(dictionaryItem, Is.Not.Null); Assert.That(dictionaryItem.ItemKey, Is.EqualTo("Testing1235")); @@ -147,14 +144,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var dictionaryItem = repository.Get(1); - var dictionaryItems = repository.GetMany(); + IDictionaryItem dictionaryItem = repository.Get(1); + IEnumerable dictionaryItems = repository.GetMany(); // Assert Assert.That(dictionaryItems, Is.Not.Null); @@ -168,13 +165,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_With_Params_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var dictionaryItems = repository.GetMany(1, 2); + IEnumerable dictionaryItems = repository.GetMany(1, 2); // Assert Assert.That(dictionaryItems, Is.Not.Null); @@ -188,14 +185,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var query = provider.SqlContext.Query().Where(x => x.ItemKey == "Article"); - var result = repository.Get(query); + IQuery query = provider.SqlContext.Query().Where(x => x.ItemKey == "Article"); + IEnumerable result = repository.Get(query); // Assert Assert.That(result, Is.Not.Null); @@ -208,14 +205,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var query = provider.SqlContext.Query().Where(x => x.ItemKey.StartsWith("Read")); - var result = repository.Count(query); + IQuery query = provider.SqlContext.Query().Where(x => x.ItemKey.StartsWith("Read")); + int result = repository.Count(query); // Assert Assert.That(result, Is.EqualTo(1)); @@ -226,13 +223,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var languageRepository = GetRequiredService(); - var repository = CreateRepository(); + ILanguageRepository languageRepository = GetRequiredService(); + IDictionaryRepository repository = CreateRepository(); - var language = languageRepository.Get(1); + ILanguage language = languageRepository.Get(1); var read = new DictionaryItem("Read"); var translations = new List @@ -244,7 +241,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act repository.Save(read); - var exists = repository.Exists(read.Id); + bool exists = repository.Exists(read.Id); // Assert Assert.That(read.HasIdentity, Is.True); @@ -256,20 +253,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var item = repository.Get(1); + IDictionaryItem item = repository.Get(1); var translations = item.Translations.ToList(); translations[0].Value = "Read even more"; item.Translations = translations; repository.Save(item); - var dictionaryItem = repository.Get(1); + IDictionaryItem dictionaryItem = repository.Get(1); // Assert Assert.That(dictionaryItem, Is.Not.Null); @@ -282,25 +279,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_WithNewTranslation_On_DictionaryRepository() { // Arrange - var localizationService = GetRequiredService(); - var provider = ScopeProvider; + ILocalizationService localizationService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); var globalSettings = new GlobalSettings(); var languageNo = new Language(globalSettings, "nb-NO") { CultureName = "nb-NO" }; localizationService.Save(languageNo); // Act - var item = repository.Get(1); + IDictionaryItem item = repository.Get(1); var translations = item.Translations.ToList(); translations.Add(new DictionaryTranslation(languageNo, "Les mer")); item.Translations = translations; repository.Save(item); - var dictionaryItem = (DictionaryItem) repository.Get(1); + var dictionaryItem = (DictionaryItem)repository.Get(1); // Assert Assert.That(dictionaryItem, Is.Not.Null); @@ -313,16 +310,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var item = repository.Get(1); + IDictionaryItem item = repository.Get(1); repository.Delete(item); - var exists = repository.Exists(1); + bool exists = repository.Exists(1); // Assert Assert.That(exists, Is.False); @@ -333,13 +330,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_DictionaryRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); // Act - var exists = repository.Exists(1); + bool exists = repository.Exists(1); // Assert Assert.That(exists, Is.True); @@ -351,27 +348,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { Dictionary keyMap; - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(); + IDictionaryRepository repository = CreateRepository(); keyMap = repository.GetDictionaryItemKeyMap(); } Assert.IsNotNull(keyMap); Assert.IsNotEmpty(keyMap); - foreach (var kvp in keyMap) + foreach (KeyValuePair kvp in keyMap) + { Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value); + } } public void CreateTestData() { - var localizationService = GetRequiredService(); - var language = localizationService.GetLanguageByIsoCode("en-US"); + ILocalizationService localizationService = GetRequiredService(); + ILanguage language = localizationService.GetLanguageByIsoCode("en-US"); var globalSettings = new GlobalSettings(); var languageDK = new Language(globalSettings, "da-DK") { CultureName = "da-DK" }; - localizationService.Save(languageDK);//Id 2 + localizationService.Save(languageDK); // Id 2 var readMore = new DictionaryItem("Read More"); var translations = new List @@ -380,7 +379,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor new DictionaryTranslation(languageDK, "Læs mere") }; readMore.Translations = translations; - localizationService.Save(readMore);//Id 1 + localizationService.Save(readMore); // Id 1 var article = new DictionaryItem("Article"); var translations2 = new List @@ -389,7 +388,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor new DictionaryTranslation(languageDK, "Artikel") }; article.Translations = translations2; - localizationService.Save(article);//Id 2 + localizationService.Save(article); // Id 2 } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs index e0ef0434c9..7bfc9ea573 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs @@ -1,7 +1,11 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; @@ -9,6 +13,7 @@ using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.PropertyEditors; @@ -32,10 +37,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private Content _trashed; private IContentService ContentService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IFileSystems FileSystems => GetRequiredService(); + private IConfigurationEditorJsonSerializer ConfigurationEditorJsonSerializer => GetRequiredService(); [SetUp] @@ -50,36 +60,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } [TearDown] - public void Teardown() - { - ContentRepositoryBase.ThrowOnWarning = false; - } + public void Teardown() => ContentRepositoryBase.ThrowOnWarning = false; public void CreateTestData() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Create and Save ContentType "umbTextpage" -> (_contentType.Id) - _contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId:template.Id); + // Create and Save ContentType "umbTextpage" -> (_contentType.Id) + _contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); _contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"); ContentTypeService.Save(_contentType); - //Create and Save Content "Homepage" based on "umbTextpage" -> (_textpage.Id) + // Create and Save Content "Homepage" based on "umbTextpage" -> (_textpage.Id) _textpage = ContentBuilder.CreateSimpleContent(_contentType); _textpage.Key = new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0"); ContentService.Save(_textpage, 0); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> (_subpage.Id) + // Create and Save Content "Text Page 1" based on "umbTextpage" -> (_subpage.Id) _subpage = ContentBuilder.CreateSimpleContent(_contentType, "Text Page 1", _textpage.Id); _subpage.Key = new Guid("FF11402B-7E53-4654-81A7-462AC2108059"); ContentService.Save(_subpage, 0); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> (_subpage2.Id) + // Create and Save Content "Text Page 1" based on "umbTextpage" -> (_subpage2.Id) _subpage2 = ContentBuilder.CreateSimpleContent(_contentType, "Text Page 2", _textpage.Id); ContentService.Save(_subpage2, 0); - //Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (_trashed.Id) + // Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (_trashed.Id) _trashed = ContentBuilder.CreateSimpleContent(_contentType, "Text Page Deleted", -20); _trashed.Trashed = true; ContentService.Save(_trashed, 0); @@ -87,26 +94,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, out DataTypeRepository dtdRepository, AppCaches appCaches = null) { - appCaches = appCaches ?? AppCaches; + appCaches ??= AppCaches; - TemplateRepository tr; - var ctRepository = CreateRepository(scopeAccessor, out contentTypeRepository, out tr); + DocumentRepository ctRepository = CreateRepository(scopeAccessor, out contentTypeRepository, out TemplateRepository tr); var editors = new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty())); dtdRepository = new DataTypeRepository(scopeAccessor, appCaches, new Lazy(() => editors), LoggerFactory.CreateLogger(), LoggerFactory, ConfigurationEditorJsonSerializer); return ctRepository; } - private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, AppCaches appCaches = null) - { - TemplateRepository tr; - return CreateRepository(scopeAccessor, out contentTypeRepository, out tr, appCaches); - } + private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, AppCaches appCaches = null) => + CreateRepository(scopeAccessor, out contentTypeRepository, out TemplateRepository tr, appCaches); private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, out TemplateRepository templateRepository, AppCaches appCaches = null) { - var globalSettings = Microsoft.Extensions.Options.Options.Create(new GlobalSettings()); + IOptions globalSettings = Options.Create(new GlobalSettings()); - appCaches = appCaches ?? AppCaches; + appCaches ??= AppCaches; templateRepository = new TemplateRepository(scopeAccessor, appCaches, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); var tagRepository = new TagRepository(scopeAccessor, appCaches, LoggerFactory.CreateLogger()); @@ -118,8 +121,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var relationRepository = new RelationRepository(scopeAccessor, LoggerFactory.CreateLogger(), relationTypeRepository, entityRepository); var propertyEditors = new Lazy(() => new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty()))); var dataValueReferences = new DataValueReferenceFactoryCollection(Enumerable.Empty()); - var repository = new DocumentRepository(scopeAccessor, appCaches, LoggerFactory.CreateLogger(), LoggerFactory, contentTypeRepository, templateRepository, tagRepository, languageRepository, relationRepository, - relationTypeRepository, propertyEditors, dataValueReferences, DataTypeService, ConfigurationEditorJsonSerializer); + var repository = new DocumentRepository( + scopeAccessor, + appCaches, + LoggerFactory.CreateLogger(), + LoggerFactory, + contentTypeRepository, + templateRepository, + tagRepository, + languageRepository, + relationRepository, + relationTypeRepository, + propertyEditors, + dataValueReferences, + DataTypeService, + ConfigurationEditorJsonSerializer); return repository; } @@ -131,41 +147,43 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor new DictionaryAppCache(), new IsolatedCaches(t => new ObjectCacheAppCache())); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, appCaches: realCache); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository, appCaches: realCache); - var udb = scope.Database; + IUmbracoDatabase udb = scope.Database; udb.EnableSqlCount = false; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); repository.Save(content); udb.EnableSqlCount = true; - //go get it, this should already be cached since the default repository key is the INT - repository.Get(content.Id); - Assert.AreEqual(0, udb.SqlCount); - //retrieve again, this should use cache + // go get it, this should already be cached since the default repository key is the INT repository.Get(content.Id); Assert.AreEqual(0, udb.SqlCount); - //reset counter + // retrieve again, this should use cache + repository.Get(content.Id); + Assert.AreEqual(0, udb.SqlCount); + + // reset counter udb.EnableSqlCount = false; udb.EnableSqlCount = true; - //now get by GUID, this won't be cached yet because the default repo key is not a GUID + // now get by GUID, this won't be cached yet because the default repo key is not a GUID repository.Get(content.Key); - var sqlCount = udb.SqlCount; + int sqlCount = udb.SqlCount; Assert.Greater(sqlCount, 0); - //retrieve again, this should use cache now + + // retrieve again, this should use cache now repository.Get(content.Key); Assert.AreEqual(sqlCount, udb.SqlCount); } @@ -174,16 +192,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CreateVersions() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out DataTypeRepository _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository, out DataTypeRepository _); var versions = new List(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var hasPropertiesContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); - + ContentType hasPropertiesContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(hasPropertiesContentType); @@ -203,10 +220,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // NEW VERSION // new edit version has been created - Assert.AreNotEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreNotEqual(versions[^2], versions[^1]); Assert.IsTrue(content1.Published); Assert.AreEqual(PublishedState.Published, ((Content)content1).PublishedState); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -220,9 +237,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // the same version // no new version has been created - Assert.AreEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreEqual(versions[^2], versions[^1]); Assert.IsTrue(content1.Published); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -234,10 +251,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // the same version // no new version has been created - Assert.AreEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreEqual(versions[^2], versions[^1]); Assert.IsFalse(content1.Published); Assert.AreEqual(PublishedState.Unpublished, ((Content)content1).PublishedState); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(false, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -251,8 +268,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // the same version // no new version has been created - Assert.AreEqual(versions[versions.Count - 2], versions[versions.Count - 1]); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^2], versions[^1]); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(false, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -265,10 +282,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // NEW VERSION // new version has been created - Assert.AreNotEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreNotEqual(versions[^2], versions[^1]); Assert.IsTrue(content1.Published); Assert.AreEqual(PublishedState.Published, ((Content)content1).PublishedState); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -278,15 +295,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor content1.Name = "name-3"; content1.SetValue("title", "title-3"); - //Thread.Sleep(2000); // force date change + //// Thread.Sleep(2000); // force date change repository.Save(content1); versions.Add(content1.VersionId); // the same version // no new version has been created - Assert.AreEqual(versions[versions.Count - 2], versions[versions.Count - 1]); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^2], versions[^1]); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); @@ -301,30 +318,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor versions.Add(content1.VersionId); // NEW VERSION // a new version has been created - Assert.AreNotEqual(versions[versions.Count - 2], versions[versions.Count - 1]); + Assert.AreNotEqual(versions[^2], versions[^1]); Assert.IsTrue(content1.Published); Assert.AreEqual(PublishedState.Published, ((Content)content1).PublishedState); - Assert.AreEqual(versions[versions.Count - 1], repository.Get(content1.Id).VersionId); + Assert.AreEqual(versions[^1], repository.Get(content1.Id).VersionId); // misc checks Assert.AreEqual(true, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); // all versions - var allVersions = repository.GetAllVersions(content1.Id).ToArray(); + IContent[] allVersions = repository.GetAllVersions(content1.Id).ToArray(); Console.WriteLine(); - foreach (var v in versions) + foreach (int v in versions) + { Console.WriteLine(v); + } + Console.WriteLine(); - foreach (var v in allVersions) + foreach (IContent v in allVersions) { var c = (Content)v; Console.WriteLine($"{c.Id} {c.VersionId} {(c.Published ? "+" : "-")}pub pk={c.VersionId} ppk={c.PublishedVersionId} name=\"{c.Name}\" pname=\"{c.PublishName}\""); } // get older version - var content = repository.GetVersion(versions[versions.Count - 4]); + IContent content = repository.GetVersion(versions[^4]); Assert.AreNotEqual(0, content.VersionId); - Assert.AreEqual(versions[versions.Count - 4], content.VersionId); + Assert.AreEqual(versions[^4], content.VersionId); Assert.AreEqual("name-4", content1.Name); Assert.AreEqual("title-4", content1.GetValue("title")); Assert.AreEqual("name-2", content.Name); @@ -332,10 +352,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // get all versions - most recent first allVersions = repository.GetAllVersions(content1.Id).ToArray(); - var expVersions = versions.Distinct().Reverse().ToArray(); + int[] expVersions = versions.Distinct().Reverse().ToArray(); Assert.AreEqual(expVersions.Length, allVersions.Length); - for (var i = 0; i < expVersions.Length; i++) + for (int i = 0; i < expVersions.Length; i++) + { Assert.AreEqual(expVersions[i], allVersions[i].VersionId); + } } } @@ -350,36 +372,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void PropertyDataAssignedCorrectly() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out DataTypeRepository _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository, out DataTypeRepository _); - var emptyContentType = ContentTypeBuilder.CreateBasicContentType(); - var hasPropertiesContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + ContentType emptyContentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType hasPropertiesContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(emptyContentType); contentTypeRepository.Save(hasPropertiesContentType); - - var content1 = ContentBuilder.CreateSimpleContent(hasPropertiesContentType); - var content2 = ContentBuilder.CreateBasicContent(emptyContentType); - var content3 = ContentBuilder.CreateSimpleContent(hasPropertiesContentType); - + Content content1 = ContentBuilder.CreateSimpleContent(hasPropertiesContentType); + Content content2 = ContentBuilder.CreateBasicContent(emptyContentType); + Content content3 = ContentBuilder.CreateSimpleContent(hasPropertiesContentType); repository.Save(content1); repository.Save(content2); repository.Save(content3); - // this will cause the GetPropertyCollection to execute and we need to ensure that // all of the properties and property types are all correct - var result = repository.GetMany(content1.Id, content2.Id, content3.Id).ToArray(); - var n1 = result[0]; - var n2 = result[1]; - var n3 = result[2]; + IContent[] result = repository.GetMany(content1.Id, content2.Id, content3.Id).ToArray(); + IContent n1 = result[0]; + IContent n2 = result[1]; + IContent n3 = result[2]; Assert.AreEqual(content1.Id, n1.Id); Assert.AreEqual(content2.Id, n2.Id); @@ -393,72 +412,72 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - // /// - // /// This test ensures that when property values using special database fields are saved, the actual data in the - // /// object being stored is also transformed in the same way as the data being stored in the database is. - // /// Before you would see that ex: a decimal value being saved as 100 or "100", would be that exact value in the - // /// object, but the value saved to the database was actually 100.000000. - // /// When querying the database for the value again - the value would then differ from what is in the object. - // /// This caused inconsistencies between saving+publishing and simply saving and then publishing, due to the former - // /// sending the non-transformed data directly on to publishing. - // /// - // [Test] - // public void PropertyValuesWithSpecialTypes() - // { - // var provider = ScopeProvider; - // using (var scope = provider.CreateScope()) - // { - // var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out DataTypeRepository dataTypeDefinitionRepository); - // - // var editor = new DecimalPropertyEditor(LoggerFactory, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper); - // var dtd = new DataType(editor) { Name = "test", DatabaseType = ValueStorageType.Decimal }; - // dataTypeDefinitionRepository.Save(dtd); - // - // const string decimalPropertyAlias = "decimalProperty"; - // const string intPropertyAlias = "intProperty"; - // const string dateTimePropertyAlias = "datetimeProperty"; - // var dateValue = new DateTime(2016, 1, 6); - // - // var propertyTypeCollection = new PropertyTypeCollection(true, - // new List - // { - // MockedPropertyTypes.CreateDecimalProperty(decimalPropertyAlias, "Decimal property", dtd.Id), - // MockedPropertyTypes.CreateIntegerProperty(intPropertyAlias, "Integer property"), - // MockedPropertyTypes.CreateDateTimeProperty(dateTimePropertyAlias, "DateTime property") - // }); - // var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", propertyTypeCollection); - // contentTypeRepository.Save(contentType); - // - // // int and decimal values are passed in as strings as they would be from the backoffice UI - // var textpage = ContentBuilder.CreateSimpleContentWithSpecialDatabaseTypes(contentType, "test@umbraco.org", -1, "100", "150", dateValue); - // - // repository.Save(textpage); - // scope.Complete(); - // - // Assert.That(contentType.HasIdentity, Is.True); - // Assert.That(textpage.HasIdentity, Is.True); - // - // var persistedTextpage = repository.Get(textpage.Id); - // Assert.That(persistedTextpage.Name, Is.EqualTo(textpage.Name)); - // Assert.AreEqual(100m, persistedTextpage.GetValue(decimalPropertyAlias)); - // Assert.AreEqual(persistedTextpage.GetValue(decimalPropertyAlias), textpage.GetValue(decimalPropertyAlias)); - // Assert.AreEqual(150, persistedTextpage.GetValue(intPropertyAlias)); - // Assert.AreEqual(persistedTextpage.GetValue(intPropertyAlias), textpage.GetValue(intPropertyAlias)); - // Assert.AreEqual(dateValue, persistedTextpage.GetValue(dateTimePropertyAlias)); - // Assert.AreEqual(persistedTextpage.GetValue(dateTimePropertyAlias), textpage.GetValue(dateTimePropertyAlias)); - // } - // } + //// /// + //// /// This test ensures that when property values using special database fields are saved, the actual data in the + //// /// object being stored is also transformed in the same way as the data being stored in the database is. + //// /// Before you would see that ex: a decimal value being saved as 100 or "100", would be that exact value in the + //// /// object, but the value saved to the database was actually 100.000000. + //// /// When querying the database for the value again - the value would then differ from what is in the object. + //// /// This caused inconsistencies between saving+publishing and simply saving and then publishing, due to the former + //// /// sending the non-transformed data directly on to publishing. + //// /// + //// [Test] + //// public void PropertyValuesWithSpecialTypes() + //// { + //// var provider = ScopeProvider; + //// using (var scope = provider.CreateScope()) + //// { + //// var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out DataTypeRepository dataTypeDefinitionRepository); + //// + //// var editor = new DecimalPropertyEditor(LoggerFactory, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper); + //// var dtd = new DataType(editor) { Name = "test", DatabaseType = ValueStorageType.Decimal }; + //// dataTypeDefinitionRepository.Save(dtd); + //// + //// const string decimalPropertyAlias = "decimalProperty"; + //// const string intPropertyAlias = "intProperty"; + //// const string dateTimePropertyAlias = "datetimeProperty"; + //// var dateValue = new DateTime(2016, 1, 6); + //// + //// var propertyTypeCollection = new PropertyTypeCollection(true, + //// new List + //// { + //// MockedPropertyTypes.CreateDecimalProperty(decimalPropertyAlias, "Decimal property", dtd.Id), + //// MockedPropertyTypes.CreateIntegerProperty(intPropertyAlias, "Integer property"), + //// MockedPropertyTypes.CreateDateTimeProperty(dateTimePropertyAlias, "DateTime property") + //// }); + //// var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", propertyTypeCollection); + //// contentTypeRepository.Save(contentType); + //// + //// // int and decimal values are passed in as strings as they would be from the backoffice UI + //// var textpage = ContentBuilder.CreateSimpleContentWithSpecialDatabaseTypes(contentType, "test@umbraco.org", -1, "100", "150", dateValue); + //// + //// repository.Save(textpage); + //// scope.Complete(); + //// + //// Assert.That(contentType.HasIdentity, Is.True); + //// Assert.That(textpage.HasIdentity, Is.True); + //// + //// var persistedTextpage = repository.Get(textpage.Id); + //// Assert.That(persistedTextpage.Name, Is.EqualTo(textpage.Name)); + //// Assert.AreEqual(100m, persistedTextpage.GetValue(decimalPropertyAlias)); + //// Assert.AreEqual(persistedTextpage.GetValue(decimalPropertyAlias), textpage.GetValue(decimalPropertyAlias)); + //// Assert.AreEqual(150, persistedTextpage.GetValue(intPropertyAlias)); + //// Assert.AreEqual(persistedTextpage.GetValue(intPropertyAlias), textpage.GetValue(intPropertyAlias)); + //// Assert.AreEqual(dateValue, persistedTextpage.GetValue(dateTimePropertyAlias)); + //// Assert.AreEqual(persistedTextpage.GetValue(dateTimePropertyAlias), textpage.GetValue(dateTimePropertyAlias)); + //// } + //// } [Test] public void SaveContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage", defaultTemplateId: template.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); IContent textpage = ContentBuilder.CreateSimpleContent(contentType); @@ -474,25 +493,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void SaveContentWithDefaultTemplate() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, out TemplateRepository templateRepository); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository, out TemplateRepository templateRepository); var template = new Template(ShortStringHelper, "hello", "hello"); templateRepository.Save(template); - - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage"); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage"); contentType.AllowedTemplates = Enumerable.Empty(); // because CreateSimpleContentType assigns one already contentType.SetDefaultTemplate(template); contentTypeRepository.Save(contentType); - var textpage = ContentBuilder.CreateSimpleContent(contentType); + Content textpage = ContentBuilder.CreateSimpleContent(contentType); repository.Save(textpage); - - var fetched = repository.Get(textpage.Id); + IContent fetched = repository.Get(textpage.Id); Assert.True(textpage.TemplateId.HasValue); Assert.NotZero(textpage.TemplateId.Value); @@ -500,40 +517,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); - TestHelper.AssertPropertyValuesAreEqual(textpage, fetched, "yyyy-MM-dd HH:mm:ss"); + TestHelper.AssertPropertyValuesAreEqual(textpage, fetched); } } - //Covers issue U4-2791 and U4-2607 + // Covers issue U4-2791 and U4-2607 [Test] public void SaveContentWithAtSignInName() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); - - var textpage = ContentBuilder.CreateSimpleContent(contentType, "test@umbraco.org"); - var anotherTextpage = ContentBuilder.CreateSimpleContent(contentType, "@lightgiants"); + Content textpage = ContentBuilder.CreateSimpleContent(contentType, "test@umbraco.org"); + Content anotherTextpage = ContentBuilder.CreateSimpleContent(contentType, "@lightgiants"); repository.Save(textpage); repository.Save(anotherTextpage); - - Assert.That(contentType.HasIdentity, Is.True); Assert.That(textpage.HasIdentity, Is.True); - var content = repository.Get(textpage.Id); + IContent content = repository.Get(textpage.Id); Assert.That(content.Name, Is.EqualTo(textpage.Name)); - var content2 = repository.Get(anotherTextpage.Id); + IContent content2 = repository.Get(anotherTextpage.Id); Assert.That(content2.Name, Is.EqualTo(anotherTextpage.Name)); scope.Complete(); @@ -543,43 +557,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void SaveContentMultiple() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); - var textpage = ContentBuilder.CreateSimpleContent(contentType); + Content textpage = ContentBuilder.CreateSimpleContent(contentType); repository.Save(textpage); - - var subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 1", textpage.Id); + Content subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 1", textpage.Id); repository.Save(subpage); - Assert.That(contentType.HasIdentity, Is.True); Assert.That(textpage.HasIdentity, Is.True); Assert.That(subpage.HasIdentity, Is.True); Assert.That(textpage.Id, Is.EqualTo(subpage.ParentId)); } - } - [Test] public void GetContentIsNotDirty() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var content = repository.Get(_subpage2.Id); - var dirty = ((Content)content).IsDirty(); + IContent content = repository.Get(_subpage2.Id); + bool dirty = ((Content)content).IsDirty(); Assert.That(dirty, Is.False); } @@ -588,16 +598,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void UpdateContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var content = repository.Get(_subpage.Id); + IContent content = repository.Get(_subpage.Id); content.Name = "About 2"; repository.Save(content); - var updatedContent = repository.Get(_subpage.Id); + IContent updatedContent = repository.Get(_subpage.Id); Assert.AreEqual(content.Id, updatedContent.Id); Assert.AreEqual(content.Name, updatedContent.Name); @@ -617,42 +627,42 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void UpdateContentWithNullTemplate() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var content = repository.Get(_subpage.Id); + IContent content = repository.Get(_subpage.Id); content.TemplateId = null; repository.Save(content); - var updatedContent = repository.Get(_subpage.Id); + IContent updatedContent = repository.Get(_subpage.Id); Assert.False(updatedContent.TemplateId.HasValue); } - } [Test] public void DeleteContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository); - var contentType = contentTypeRepository.Get(_contentType.Id); - var content = new Content("Textpage 2 Child Node", _trashed.Id, contentType); - content.CreatorId = 0; - content.WriterId = 0; + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out ContentTypeRepository contentTypeRepository); + IContentType contentType = contentTypeRepository.Get(_contentType.Id); + var content = new Content("Textpage 2 Child Node", _trashed.Id, contentType) + { + CreatorId = 0, + WriterId = 0 + }; repository.Save(content); - var id = content.Id; + int id = content.Id; repository.Delete(content); - - var content1 = repository.Get(id); + IContent content1 = repository.Get(id); Assert.IsNull(content1); } } @@ -660,11 +670,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); - var content = repository.Get(_subpage2.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); + IContent content = repository.Get(_subpage2.Id); Assert.AreEqual(_subpage2.Id, content.Id); Assert.That(content.CreateDate, Is.GreaterThan(DateTime.MinValue)); @@ -681,13 +691,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void QueryContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.Get(query); Assert.GreaterOrEqual(2, result.Count()); } @@ -698,36 +708,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { IContent[] result; - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); result = repository.GetMany().ToArray(); // save them all - foreach (var content in result) + foreach (IContent content in result) { content.SetValue("title", content.GetValue("title") + "x"); repository.Save(content); } - // publish them all - foreach (var content in result) + foreach (IContent content in result) { content.PublishCulture(CultureImpact.Invariant); repository.Save(content); } - scope.Complete(); } // get them all again - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); - var result2 = repository.GetMany().ToArray(); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); + IContent[] result2 = repository.GetMany().ToArray(); Assert.AreEqual(result.Length, result2.Length); } @@ -736,10 +744,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void AliasRegexTest() { - var regex = new SqlServerSyntaxProvider().AliasRegex; + System.Text.RegularExpressions.Regex regex = new SqlServerSyntaxProvider().AliasRegex; Assert.AreEqual(@"(\[\w+]\.\[\w+])\s+AS\s+(\[\w+])", regex.ToString()); const string sql = "SELECT [table].[column1] AS [alias1], [table].[column2] AS [alias2] FROM [table];"; - var matches = regex.Matches(sql); + System.Text.RegularExpressions.MatchCollection matches = regex.Matches(sql); Assert.AreEqual(2, matches.Count); Assert.AreEqual("[table].[column1]", matches[0].Groups[1].Value); Assert.AreEqual("[alias1]", matches[0].Groups[2].Value); @@ -750,25 +758,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_With_Variant_Names() { - // one invariant content type named "umbInvariantTextPage" - // - var template = TemplateBuilder.CreateTextPageTemplate(); + // One invariant content type named "umbInvariantTextPage" + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var invariantCt = ContentTypeBuilder.CreateSimpleContentType("umbInvariantTextpage", "Invariant Textpage", defaultTemplateId: template.Id); + ContentType invariantCt = ContentTypeBuilder.CreateSimpleContentType("umbInvariantTextpage", "Invariant Textpage", defaultTemplateId: template.Id); invariantCt.Variations = ContentVariation.Nothing; - foreach (var p in invariantCt.PropertyTypes) p.Variations = ContentVariation.Nothing; + foreach (IPropertyType p in invariantCt.PropertyTypes) + { + p.Variations = ContentVariation.Nothing; + } + ContentTypeService.Save(invariantCt); - // one variant (by culture) content type named "umbVariantTextPage" + // One variant (by culture) content type named "umbVariantTextPage" // with properties, every 2nd one being variant (by culture), the other being invariant - // - - var variantCt = ContentTypeBuilder.CreateSimpleContentType("umbVariantTextpage", "Variant Textpage", defaultTemplateId: template.Id); + ContentType variantCt = ContentTypeBuilder.CreateSimpleContentType("umbVariantTextpage", "Variant Textpage", defaultTemplateId: template.Id); variantCt.Variations = ContentVariation.Culture; var propTypes = variantCt.PropertyTypes.ToList(); - for (var i = 0; i < propTypes.Count; i++) + for (int i = 0; i < propTypes.Count; i++) { - var p = propTypes[i]; + IPropertyType p = propTypes[i]; p.Variations = i % 2 == 0 ? ContentVariation.Culture : ContentVariation.Nothing; } @@ -777,30 +786,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor invariantCt.AllowedContentTypes = new[] { new ContentTypeSort(invariantCt.Id, 0), new ContentTypeSort(variantCt.Id, 1) }; ContentTypeService.Save(invariantCt); - //create content - - var root = ContentBuilder.CreateSimpleContent(invariantCt); + // Create content + Content root = ContentBuilder.CreateSimpleContent(invariantCt); ContentService.Save(root); var children = new List(); - for (var i = 0; i < 25; i++) + for (int i = 0; i < 25; i++) { - var isInvariant = i % 2 == 0; - var name = (isInvariant ? "INV" : "VAR") + "_" + Guid.NewGuid(); - var culture = isInvariant ? null : "en-US"; + bool isInvariant = i % 2 == 0; + string name = (isInvariant ? "INV" : "VAR") + "_" + Guid.NewGuid(); + string culture = isInvariant ? null : "en-US"; - var child = ContentBuilder.CreateSimpleContent( + Content child = ContentBuilder.CreateSimpleContent( isInvariant ? invariantCt : variantCt, - name, root, + name, + root, culture, setPropertyValues: isInvariant); if (!isInvariant) { - //manually set the property values since we have mixed variant/invariant property types + // manually set the property values since we have mixed variant/invariant property types child.SetValue("title", name + " Subpage", culture: culture); - child.SetValue("bodyText", "This is a subpage", culture: null); //this one is invariant + child.SetValue("bodyText", "This is a subpage", culture: null); // this one is invariant child.SetValue("author", "John Doe", culture: culture); } @@ -808,17 +817,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor children.Add(child); } - var child1 = children[1]; + IContent child1 = children[1]; Assert.IsTrue(child1.ContentType.VariesByCulture()); Assert.IsTrue(child1.Name.StartsWith("VAR")); Assert.IsTrue(child1.GetCultureName("en-US").StartsWith("VAR")); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var child = repository.Get(children[1].Id); // 1 is variant + IContent child = repository.Get(children[1].Id); // 1 is variant Assert.IsTrue(child.ContentType.VariesByCulture()); Assert.IsTrue(child.Name.StartsWith("VAR")); Assert.IsTrue(child.GetCultureName("en-US").StartsWith("VAR")); @@ -828,23 +837,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var query = scope.SqlContext.Query().Where(x => x.ParentId == root.Id); - var result = repository.GetPage(query, 0, 20, out var totalRecords, null, Ordering.By("UpdateDate")); + IQuery query = scope.SqlContext.Query().Where(x => x.ParentId == root.Id); + IEnumerable result = repository.GetPage(query, 0, 20, out long totalRecords, null, Ordering.By("UpdateDate")); Assert.AreEqual(25, totalRecords); - foreach (var r in result) + foreach (IContent r in result) { - var isInvariant = r.ContentType.Alias == "umbInvariantTextpage"; - var name = isInvariant ? r.Name : r.CultureInfos["en-US"].Name; - var namePrefix = isInvariant ? "INV" : "VAR"; + bool isInvariant = r.ContentType.Alias == "umbInvariantTextpage"; + string name = isInvariant ? r.Name : r.CultureInfos["en-US"].Name; + string namePrefix = isInvariant ? "INV" : "VAR"; - //ensure the correct name (invariant vs variant) is in the result + // ensure the correct name (invariant vs variant) is in the result Assert.IsTrue(name.StartsWith(namePrefix)); - foreach (var p in r.Properties) + foreach (IProperty p in r.Properties) { - //ensure there is a value for the correct variant/invariant property - var value = p.GetValue(p.PropertyType.Variations.VariesByNothing() ? null : "en-US"); + // ensure there is a value for the correct variant/invariant property + object value = p.GetValue(p.PropertyType.Variations.VariesByNothing() ? null : "en-US"); Assert.IsNotNull(value); } } @@ -860,19 +869,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_CustomPropertySort() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Name.Contains("Text")); + IQuery query = scope.SqlContext.Query().Where(x => x.Name.Contains("Text")); try { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var result = repository.GetPage(query, 0, 2, out var totalRecords, null, Ordering.By("title", isCustomField: true)); + IEnumerable result = repository.GetPage(query, 0, 2, out long totalRecords, null, Ordering.By("title", isCustomField: true)); Assert.AreEqual(3, totalRecords); Assert.AreEqual(2, result.Count()); @@ -892,19 +901,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_FirstPage() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); try { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var result = repository.GetPage(query, 0, 1, out var totalRecords, null, Ordering.By("Name")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("Name")); Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -921,13 +930,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_SecondPage() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.GetPage(query, 1, 1, out var totalRecords, null, Ordering.By("Name")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 1, 1, out long totalRecords, null, Ordering.By("Name")); Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -938,13 +947,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_SinglePage() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.GetPage(query, 0, 2, out var totalRecords, null, Ordering.By("Name")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 2, out long totalRecords, null, Ordering.By("Name")); Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); Assert.That(result.Count(), Is.EqualTo(2)); @@ -955,13 +964,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_DescendingOrder() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.GetPage(query, 0, 1, out var totalRecords, null, Ordering.By("Name", Direction.Descending)); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("Name", Direction.Descending)); Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -972,15 +981,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_FilterMatchingSome() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); - var filterQuery = scope.SqlContext.Query().Where(x => x.Name.Contains("Page 2")); - var result = repository.GetPage(query, 0, 1, out var totalRecords, filterQuery, Ordering.By("Name")); + IQuery filterQuery = scope.SqlContext.Query().Where(x => x.Name.Contains("Page 2")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, filterQuery, Ordering.By("Name")); Assert.That(totalRecords, Is.EqualTo(1)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -991,15 +1000,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetPagedResultsByQuery_FilterMatchingAll() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); - var filterQuery = scope.SqlContext.Query().Where(x => x.Name.Contains("text")); - var result = repository.GetPage(query, 0, 1, out var totalRecords, filterQuery, Ordering.By("Name")); + IQuery filterQuery = scope.SqlContext.Query().Where(x => x.Name.Contains("text")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, filterQuery, Ordering.By("Name")); Assert.That(totalRecords, Is.EqualTo(2)); Assert.That(result.Count(), Is.EqualTo(1)); @@ -1010,13 +1019,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetAllContentByIds() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); - - var contents = repository.GetMany(_subpage.Id, _subpage2.Id); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); + IEnumerable contents = repository.GetMany(_subpage.Id, _subpage2.Id); Assert.That(contents, Is.Not.Null); Assert.That(contents.Any(), Is.True); @@ -1027,12 +1035,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetAllContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var contents = repository.GetMany(); + IEnumerable contents = repository.GetMany(); Assert.That(contents, Is.Not.Null); Assert.That(contents.Any(), Is.True); @@ -1053,12 +1061,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void ExistContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var exists = repository.Exists(_subpage.Id); + bool exists = repository.Exists(_subpage.Id); Assert.That(exists, Is.True); } @@ -1067,13 +1075,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CountContent() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.Count(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + int result = repository.Count(query); Assert.That(result, Is.GreaterThanOrEqualTo(2)); } @@ -1082,19 +1090,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void QueryContentByUniqueId() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out _); + DocumentRepository repository = CreateRepository((IScopeAccessor)provider, out _); - var query = scope.SqlContext.Query().Where(x => x.Key == new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); - var content = repository.Get(query).SingleOrDefault(); + IQuery query = scope.SqlContext.Query().Where(x => x.Key == new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); + IContent content = repository.Get(query).SingleOrDefault(); Assert.IsNotNull(content); Assert.AreEqual(_textpage.Id, content.Id); } } - - } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DomainRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DomainRepositoryTest.cs index b6faa4e31d..3a9794a93b 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DomainRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DomainRepositoryTest.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Data; using System.Linq; using Microsoft.Extensions.Logging; @@ -20,20 +23,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class DomainRepositoryTest : UmbracoIntegrationTest { private ILanguageRepository LanguageRepository => GetRequiredService(); + private IDocumentRepository DocumentRepository => GetRequiredService(); + private IContentTypeRepository ContentTypeRepository => GetRequiredService(); private DomainRepository CreateRepository(IScopeProvider provider) { - var accessor = (IScopeAccessor) provider; + var accessor = (IScopeAccessor)provider; var domainRepository = new DomainRepository(accessor, AppCaches.NoCache, LoggerFactory.CreateLogger()); return domainRepository; } private int CreateTestData(string isoName, out ContentType ct) { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var globalSettings = new GlobalSettings(); var lang = new Language(globalSettings, isoName); @@ -51,21 +56,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_And_Get_By_Id() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain); - //re-get + // re-get domain = repo.Get(domain.Id); Assert.NotNull(domain); @@ -81,20 +85,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_And_Get_By_Id_Empty_lang() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var content = DocumentRepository.Get(contentId); + IContent content = DocumentRepository.Get(contentId); var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id }; repo.Save(domain); - //re-get + // re-get domain = repo.Get(domain.Id); Assert.NotNull(domain); @@ -109,16 +112,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Cant_Create_Duplicate_Domain_Name() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); var domain1 = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain1); @@ -132,26 +134,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain); repo.Delete(domain); - //re-get + // re-get domain = repo.Get(domain.Id); - Assert.IsNull(domain); } } @@ -159,29 +159,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Update() { - ContentType ct; - var contentId1 = CreateTestData("en-AU", out ct); + int contentId1 = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var content1 = DocumentRepository.Get(contentId1); + IContent content1 = DocumentRepository.Get(contentId1); - //more test data - var lang1 = LanguageRepository.GetByIsoCode("en-AU"); + // more test data + ILanguage lang1 = LanguageRepository.GetByIsoCode("en-AU"); var globalSettings = new GlobalSettings(); var lang2 = new Language(globalSettings, "es"); LanguageRepository.Save(lang2); var content2 = new Content("test", -1, ct) { CreatorId = 0, WriterId = 0 }; DocumentRepository.Save(content2); - var domain = (IDomain)new UmbracoDomain("test.com") { RootContentId = content1.Id, LanguageId = lang1.Id }; repo.Save(domain); - //re-get + // re-get domain = repo.Get(domain.Id); domain.DomainName = "blah.com"; @@ -189,7 +187,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor domain.LanguageId = lang2.Id; repo.Save(domain); - //re-get + // re-get domain = repo.Get(domain.Id); Assert.AreEqual("blah.com", domain.DomainName); @@ -199,20 +197,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - [Test] public void Exists() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { @@ -220,7 +216,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var found = repo.Exists("test1.com"); + bool found = repo.Exists("test1.com"); Assert.IsTrue(found); } @@ -229,16 +225,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_By_Name() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { @@ -246,7 +241,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var found = repo.GetByName("test1.com"); + IDomain found = repo.GetByName("test1.com"); Assert.IsNotNull(found); } @@ -255,16 +250,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { @@ -272,7 +266,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var all = repo.GetMany(); + IEnumerable all = repo.GetMany(); Assert.AreEqual(10, all.Count()); } @@ -281,16 +275,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All_Ids() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); var ids = new List(); for (int i = 0; i < 10; i++) @@ -300,7 +293,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor ids.Add(domain.Id); } - var all = repo.GetMany(ids.Take(8).ToArray()); + IEnumerable all = repo.GetMany(ids.Take(8).ToArray()); Assert.AreEqual(8, all.Count()); } @@ -309,16 +302,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All_Without_Wildcards() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); - var lang = LanguageRepository.GetByIsoCode("en-AU"); - var content = DocumentRepository.Get(contentId); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); + IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { @@ -330,7 +322,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var all = repo.GetAll(false); + IEnumerable all = repo.GetAll(false); Assert.AreEqual(5, all.Count()); } @@ -339,20 +331,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All_For_Content() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); var contentItems = new List(); - var lang = LanguageRepository.GetByIsoCode("en-AU"); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); contentItems.Add(DocumentRepository.Get(contentId)); - //more test data (3 content items total) + // more test data (3 content items total) for (int i = 0; i < 2; i++) { var c = new Content("test" + i, -1, ct) { CreatorId = 0, WriterId = 0 }; @@ -370,13 +361,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var all1 = repo.GetAssignedDomains(contentItems[0].Id, true); + IEnumerable all1 = repo.GetAssignedDomains(contentItems[0].Id, true); Assert.AreEqual(5, all1.Count()); - var all2 = repo.GetAssignedDomains(contentItems[1].Id, true); + IEnumerable all2 = repo.GetAssignedDomains(contentItems[1].Id, true); Assert.AreEqual(5, all2.Count()); - var all3 = repo.GetAssignedDomains(contentItems[2].Id, true); + IEnumerable all3 = repo.GetAssignedDomains(contentItems[2].Id, true); Assert.AreEqual(0, all3.Count()); } } @@ -384,20 +375,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All_For_Content_Without_Wildcards() { - ContentType ct; - var contentId = CreateTestData("en-AU", out ct); + int contentId = CreateTestData("en-AU", out ContentType ct); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + DomainRepository repo = CreateRepository(provider); var contentItems = new List(); - var lang = LanguageRepository.GetByIsoCode("en-AU"); + ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); contentItems.Add(DocumentRepository.Get(contentId)); - //more test data (3 content items total) + // more test data (3 content items total) for (int i = 0; i < 2; i++) { var c = new Content("test" + i, -1, ct) { CreatorId = 0, WriterId = 0 }; @@ -415,10 +405,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repo.Save(domain); } - var all1 = repo.GetAssignedDomains(contentItems[0].Id, false); + IEnumerable all1 = repo.GetAssignedDomains(contentItems[0].Id, false); Assert.AreEqual(5, all1.Count()); - var all2 = repo.GetAssignedDomains(contentItems[1].Id, false); + IEnumerable all2 = repo.GetAssignedDomains(contentItems[1].Id, false); Assert.AreEqual(0, all2.Count()); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/EntityRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/EntityRepositoryTest.cs index 8fbfc765d7..cd2e5e5d01 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/EntityRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/EntityRepositoryTest.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System.Collections.Generic; using System.Linq; using NUnit.Framework; @@ -5,6 +8,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Core.Services; @@ -18,71 +22,61 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [UmbracoTest(Mapper = true, Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class EntityRepositoryTest : UmbracoIntegrationTest { - private EntityRepository CreateRepository(IScopeAccessor scopeAccessor) - { - var entityRepository = new EntityRepository(scopeAccessor, AppCaches.Disabled); - return entityRepository; - } - [Test] public void Get_Paged_Mixed_Entities_By_Ids() { - //Create content - - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); + // Create content + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); var createdContent = new List(); - var contentType = ContentTypeBuilder.CreateBasicContentType("blah"); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType("blah"); contentTypeService.Save(contentType); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateBasicContent(contentType); + Content c1 = ContentBuilder.CreateBasicContent(contentType); contentService.Save(c1); createdContent.Add(c1); } - //Create media - - var mediaService = GetRequiredService(); - var mediaTypeService = GetRequiredService(); + // Create media + IMediaService mediaService = GetRequiredService(); + IMediaTypeService mediaTypeService = GetRequiredService(); var createdMedia = new List(); - var imageType = MediaTypeBuilder.CreateImageMediaType("myImage"); + MediaType imageType = MediaTypeBuilder.CreateImageMediaType("myImage"); mediaTypeService.Save(imageType); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageType, -1); + Media c1 = MediaBuilder.CreateMediaImage(imageType, -1); mediaService.Save(c1); createdMedia.Add(c1); } // Create members - - var memberService = GetRequiredService(); - var memberTypeService = GetRequiredService(); - var memberType = MemberTypeBuilder.CreateSimpleMemberType("simple"); + IMemberService memberService = GetRequiredService(); + IMemberTypeService memberTypeService = GetRequiredService(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType("simple"); memberTypeService.Save(memberType); var createdMembers = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10).ToList(); memberService.Save(createdMembers); - - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repo = CreateRepository((IScopeAccessor)provider); + EntityRepository repo = CreateRepository((IScopeAccessor)provider); - var ids = createdContent.Select(x => x.Id).Concat(createdMedia.Select(x => x.Id)).Concat(createdMembers.Select(x => x.Id)); + IEnumerable ids = createdContent.Select(x => x.Id).Concat(createdMedia.Select(x => x.Id)).Concat(createdMembers.Select(x => x.Id)); - var objectTypes = new[] { Constants.ObjectTypes.Document, Constants.ObjectTypes.Media, Constants.ObjectTypes.Member }; + System.Guid[] objectTypes = new[] { Constants.ObjectTypes.Document, Constants.ObjectTypes.Media, Constants.ObjectTypes.Member }; - var query = provider.SqlContext.Query() + IQuery query = provider.SqlContext.Query() .WhereIn(e => e.Id, ids); - var entities = repo.GetPagedResultsByQuery(query, objectTypes, 0, 20, out var totalRecords, null, null).ToList(); + var entities = repo.GetPagedResultsByQuery(query, objectTypes, 0, 20, out long totalRecords, null, null).ToList(); Assert.AreEqual(20, entities.Count); Assert.AreEqual(30, totalRecords); - //add the next page + // add the next page entities.AddRange(repo.GetPagedResultsByQuery(query, objectTypes, 1, 20, out totalRecords, null, null)); Assert.AreEqual(30, entities.Count); @@ -97,5 +91,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual(10, memberEntities.Count); } } + + private EntityRepository CreateRepository(IScopeAccessor scopeAccessor) => new EntityRepository(scopeAccessor, AppCaches.Disabled); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs index 93b6ee43f5..29885d732d 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs @@ -1,6 +1,9 @@ -using System; -using NUnit.Framework; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using Microsoft.Extensions.Logging; +using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; @@ -17,10 +20,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CanSetAndGet() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; // Insert new key/value - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { var keyValue = new KeyValue { @@ -28,26 +31,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Value = "bar", UpdateDate = DateTime.Now, }; - var repo = CreateRepository(provider); + IKeyValueRepository repo = CreateRepository(provider); repo.Save(keyValue); scope.Complete(); } // Retrieve key/value - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var keyValue = repo.Get("foo"); + IKeyValueRepository repo = CreateRepository(provider); + IKeyValue keyValue = repo.Get("foo"); scope.Complete(); Assert.AreEqual("bar", keyValue.Value); } // Update value - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var keyValue = repo.Get("foo"); + IKeyValueRepository repo = CreateRepository(provider); + IKeyValue keyValue = repo.Get("foo"); keyValue.Value = "buzz"; keyValue.UpdateDate = DateTime.Now; repo.Save(keyValue); @@ -55,19 +58,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } // Retrieve key/value again - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var keyValue = repo.Get("foo"); + IKeyValueRepository repo = CreateRepository(provider); + IKeyValue keyValue = repo.Get("foo"); scope.Complete(); Assert.AreEqual("buzz", keyValue.Value); } } - private IKeyValueRepository CreateRepository(IScopeProvider provider) - { - return new KeyValueRepository((IScopeAccessor) provider, LoggerFactory.CreateLogger()); - } + private IKeyValueRepository CreateRepository(IScopeProvider provider) => new KeyValueRepository((IScopeAccessor)provider, LoggerFactory.CreateLogger()); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/LanguageRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/LanguageRepositoryTest.cs index aa9c0ddc86..45e63cf091 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/LanguageRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/LanguageRepositoryTest.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 Microsoft.Extensions.Logging; @@ -7,6 +11,7 @@ using Umbraco.Core.Cache; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Persistence; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Core.Services; @@ -28,23 +33,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor _globalSettings = new GlobalSettings(); } - private LanguageRepository CreateRepository(IScopeProvider provider) - { - return new LanguageRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Microsoft.Extensions.Options.Options.Create(_globalSettings)); - } - [Test] public void Can_Perform_Get_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(1); + ILanguage language = repository.Get(1); // Assert Assert.That(language, Is.Not.Null); @@ -58,10 +58,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Get_By_Iso_Code_On_LanguageRepository() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); var au = CultureInfo.GetCultureInfo("en-AU"); var language = (ILanguage)new Language(_globalSettings, au.Name) @@ -71,7 +71,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; repository.Save(language); - //re-get + // re-get language = repository.GetByIsoCode(au.Name); // Assert @@ -87,13 +87,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Get_When_Id_Doesnt_Exist_Returns_Null() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(0); + ILanguage language = repository.Get(0); // Assert Assert.That(language, Is.Null); @@ -104,13 +104,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var languages = repository.GetMany(); + IEnumerable languages = repository.GetMany(); // Assert Assert.That(languages, Is.Not.Null); @@ -124,13 +124,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_With_Params_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var languages = repository.GetMany(1, 2); + IEnumerable languages = repository.GetMany(1, 2); // Assert Assert.That(languages, Is.Not.Null); @@ -144,14 +144,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var query = scope.SqlContext.Query().Where(x => x.IsoCode == "da-DK"); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.IsoCode == "da-DK"); + IEnumerable result = repository.Get(query); // Assert Assert.That(result, Is.Not.Null); @@ -164,13 +164,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var query = scope.SqlContext.Query().Where(x => x.IsoCode.StartsWith("D")); + IQuery query = scope.SqlContext.Query().Where(x => x.IsoCode.StartsWith("D")); int count = repository.Count(query); // Assert @@ -182,10 +182,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act var languageBR = new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR" }; @@ -193,7 +193,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(languageBR.HasIdentity, Is.True); - Assert.That(languageBR.Id, Is.EqualTo(6)); //With 5 existing entries the Id should be 6 + Assert.That(languageBR.Id, Is.EqualTo(6)); // With 5 existing entries the Id should be 6 Assert.IsFalse(languageBR.IsDefault); Assert.IsFalse(languageBR.IsMandatory); Assert.IsNull(languageBR.FallbackLanguageId); @@ -204,10 +204,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_LanguageRepository_With_Boolean_Properties() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act var languageBR = new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR", IsDefault = true, IsMandatory = true }; @@ -215,7 +215,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(languageBR.HasIdentity, Is.True); - Assert.That(languageBR.Id, Is.EqualTo(6)); //With 5 existing entries the Id should be 6 + Assert.That(languageBR.Id, Is.EqualTo(6)); // With 5 existing entries the Id should be 6 Assert.IsTrue(languageBR.IsDefault); Assert.IsTrue(languageBR.IsMandatory); Assert.IsNull(languageBR.FallbackLanguageId); @@ -226,10 +226,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_LanguageRepository_With_Fallback_Language() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act var languageBR = new Language(_globalSettings, "pt-BR") @@ -241,7 +241,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(languageBR.HasIdentity, Is.True); - Assert.That(languageBR.Id, Is.EqualTo(6)); //With 5 existing entries the Id should be 6 + Assert.That(languageBR.Id, Is.EqualTo(6)); // With 5 existing entries the Id should be 6 Assert.That(languageBR.FallbackLanguageId, Is.EqualTo(1)); } } @@ -250,10 +250,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_LanguageRepository_With_New_Default() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); var languageBR = (ILanguage)new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR", IsDefault = true, IsMandatory = true }; repository.Save(languageBR); @@ -278,20 +278,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(5); + ILanguage language = repository.Get(5); language.IsoCode = "pt-BR"; language.CultureName = "pt-BR"; language.FallbackLanguageId = 1; repository.Save(language); - var languageUpdated = repository.Get(5); + ILanguage languageUpdated = repository.Get(5); // Assert Assert.That(languageUpdated, Is.Not.Null); @@ -305,13 +305,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Perform_Update_With_Existing_Culture() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(5); + ILanguage language = repository.Get(5); language.IsoCode = "da-DK"; language.CultureName = "da-DK"; @@ -323,16 +323,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var language = repository.Get(3); + ILanguage language = repository.Get(3); repository.Delete(language); - var exists = repository.Exists(3); + bool exists = repository.Exists(3); // Assert Assert.That(exists, Is.False); @@ -343,20 +343,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_LanguageRepository_With_Language_Used_As_Fallback() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { // Add language to delete as a fall-back language to another one - var repository = CreateRepository(provider); - var languageToFallbackFrom = repository.Get(5); + LanguageRepository repository = CreateRepository(provider); + ILanguage languageToFallbackFrom = repository.Get(5); languageToFallbackFrom.FallbackLanguageId = 2; // fall back to #2 (something we can delete) repository.Save(languageToFallbackFrom); // delete #2 - var languageToDelete = repository.Get(2); + ILanguage languageToDelete = repository.Get(2); repository.Delete(languageToDelete); - var exists = repository.Exists(2); + bool exists = repository.Exists(2); // has been deleted Assert.That(exists, Is.False); @@ -367,14 +367,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_LanguageRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + LanguageRepository repository = CreateRepository(provider); // Act - var exists = repository.Exists(3); - var doesntExist = repository.Exists(10); + bool exists = repository.Exists(3); + bool doesntExist = repository.Exists(10); // Assert Assert.That(exists, Is.True); @@ -382,22 +382,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } + private LanguageRepository CreateRepository(IScopeProvider provider) => new LanguageRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Microsoft.Extensions.Options.Options.Create(_globalSettings)); + private void CreateTestData() { - //Id 1 is en-US - when Umbraco is installed - - var localizationService = GetRequiredService(); + // Id 1 is en-US - when Umbraco is installed + ILocalizationService localizationService = GetRequiredService(); var languageDK = new Language(_globalSettings, "da-DK") { CultureName = "da-DK" }; - localizationService.Save(languageDK);//Id 2 + localizationService.Save(languageDK); // Id 2 var languageSE = new Language(_globalSettings, "sv-SE") { CultureName = "sv-SE" }; - localizationService.Save(languageSE);//Id 3 + localizationService.Save(languageSE); // Id 3 var languageDE = new Language(_globalSettings, "de-DE") { CultureName = "de-DE" }; - localizationService.Save(languageDE);//Id 4 + localizationService.Save(languageDE); // Id 4 var languagePT = new Language(_globalSettings, "pt-PT") { CultureName = "pt-PT" }; - localizationService.Save(languagePT);//Id 5 + localizationService.Save(languagePT); // Id 5 } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs index e68f9584fb..160642bcb7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs @@ -1,4 +1,8 @@ -using System.Data.SqlClient; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; @@ -29,10 +33,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Cannot_Add_Duplicate_Macros() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); var macro = new Macro(ShortStringHelper, "test1", "Test", "~/views/macropartials/test.cshtml"); @@ -44,12 +48,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Cannot_Update_To_Duplicate_Macro_Alias() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - var macro = repository.Get(1); + IMacro macro = repository.Get(1); macro.Alias = "test2"; Assert.Throws(() => repository.Save(macro)); @@ -60,10 +64,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Instantiate_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Assert Assert.That(repository, Is.Not.Null); @@ -74,13 +78,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var macro = repository.Get(1); + IMacro macro = repository.Get(1); // Assert Assert.That(macro, Is.Not.Null); @@ -100,13 +104,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var macros = repository.GetMany(); + IEnumerable macros = repository.GetMany(); // Assert Assert.That(macros.Count(), Is.EqualTo(3)); @@ -117,14 +121,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_Repository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var query = scope.SqlContext.Query().Where(x => x.Alias.ToUpper() == "TEST1"); - var result = repository.Get((IQuery) query); + IQuery query = scope.SqlContext.Query().Where(x => x.Alias.ToUpper() == "TEST1"); + IEnumerable result = repository.Get((IQuery)query); // Assert Assert.AreEqual(1, result.Count()); @@ -135,13 +139,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_Repository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var query = scope.SqlContext.Query().Where(x => x.Name.StartsWith("Test")); + IQuery query = scope.SqlContext.Query().Where(x => x.Name.StartsWith("Test")); int count = repository.Count(query); // Assert @@ -153,10 +157,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act var macro = new Macro(ShortStringHelper, "test", "Test", "~/views/macropartials/test.cshtml"); @@ -165,7 +169,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(macro.HasIdentity, Is.True); - Assert.That(macro.Id, Is.EqualTo(4));//With 3 existing entries the Id should be 4 + Assert.That(macro.Id, Is.EqualTo(4)); // With 3 existing entries the Id should be 4 Assert.Greater(macro.Properties.Values.Single().Id, 0); } } @@ -174,13 +178,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var macro = repository.Get(2); + IMacro macro = repository.Get(2); macro.Name = "Hello"; macro.CacheDuration = 1234; macro.CacheByPage = true; @@ -191,7 +195,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(macro); - var macroUpdated = repository.Get(2); + IMacro macroUpdated = repository.Get(2); // Assert Assert.That(macroUpdated, Is.Not.Null); @@ -209,17 +213,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var macro = repository.Get(3); + IMacro macro = repository.Get(3); Assert.IsNotNull(macro); repository.Delete(macro); - var exists = repository.Exists(3); + bool exists = repository.Exists(3); // Assert Assert.That(exists, Is.False); @@ -230,14 +234,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act - var exists = repository.Exists(3); - var doesntExist = repository.Exists(10); + bool exists = repository.Exists(3); + bool doesntExist = repository.Exists(10); // Assert Assert.That(exists, Is.True); @@ -249,25 +253,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Add_Property_For_Macro() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - var macro = repository.Get(1); + IMacro macro = repository.Get(1); macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); repository.Save(macro); // Assert - Assert.Greater(macro.Properties.Values.First().Id, 0); //ensure id is returned - var result = repository.Get(1); + Assert.Greater(macro.Properties.Values.First().Id, 0); // ensure id is returned + IMacro result = repository.Get(1); Assert.Greater(result.Properties.Values.First().Id, 0); Assert.AreEqual(1, result.Properties.Values.Count()); Assert.AreEqual("new1", result.Properties.Values.First().Alias); Assert.AreEqual("New1", result.Properties.Values.First().Name); Assert.AreEqual(3, result.Properties.Values.First().SortOrder); - } } @@ -275,24 +278,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Add_New_Macro_With_Property() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); repository.Save(macro); - // Assert - var result = repository.Get(macro.Id); + IMacro result = repository.Get(macro.Id); Assert.AreEqual(1, result.Properties.Values.Count()); Assert.AreEqual("blah1", result.Properties.Values.First().Alias); Assert.AreEqual("New1", result.Properties.Values.First().Name); Assert.AreEqual(4, result.Properties.Values.First().SortOrder); - } } @@ -300,23 +301,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Remove_Macro_Property() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); repository.Save(macro); - var result = repository.Get(macro.Id); + IMacro result = repository.Get(macro.Id); result.Properties.Remove("blah1"); repository.Save(result); // Assert result = repository.Get(macro.Id); Assert.AreEqual(0, result.Properties.Values.Count()); - } } @@ -324,16 +324,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Add_Remove_Macro_Properties() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); var prop1 = new MacroProperty("blah1", "New1", 4, "test.editor"); var prop2 = new MacroProperty("blah2", "New2", 3, "test.editor"); - //add/remove a few to test the collection observable + // add/remove a few to test the collection observable macro.Properties.Add(prop1); macro.Properties.Add(prop2); macro.Properties.Remove(prop1); @@ -343,11 +343,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(macro); // Assert - var result = repository.Get(macro.Id); + IMacro result = repository.Get(macro.Id); Assert.AreEqual(1, result.Properties.Values.Count()); Assert.AreEqual("blah2", result.Properties.Values.Single().Alias); - } } @@ -355,26 +354,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_Property_For_Macro() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - var macro = repository.Get(1); + IMacro macro = repository.Get(1); macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); repository.Save(macro); - //Act + // Act macro = repository.Get(1); macro.Properties["new1"].Name = "this is a new name"; repository.Save(macro); - // Assert - var result = repository.Get(1); + IMacro result = repository.Get(1); Assert.AreEqual("new1", result.Properties.Values.First().Alias); Assert.AreEqual("this is a new name", result.Properties.Values.First().Name); - } } @@ -382,32 +379,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_Macro_Property_Alias() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - var macro = repository.Get(1); + IMacro macro = repository.Get(1); macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); repository.Save(macro); - //Act + // Act macro = repository.Get(1); macro.Properties.UpdateProperty("new1", newAlias: "newAlias"); repository.Save(macro); // Assert - var result = repository.Get(1); + IMacro result = repository.Get(1); Assert.AreEqual("newAlias", result.Properties.Values.First().Alias); } } public void CreateTestData() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, _logger, ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); repository.Save(new Macro(ShortStringHelper, "test1", "Test1", "~/views/macropartials/test1.cshtml")); repository.Save(new Macro(ShortStringHelper, "test2", "Test2", "~/views/macropartials/test2.cshtml")); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaRepositoryTest.cs index f504218cec..0c70405378 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaRepositoryTest.cs @@ -1,4 +1,8 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; +using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Moq; @@ -10,6 +14,7 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; @@ -27,9 +32,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class MediaRepositoryTest : UmbracoIntegrationTest { private IMediaService MediaService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); + private ITemplateRepository TemplateRepository => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); // Makes handing IDs easier, these are set by CreateTestData @@ -38,15 +47,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private Media _testFile; [SetUp] - public void SetUpTestData() - { - CreateTestData(); - } + public void SetUpTestData() => CreateTestData(); private MediaRepository CreateRepository(IScopeProvider provider, out MediaTypeRepository mediaTypeRepository, AppCaches appCaches = null) { - appCaches = appCaches ?? AppCaches.NoCache; - var scopeAccessor = (IScopeAccessor) provider; + appCaches ??= AppCaches.NoCache; + var scopeAccessor = (IScopeAccessor)provider; var globalSettings = new GlobalSettings(); var commonRepository = new ContentTypeCommonRepository(scopeAccessor, TemplateRepository, appCaches, ShortStringHelper); var languageRepository = new LanguageRepository(scopeAccessor, appCaches, LoggerFactory.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); @@ -65,46 +71,46 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CacheActiveForIntsAndGuids() { - MediaTypeRepository mediaTypeRepository; - var realCache = new AppCaches( new ObjectCacheAppCache(), new DictionaryAppCache(), new IsolatedCaches(t => new ObjectCacheAppCache())); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out mediaTypeRepository, appCaches: realCache); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository, appCaches: realCache); - var udb = scope.Database; + IUmbracoDatabase udb = scope.Database; udb.EnableSqlCount = false; - var mediaType = MediaTypeBuilder.CreateSimpleMediaType("umbTextpage1", "Textpage"); + MediaType mediaType = MediaTypeBuilder.CreateSimpleMediaType("umbTextpage1", "Textpage"); mediaTypeRepository.Save(mediaType); - var media = MediaBuilder.CreateSimpleMedia(mediaType, "hello", -1); + Media media = MediaBuilder.CreateSimpleMedia(mediaType, "hello", -1); repository.Save(media); udb.EnableSqlCount = true; - //go get it, this should already be cached since the default repository key is the INT - var found = repository.Get(media.Id); + // go get it, this should already be cached since the default repository key is the INT + IMedia found = repository.Get(media.Id); Assert.AreEqual(0, udb.SqlCount); - //retrieve again, this should use cache + + // retrieve again, this should use cache found = repository.Get(media.Id); Assert.AreEqual(0, udb.SqlCount); - //reset counter + // reset counter udb.EnableSqlCount = false; udb.EnableSqlCount = true; - //now get by GUID, this won't be cached yet because the default repo key is not a GUID + // now get by GUID, this won't be cached yet because the default repo key is not a GUID found = repository.Get(media.Key); - var sqlCount = udb.SqlCount; + int sqlCount = udb.SqlCount; Assert.Greater(sqlCount, 0); - //retrieve again, this should use cache now + + // retrieve again, this should use cache now found = repository.Get(media.Key); Assert.AreEqual(sqlCount, udb.SqlCount); } @@ -114,26 +120,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SaveMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); - var mediaType = mediaTypeRepository.Get(1032); - var image = MediaBuilder.CreateMediaImage(mediaType, -1); + IMediaType mediaType = mediaTypeRepository.Get(1032); + Media image = MediaBuilder.CreateMediaImage(mediaType, -1); // Act mediaTypeRepository.Save(mediaType); repository.Save(image); - var fetched = repository.Get(image.Id); + IMedia fetched = repository.Get(image.Id); // Assert Assert.That(mediaType.HasIdentity, Is.True); Assert.That(image.HasIdentity, Is.True); - TestHelper.AssertPropertyValuesAreEqual(image, fetched, "yyyy-MM-dd HH:mm:ss"); + TestHelper.AssertPropertyValuesAreEqual(image, fetched); } } @@ -141,19 +146,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SaveMediaMultiple() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); - var mediaType = mediaTypeRepository.Get(1032); - var file = MediaBuilder.CreateMediaFile(mediaType, -1); + IMediaType mediaType = mediaTypeRepository.Get(1032); + Media file = MediaBuilder.CreateMediaFile(mediaType, -1); // Act repository.Save(file); - var image = MediaBuilder.CreateMediaImage(mediaType, -1); + Media image = MediaBuilder.CreateMediaImage(mediaType, -1); repository.Save(image); // Assert @@ -170,14 +174,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetMediaIsNotDirty() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var media = repository.Get(_testImage.Id); + IMedia media = repository.Get(_testImage.Id); bool dirty = ((ICanBeDirty)media).IsDirty(); // Assert @@ -189,18 +192,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void UpdateMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var content = repository.Get(_testFile.Id); + IMedia content = repository.Get(_testFile.Id); content.Name = "Test File Updated"; repository.Save(content); - var updatedContent = repository.Get(_testFile.Id); + IMedia updatedContent = repository.Get(_testFile.Id); // Assert Assert.That(updatedContent.Id, Is.EqualTo(content.Id)); @@ -212,18 +214,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void DeleteMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var media = repository.Get(_testFile.Id); + IMedia media = repository.Get(_testFile.Id); repository.Delete(media); - var deleted = repository.Get(_testFile.Id); - var exists = repository.Exists(_testFile.Id); + IMedia deleted = repository.Get(_testFile.Id); + bool exists = repository.Exists(_testFile.Id); // Assert Assert.That(deleted, Is.Null); @@ -235,14 +236,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var media = repository.Get(_testImage.Id); + IMedia media = repository.Get(_testImage.Id); // Assert Assert.That(media.Id, Is.EqualTo(_testImage.Id)); @@ -262,18 +262,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void QueryMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.Get(query); // Assert - Assert.That(result.Count(), Is.GreaterThanOrEqualTo(2)); //There should be two entities on level 2: File and Media + Assert.That(result.Count(), Is.GreaterThanOrEqualTo(2)); // There should be two entities on level 2: File and Media } } @@ -281,23 +280,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void QueryMedia_ContentTypeIdFilter() { // Arrange - var folderMediaType = MediaTypeService.Get(1031); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IMediaType folderMediaType = MediaTypeService.Get(1031); + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act for (int i = 0; i < 10; i++) { - var folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); + Media folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); repository.Save(folder); } - - var types = new[] { 1031 }; - var query = scope.SqlContext.Query().Where(x => types.Contains(x.ContentTypeId)); - var result = repository.Get(query); + int[] types = new[] { 1031 }; + IQuery query = scope.SqlContext.Query().Where(x => types.Contains(x.ContentTypeId)); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.GreaterThanOrEqualTo(11)); @@ -312,23 +310,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // and we don't absolutely need it now, so leaving it out for now // Arrange - var folderMediaType = MediaTypeService.Get(1031); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IMediaType folderMediaType = MediaTypeService.Get(1031); + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act for (int i = 0; i < 10; i++) { - var folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); + Media folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); repository.Save(folder); } - - var types = new[] { "Folder" }; - var query = scope.SqlContext.Query().Where(x => types.Contains(x.ContentType.Alias)); - var result = repository.Get(query); + string[] types = new[] { "Folder" }; + IQuery query = scope.SqlContext.Query().Where(x => types.Contains(x.ContentType.Alias)); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.GreaterThanOrEqualTo(11)); @@ -339,15 +336,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_FirstPage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - long totalRecords; - var result = repository.GetPage(query, 0, 1, out totalRecords, null, Ordering.By("SortOrder")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -360,16 +356,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_SecondPage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - long totalRecords; - var result = repository.GetPage(query, 1, 1, out totalRecords, null, Ordering.By("SortOrder")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 1, 1, out long totalRecords, null, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -382,16 +376,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_SinglePage() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - long totalRecords; - var result = repository.GetPage(query, 0, 2, out totalRecords, null, Ordering.By("SortOrder")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 2, out long totalRecords, null, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -404,16 +396,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_DescendingOrder() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - long totalRecords; - var result = repository.GetPage(query, 0, 1, out totalRecords, null, Ordering.By("SortOrder", Direction.Descending)); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("SortOrder", Direction.Descending)); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -426,15 +416,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_AlternateOrder() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); - var result = repository.GetPage(query, 0, 1, out var totalRecords, null, Ordering.By("Name")); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, null, Ordering.By("Name")); // Assert Assert.That(totalRecords, Is.GreaterThanOrEqualTo(2)); @@ -447,17 +436,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_FilterMatchingSome() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); - var filter = scope.SqlContext.Query().Where(x => x.Name.Contains("File")); - var result = repository.GetPage(query, 0, 1, out var totalRecords, filter, Ordering.By("SortOrder")); + IQuery filter = scope.SqlContext.Query().Where(x => x.Name.Contains("File")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, filter, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.EqualTo(1)); @@ -470,16 +458,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetPagedResultsByQuery_FilterMatchingAll() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out _); + MediaRepository repository = CreateRepository(provider, out _); // Act - var query = scope.SqlContext.Query().Where(x => x.Level == 2); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == 2); - var filter = scope.SqlContext.Query().Where(x => x.Name.Contains("Test")); - var result = repository.GetPage(query, 0, 1, out var totalRecords, filter, Ordering.By("SortOrder")); + IQuery filter = scope.SqlContext.Query().Where(x => x.Name.Contains("Test")); + IEnumerable result = repository.GetPage(query, 0, 1, out long totalRecords, filter, Ordering.By("SortOrder")); // Assert Assert.That(totalRecords, Is.EqualTo(2)); @@ -492,14 +480,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetAllMediaByIds() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var medias = repository.GetMany(_testImage.Id, _testFile.Id); + IEnumerable medias = repository.GetMany(_testImage.Id, _testFile.Id); // Assert Assert.That(medias, Is.Not.Null); @@ -512,14 +499,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void GetAllMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var medias = repository.GetMany(); + IEnumerable medias = repository.GetMany(); // Assert Assert.That(medias, Is.Not.Null); @@ -542,16 +528,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void ExistMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act - var exists = repository.Exists(_testImage.Id); - var existsToo = repository.Exists(_testImage.Id); - var doesntExists = repository.Exists(NodeDto.NodeIdSeed + 5); + bool exists = repository.Exists(_testImage.Id); + bool existsToo = repository.Exists(_testImage.Id); + bool doesntExists = repository.Exists(NodeDto.NodeIdSeed + 5); // Assert Assert.That(exists, Is.True); @@ -564,16 +549,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void CountMedia() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - MediaTypeRepository mediaTypeRepository; - var repository = CreateRepository(provider, out mediaTypeRepository); + MediaRepository repository = CreateRepository(provider, out MediaTypeRepository mediaTypeRepository); // Act int level = 2; - var query = scope.SqlContext.Query().Where(x => x.Level == level); - var result = repository.Count(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Level == level); + int result = repository.Count(query); // Assert Assert.That(result, Is.GreaterThanOrEqualTo(2)); @@ -582,18 +566,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void CreateTestData() { - //Create and Save folder-Media -> (1051) - var folderMediaType = MediaTypeService.Get(1031); + // Create and Save folder-Media -> (1051) + IMediaType folderMediaType = MediaTypeService.Get(1031); _testFolder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); MediaService.Save(_testFolder, 0); - //Create and Save image-Media -> (1052) - var imageMediaType = MediaTypeService.Get(1032); + // Create and Save image-Media -> (1052) + IMediaType imageMediaType = MediaTypeService.Get(1032); _testImage = MediaBuilder.CreateMediaImage(imageMediaType, _testFolder.Id); MediaService.Save(_testImage, 0); - //Create and Save file-Media -> (1053) - var fileMediaType = MediaTypeService.Get(1033); + // Create and Save file-Media -> (1053) + IMediaType fileMediaType = MediaTypeService.Get(1033); _testFile = MediaBuilder.CreateMediaFile(fileMediaType, _testFolder.Id); MediaService.Save(_testFile, 0); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaTypeRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaTypeRepositoryTest.cs index 77f18944c0..0626205d25 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaTypeRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MediaTypeRepositoryTest.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 Microsoft.Extensions.Logging; using NUnit.Framework; @@ -20,42 +24,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class MediaTypeRepositoryTest : UmbracoIntegrationTest { private IContentTypeCommonRepository CommonRepository => GetRequiredService(); + private ILanguageRepository LanguageRepository => GetRequiredService(); - private MediaTypeRepository CreateRepository(IScopeProvider provider) - { - return new MediaTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), CommonRepository, LanguageRepository, ShortStringHelper); - } - - private EntityContainerRepository CreateContainerRepository(IScopeProvider provider) - { - return new EntityContainerRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Constants.ObjectTypes.MediaTypeContainer); - - } - [Test] public void Can_Move() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); - var repository = CreateRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); var container1 = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah1" }; containerRepository.Save(container1); - var container2 = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah2", ParentId = container1.Id }; containerRepository.Save(container2); - var contentType = (IMediaType)MediaTypeBuilder.CreateVideoMediaType(); contentType.ParentId = container2.Id; repository.Save(contentType); - - //create a + // create a var contentType2 = (IMediaType)new MediaType(ShortStringHelper, contentType, "hello") { Name = "Blahasdfsadf" @@ -63,13 +54,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor contentType.ParentId = contentType.Id; repository.Save(contentType2); - - var result = repository.Move(contentType, container1).ToArray(); - + global::Umbraco.Core.Events.MoveEventInfo[] result = repository.Move(contentType, container1).ToArray(); Assert.AreEqual(2, result.Length); - //re-get + // re-get contentType = repository.Get(contentType.Id); contentType2 = repository.Get(contentType2.Id); @@ -77,23 +66,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType.Id).OriginalPath, contentType.Path); Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType2.Id).OriginalPath, contentType2.Path); } - } [Test] public void Can_Create_Container() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); Assert.That(container.Id, Is.GreaterThan(0)); - var found = containerRepository.Get(container.Id); + EntityContainer found = containerRepository.Get(container.Id); Assert.IsNotNull(found); } } @@ -101,10 +89,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete_Container() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); @@ -114,8 +102,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Act containerRepository.Delete(container); - - var found = containerRepository.Get(container.Id); + EntityContainer found = containerRepository.Get(container.Id); Assert.IsNull(found); } } @@ -123,21 +110,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_Container_Containing_Media_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); - var repository = CreateRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); - - var contentType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType contentType = MediaTypeBuilder.CreateVideoMediaType(); contentType.ParentId = container.Id; repository.Save(contentType); - Assert.AreEqual(container.Id, contentType.ParentId); } } @@ -145,26 +130,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Delete_Container_Containing_Media_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var containerRepository = CreateContainerRepository(provider); - var repository = CreateRepository(provider); + EntityContainerRepository containerRepository = CreateContainerRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" }; containerRepository.Save(container); - IMediaType contentType = MediaTypeBuilder.CreateVideoMediaType(); contentType.ParentId = container.Id; repository.Save(contentType); - // Act containerRepository.Delete(container); - - var found = containerRepository.Get(container.Id); + EntityContainer found = containerRepository.Get(container.Id); Assert.IsNull(found); contentType = repository.Get(contentType.Id); @@ -177,17 +159,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var contentType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType contentType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(contentType); - - var fetched = repository.Get(contentType.Id); + IMediaType fetched = repository.Get(contentType.Id); // Assert Assert.That(contentType.HasIdentity, Is.True); @@ -195,27 +176,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(contentType.Path.Contains(","), Is.True); Assert.That(contentType.SortOrder, Is.GreaterThan(0)); - TestHelper.AssertPropertyValuesAreEqual(contentType, fetched, "yyyy-MM-dd HH:mm:ss", ignoreProperties: new[] { "UpdateDate" }); + TestHelper.AssertPropertyValuesAreEqual(contentType, fetched, ignoreProperties: new[] { "UpdateDate" }); } - - } [Test] public void Can_Perform_Update_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var videoMediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType videoMediaType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(videoMediaType); - // Act - var mediaType = repository.Get(videoMediaType.Id); + IMediaType mediaType = repository.Get(videoMediaType.Id); mediaType.Thumbnail = "Doc2.png"; mediaType.PropertyGroups["Media"].PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "subtitle") @@ -228,8 +206,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }); repository.Save(mediaType); - - var dirty = ((MediaType) mediaType).IsDirty(); + bool dirty = ((MediaType)mediaType).IsDirty(); // Assert Assert.That(mediaType.HasIdentity, Is.True); @@ -243,21 +220,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var mediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType mediaType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(mediaType); - - var contentType2 = repository.Get(mediaType.Id); + IMediaType contentType2 = repository.Get(mediaType.Id); repository.Delete(contentType2); - - var exists = repository.Exists(mediaType.Id); + bool exists = repository.Exists(mediaType.Id); // Assert Assert.That(exists, Is.False); @@ -268,13 +243,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var mediaType = repository.Get(1033); //File + IMediaType mediaType = repository.Get(1033); // File // Assert Assert.That(mediaType, Is.Not.Null); @@ -287,12 +262,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_By_Guid_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var mediaType = repository.Get(1033); //File + IMediaType mediaType = repository.Get(1033); // File // Act mediaType = repository.Get(mediaType.Key); @@ -308,13 +283,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var mediaTypes = repository.GetMany(); + IEnumerable mediaTypes = repository.GetMany(); int count = scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM umbracoNode WHERE nodeObjectType = @NodeObjectType", @@ -330,16 +305,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_By_Guid_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var allGuidIds = repository.GetMany().Select(x => x.Key).ToArray(); + Guid[] allGuidIds = repository.GetMany().Select(x => x.Key).ToArray(); // Act - - var mediaTypes = ((IReadRepository)repository).GetMany(allGuidIds); + IEnumerable mediaTypes = ((IReadRepository)repository).GetMany(allGuidIds); int count = scope.Database.ExecuteScalar( @@ -356,13 +330,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_MediaTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var exists = repository.Exists(1032); //Image + bool exists = repository.Exists(1032); // Image // Assert Assert.That(exists, Is.True); @@ -373,22 +347,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_MediaType_With_PropertyType_Removed() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var mediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType mediaType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(mediaType); - // Act - var mediaTypeV2 = repository.Get(mediaType.Id); + IMediaType mediaTypeV2 = repository.Get(mediaType.Id); mediaTypeV2.PropertyGroups["Media"].PropertyTypes.Remove("title"); repository.Save(mediaTypeV2); - - var mediaTypeV3 = repository.Get(mediaType.Id); + IMediaType mediaTypeV3 = repository.Get(mediaType.Id); // Assert Assert.That(mediaTypeV3.PropertyTypes.Any(x => x.Alias == "title"), Is.False); @@ -401,17 +373,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyTypes_On_Video_MediaType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); - var mediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType mediaType = MediaTypeBuilder.CreateVideoMediaType(); repository.Save(mediaType); - // Act - var contentType = repository.Get(mediaType.Id); + IMediaType contentType = repository.Get(mediaType.Id); // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(2)); @@ -423,18 +394,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_PropertyTypes_On_File_MediaType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MediaTypeRepository repository = CreateRepository(provider); // Act - var contentType = repository.Get(1033); //File + IMediaType contentType = repository.Get(1033); // File // Assert Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(3)); Assert.That(contentType.PropertyGroups.Count(), Is.EqualTo(1)); } } + + private MediaTypeRepository CreateRepository(IScopeProvider provider) => + new MediaTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), CommonRepository, LanguageRepository, ShortStringHelper); + + private EntityContainerRepository CreateContainerRepository(IScopeProvider provider) => + new EntityContainerRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Constants.ObjectTypes.MediaTypeContainer); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberRepositoryTest.cs index 7b26ccd500..57518eb371 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberRepositoryTest.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 Microsoft.Extensions.Logging; @@ -29,32 +33,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class MemberRepositoryTest : UmbracoIntegrationTest { private IPasswordHasher PasswordHasher => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IMemberTypeRepository MemberTypeRepository => GetRequiredService(); + private IMemberGroupRepository MemberGroupRepository => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); private MemberRepository CreateRepository(IScopeProvider provider) { - var accessor = (IScopeAccessor) provider; - var tagRepo = GetRequiredService(); - var relationTypeRepository = GetRequiredService(); - var relationRepository = GetRequiredService(); + var accessor = (IScopeAccessor)provider; + ITagRepository tagRepo = GetRequiredService(); + IRelationTypeRepository relationTypeRepository = GetRequiredService(); + IRelationRepository relationRepository = GetRequiredService(); var propertyEditors = new Lazy(() => new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty()))); var dataValueReferences = new DataValueReferenceFactoryCollection(Enumerable.Empty()); - var repository = new MemberRepository(accessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), MemberTypeRepository, MemberGroupRepository, tagRepo, Mock.Of(), relationRepository, relationTypeRepository, PasswordHasher, propertyEditors, dataValueReferences, DataTypeService, JsonSerializer); - return repository; + return new MemberRepository(accessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), MemberTypeRepository, MemberGroupRepository, tagRepo, Mock.Of(), relationRepository, relationTypeRepository, PasswordHasher, propertyEditors, dataValueReferences, DataTypeService, JsonSerializer); } [Test] public void GetMember() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var member = CreateTestMember(); + IMember member = CreateTestMember(); member = repository.Get(member.Id); @@ -66,16 +73,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetMembers() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var type = CreateTestMemberType(); - var m1 = CreateTestMember(type, "Test 1", "test1@test.com", "pass1", "test1"); - var m2 = CreateTestMember(type, "Test 2", "test2@test.com", "pass2", "test2"); + IMemberType type = CreateTestMemberType(); + IMember m1 = CreateTestMember(type, "Test 1", "test1@test.com", "pass1", "test1"); + IMember m2 = CreateTestMember(type, "Test 2", "test2@test.com", "pass2", "test2"); - var members = repository.GetMany(m1.Id, m2.Id); + IEnumerable members = repository.GetMany(m1.Id, m2.Id); Assert.That(members, Is.Not.Null); Assert.That(members.Count(), Is.EqualTo(2)); @@ -87,18 +94,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetAllMembers() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var type = CreateTestMemberType(); - for (var i = 0; i < 5; i++) + IMemberType type = CreateTestMemberType(); + for (int i = 0; i < 5; i++) { CreateTestMember(type, "Test " + i, "test" + i + "@test.com", "pass" + i, "test" + i); } - var members = repository.GetMany(); + IEnumerable members = repository.GetMany(); Assert.That(members, Is.Not.Null); Assert.That(members.Any(x => x == null), Is.False); @@ -111,17 +118,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void QueryMember() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); var key = Guid.NewGuid(); - var member = CreateTestMember(key: key); + IMember member = CreateTestMember(key: key); // Act - var query = scope.SqlContext.Query().Where(x => x.Key == key); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Key == key); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.EqualTo(1)); @@ -132,14 +139,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void SaveMember() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var member = CreateTestMember(); + IMember member = CreateTestMember(); - var sut = repository.Get(member.Id); + IMember sut = repository.Get(member.Id); Assert.That(sut, Is.Not.Null); Assert.That(sut.HasIdentity, Is.True); @@ -148,33 +155,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(sut.RawPasswordValue, Is.EqualTo("123")); Assert.That(sut.Username, Is.EqualTo("hefty")); - TestHelper.AssertPropertyValuesAreEqual(sut, member, "yyyy-MM-dd HH:mm:ss"); + TestHelper.AssertPropertyValuesAreEqual(sut, member); } } [Test] public void MemberHasBuiltinProperties() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); - var member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); + Member member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); repository.Save(member); - var sut = repository.Get(member.Id); + IMember sut = repository.Get(member.Id); Assert.That(memberType.CompositionPropertyGroups.Count(), Is.EqualTo(2)); Assert.That(memberType.CompositionPropertyTypes.Count(), Is.EqualTo(3 + ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Count)); Assert.That(sut.Properties.Count(), Is.EqualTo(3 + ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Count)); - var grp = memberType.CompositionPropertyGroups.FirstOrDefault(x => x.Name == Constants.Conventions.Member.StandardPropertiesGroupName); + PropertyGroup grp = memberType.CompositionPropertyGroups.FirstOrDefault(x => x.Name == Constants.Conventions.Member.StandardPropertiesGroupName); Assert.IsNotNull(grp); - var aliases = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Select(x => x.Key).ToArray(); - foreach (var p in memberType.CompositionPropertyTypes.Where(x => aliases.Contains(x.Alias))) + string[] aliases = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Select(x => x.Key).ToArray(); + foreach (IPropertyType p in memberType.CompositionPropertyTypes.Where(x => aliases.Contains(x.Alias))) { Assert.AreEqual(grp.Id, p.PropertyGroupId.Value); } @@ -185,21 +192,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SavingPreservesPassword() { IMember sut; - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); - - var member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); + Member member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); repository.Save(member); - sut = repository.Get(member.Id); - //when the password is null it will not overwrite what is already there. + + // When the password is null it will not overwrite what is already there. sut.RawPasswordValue = null; repository.Save(sut); @@ -213,19 +219,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SavingUpdatesNameAndEmail() { IMember sut; - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); - - var member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); + Member member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); repository.Save(member); - sut = repository.Get(member.Id); sut.Username = "This is new"; sut.Email = "thisisnew@hello.com"; @@ -241,16 +245,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void QueryMember_WithSubQuery() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; - var query = provider.SqlContext.Query().Where(x => - ((Member) x).LongStringPropertyValue.Contains("1095") && - ((Member) x).PropertyTypeAlias == "headshot"); + IQuery query = provider.SqlContext.Query().Where(x => + ((Member)x).LongStringPropertyValue.Contains("1095") && + ((Member)x).PropertyTypeAlias == "headshot"); - var sqlSubquery = GetSubquery(); + Sql sqlSubquery = GetSubquery(); var translator = new SqlTranslator(sqlSubquery, query); - var subquery = translator.Translate(); - var sql = GetBaseQuery(false) + Sql subquery = translator.Translate(); + Sql sql = GetBaseQuery(false) .Append("WHERE umbracoNode.id IN (" + subquery.SQL + ")", subquery.Arguments) .OrderByDescending(x => x.VersionDate) .OrderBy(x => x.SortOrder); @@ -261,19 +265,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IMember CreateTestMember(IMemberType memberType = null, string name = null, string email = null, string password = null, string username = null, Guid? key = null) { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); if (memberType == null) { memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); - } - var member = MemberBuilder.CreateSimpleMember(memberType, name ?? "Johnny Hefty", email ?? "johnny@example.com", password ?? "123", username ?? "hefty", key); + Member member = MemberBuilder.CreateSimpleMember(memberType, name ?? "Johnny Hefty", email ?? "johnny@example.com", password ?? "123", username ?? "hefty", key); repository.Save(member); scope.Complete(); @@ -283,12 +286,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IMemberType CreateTestMemberType(string alias = null) { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(alias); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(alias); MemberTypeRepository.Save(memberType); scope.Complete(); return memberType; @@ -297,10 +300,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private Sql GetBaseQuery(bool isCount) { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; if (isCount) { - var sqlCount = provider.SqlContext.Sql() + Sql sqlCount = provider.SqlContext.Sql() .SelectCount() .From() .InnerJoin().On(left => left.NodeId, right => right.NodeId) @@ -311,17 +314,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor return sqlCount; } - var sql = provider.SqlContext.Sql(); - sql.Select("umbracoNode.*", $"{Constants.DatabaseSchema.Tables.Content}.contentTypeId", "cmsContentType.alias AS ContentTypeAlias", $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionId", - $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionDate", "cmsMember.Email", - "cmsMember.LoginName", "cmsMember.Password", - Constants.DatabaseSchema.Tables.PropertyData + ".id AS PropertyDataId", Constants.DatabaseSchema.Tables.PropertyData + ".propertytypeid", - Constants.DatabaseSchema.Tables.PropertyData + ".dateValue", Constants.DatabaseSchema.Tables.PropertyData + ".intValue", - Constants.DatabaseSchema.Tables.PropertyData + ".textValue", Constants.DatabaseSchema.Tables.PropertyData + ".varcharValue", - "cmsPropertyType.id", "cmsPropertyType.Alias", "cmsPropertyType.Description", - "cmsPropertyType.Name", "cmsPropertyType.mandatory", "cmsPropertyType.validationRegExp", - "cmsPropertyType.sortOrder AS PropertyTypeSortOrder", "cmsPropertyType.propertyTypeGroupId", - "cmsPropertyType.dataTypeId", "cmsDataType.propertyEditorAlias", "cmsDataType.dbType") + Sql sql = provider.SqlContext.Sql(); + sql.Select( + "umbracoNode.*", + $"{Constants.DatabaseSchema.Tables.Content}.contentTypeId", + "cmsContentType.alias AS ContentTypeAlias", + $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionId", + $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionDate", + "cmsMember.Email", + "cmsMember.LoginName", + "cmsMember.Password", + Constants.DatabaseSchema.Tables.PropertyData + ".id AS PropertyDataId", + Constants.DatabaseSchema.Tables.PropertyData + ".propertytypeid", + Constants.DatabaseSchema.Tables.PropertyData + ".dateValue", + Constants.DatabaseSchema.Tables.PropertyData + ".intValue", + Constants.DatabaseSchema.Tables.PropertyData + ".textValue", + Constants.DatabaseSchema.Tables.PropertyData + ".varcharValue", + "cmsPropertyType.id", + "cmsPropertyType.Alias", + "cmsPropertyType.Description", + "cmsPropertyType.Name", + "cmsPropertyType.mandatory", + "cmsPropertyType.validationRegExp", + "cmsPropertyType.sortOrder AS PropertyTypeSortOrder", + "cmsPropertyType.propertyTypeGroupId", + "cmsPropertyType.dataTypeId", + "cmsDataType.propertyEditorAlias", + "cmsDataType.dbType") .From() .InnerJoin().On(left => left.NodeId, right => right.NodeId) .InnerJoin().On(left => left.NodeId, right => right.ContentTypeId) @@ -337,8 +356,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private Sql GetSubquery() { - var provider = ScopeProvider; - var sql = provider.SqlContext.Sql(); + IScopeProvider provider = ScopeProvider; + Sql sql = provider.SqlContext.Sql(); sql.Select("umbracoNode.id") .From() .InnerJoin().On(left => left.NodeId, right => right.NodeId) diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberTypeRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberTypeRepositoryTest.cs index f2bf72a74d..d8f550f1bb 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberTypeRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MemberTypeRepositoryTest.cs @@ -1,7 +1,11 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; -using Moq; using Microsoft.Extensions.Logging; +using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; @@ -22,25 +26,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { private MemberTypeRepository CreateRepository(IScopeProvider provider) { - var commonRepository = GetRequiredService(); - var languageRepository = GetRequiredService(); - return new MemberTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of>(), commonRepository, languageRepository, ShortStringHelper); + IContentTypeCommonRepository commonRepository = GetRequiredService(); + ILanguageRepository languageRepository = GetRequiredService(); + return new MemberTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, Mock.Of>(), commonRepository, languageRepository, ShortStringHelper); } [Test] public void Can_Persist_Member_Type() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType = (IMemberType) MemberTypeBuilder.CreateSimpleMemberType(); + var memberType = (IMemberType)MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); - var sut = repository.Get(memberType.Id); + IMemberType sut = repository.Get(memberType.Id); - var standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + Dictionary standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); Assert.That(sut, Is.Not.Null); Assert.That(sut.PropertyGroups.Count, Is.EqualTo(2)); @@ -49,48 +53,46 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(sut.PropertyGroups.Any(x => x.HasIdentity == false || x.Id == 0), Is.False); Assert.That(sut.PropertyTypes.Any(x => x.HasIdentity == false || x.Id == 0), Is.False); - TestHelper.AssertPropertyValuesAreEqual(sut, memberType, "yyyy-MM-dd HH:mm:ss"); + TestHelper.AssertPropertyValuesAreEqual(sut, memberType); } } [Test] public void Can_Persist_Member_Type_Same_Property_Keys() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); var memberType = (IMemberType)MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); scope.Complete(); - var propertyKeys = memberType.PropertyTypes.Select(x => x.Key).OrderBy(x => x).ToArray(); - var groupKeys = memberType.PropertyGroups.Select(x => x.Key).OrderBy(x => x).ToArray(); + Guid[] propertyKeys = memberType.PropertyTypes.Select(x => x.Key).OrderBy(x => x).ToArray(); + Guid[] groupKeys = memberType.PropertyGroups.Select(x => x.Key).OrderBy(x => x).ToArray(); memberType = repository.Get(memberType.Id); - var propertyKeys2 = memberType.PropertyTypes.Select(x => x.Key).OrderBy(x => x).ToArray(); - var groupKeys2 = memberType.PropertyGroups.Select(x => x.Key).OrderBy(x => x).ToArray(); + Guid[] propertyKeys2 = memberType.PropertyTypes.Select(x => x.Key).OrderBy(x => x).ToArray(); + Guid[] groupKeys2 = memberType.PropertyGroups.Select(x => x.Key).OrderBy(x => x).ToArray(); Assert.IsTrue(propertyKeys.SequenceEqual(propertyKeys2)); Assert.IsTrue(groupKeys.SequenceEqual(groupKeys2)); - } } [Test] public void Cannot_Persist_Member_Type_Without_Alias() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); memberType.Alias = null; - Assert.Throws(() => repository.Save(memberType)); } } @@ -98,24 +100,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_All_Member_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType1); - - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); memberType2.Name = "AnotherType"; memberType2.Alias = "anotherType"; repository.Save(memberType2); + IEnumerable result = repository.GetMany(); - var result = repository.GetMany(); - - //there are 3 because of the Member type created for init data + // there are 3 because of the Member type created for init data Assert.AreEqual(3, result.Count()); } } @@ -123,24 +123,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_All_Member_Types_By_Guid_Ids() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType1); - - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); memberType2.Name = "AnotherType"; memberType2.Alias = "anotherType"; repository.Save(memberType2); + IEnumerable result = ((IReadRepository)repository).GetMany(memberType1.Key, memberType2.Key); - var result = ((IReadRepository)repository).GetMany(memberType1.Key, memberType2.Key); - - //there are 3 because of the Member type created for init data + // there are 3 because of the Member type created for init data Assert.AreEqual(2, result.Count()); } } @@ -148,53 +146,49 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Member_Types_By_Guid_Id() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType1); - - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); memberType2.Name = "AnotherType"; memberType2.Alias = "anotherType"; repository.Save(memberType2); + IMemberType result = repository.Get(memberType1.Key); - var result = repository.Get(memberType1.Key); - - //there are 3 because of the Member type created for init data + // there are 3 because of the Member type created for init data Assert.IsNotNull(result); Assert.AreEqual(memberType1.Key, result.Key); } } - //NOTE: This tests for left join logic (rev 7b14e8eacc65f82d4f184ef46c23340c09569052) + // NOTE: This tests for left join logic (rev 7b14e8eacc65f82d4f184ef46c23340c09569052) [Test] public void Can_Get_All_Members_When_No_Properties_Assigned() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); - var memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); memberType1.PropertyTypeCollection.Clear(); repository.Save(memberType1); - - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType(); memberType2.PropertyTypeCollection.Clear(); memberType2.Name = "AnotherType"; memberType2.Alias = "anotherType"; repository.Save(memberType2); + IEnumerable result = repository.GetMany(); - var result = repository.GetMany(); - - //there are 3 because of the Member type created for init data + // there are 3 because of the Member type created for init data Assert.AreEqual(3, result.Count()); } } @@ -202,10 +196,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Member_Type_By_Id() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); @@ -218,10 +212,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Member_Type_By_Guid_Id() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); @@ -235,12 +229,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Bug_Changing_Built_In_Member_Type_Property_Type_Aliases_Results_In_Exception() { - var stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + Dictionary stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType("mtype"); @@ -255,10 +249,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); - foreach (var stub in stubs) + foreach (KeyValuePair stub in stubs) { - var prop = memberType.PropertyTypes.First(x => x.Alias == stub.Key); - prop.Alias = prop.Alias + "__0000"; + IPropertyType prop = memberType.PropertyTypes.First(x => x.Alias == stub.Key); + prop.Alias += "__0000"; } // saving *existing* member type does *not* ensure stub properties @@ -273,19 +267,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.IsNotNull(memberType); Assert.AreEqual(2, memberType.PropertyGroups.Count); - Assert.AreEqual(3 + stubs.Count * 2, memberType.PropertyTypes.Count()); + Assert.AreEqual(3 + (stubs.Count * 2), memberType.PropertyTypes.Count()); } } [Test] public void Built_In_Member_Type_Properties_Are_Automatically_Added_When_Creating() { - var stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + Dictionary stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); @@ -311,12 +305,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Built_In_Member_Type_Properties_Missing_Are_Automatically_Added_When_Creating() { - var stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + Dictionary stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); @@ -342,24 +336,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - //This is to show that new properties are created for each member type - there was a bug before + // This is to show that new properties are created for each member type - there was a bug before // that was reusing the same properties with the same Ids between member types [Test] public void Built_In_Member_Type_Properties_Are_Not_Reused_For_Different_Member_Types() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType1 = MemberTypeBuilder.CreateSimpleMemberType(); IMemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType("test2"); repository.Save(memberType1); repository.Save(memberType2); - - var m1Ids = memberType1.PropertyTypes.Select(x => x.Id).ToArray(); - var m2Ids = memberType2.PropertyTypes.Select(x => x.Id).ToArray(); + int[] m1Ids = memberType1.PropertyTypes.Select(x => x.Id).ToArray(); + int[] m2Ids = memberType2.PropertyTypes.Select(x => x.Id).ToArray(); Assert.IsFalse(m1Ids.Any(m2Ids.Contains)); } @@ -369,21 +362,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Delete_MemberType() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + MemberTypeRepository repository = CreateRepository(provider); // Act IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); - - var contentType2 = repository.Get(memberType.Id); + IMemberType contentType2 = repository.Get(memberType.Id); repository.Delete(contentType2); - - var exists = repository.Exists(memberType.Id); + bool exists = repository.Exists(memberType.Id); // Assert Assert.That(exists, Is.False); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs index f784390ced..c15a858218 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs @@ -1,9 +1,14 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.Dtos; @@ -21,10 +26,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CreateNotification() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var node = new NodeDto // create bogus item so we can add a notification { @@ -39,11 +44,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor UniqueId = Guid.NewGuid(), UserId = Constants.Security.SuperUserId }; - var result = scope.Database.Insert(node); - var entity = Mock.Of(e => e.Id == node.NodeId); - var user = Mock.Of(e => e.Id == node.UserId); + object result = scope.Database.Insert(node); + IEntity entity = Mock.Of(e => e.Id == node.NodeId); + IUser user = Mock.Of(e => e.Id == node.UserId); - var notification = repo.CreateNotification(user, entity, "A"); + Notification notification = repo.CreateNotification(user, entity, "A"); Assert.AreEqual("A", notification.Action); Assert.AreEqual(node.NodeId, notification.EntityId); @@ -55,26 +60,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetUserNotifications() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var userDto = new UserDto { Email = "test", Login = "test", Password = "test", UserName = "test", UserLanguage = "en", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; scope.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == userDto.Id); - var userAdmin = Mock.Of(e => e.Id == Constants.Security.SuperUserId); + IUser userNew = Mock.Of(e => e.Id == userDto.Id); + IUser userAdmin = Mock.Of(e => e.Id == Constants.Security.SuperUserId); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { var node = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1," + i, SortOrder = 1, Text = "hello" + i, Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; - var result = scope.Database.Insert(node); - var entity = Mock.Of(e => e.Id == node.NodeId); - var notification = repo.CreateNotification((i%2 == 0) ? userAdmin : userNew, entity, i.ToString(CultureInfo.InvariantCulture)); + object result = scope.Database.Insert(node); + IEntity entity = Mock.Of(e => e.Id == node.NodeId); + Notification notification = repo.CreateNotification((i % 2 == 0) ? userAdmin : userNew, entity, i.ToString(CultureInfo.InvariantCulture)); } - var notifications = repo.GetUserNotifications(userAdmin); + IEnumerable notifications = repo.GetUserNotifications(userAdmin); Assert.AreEqual(5, notifications.Count()); } @@ -83,27 +88,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void GetEntityNotifications() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var node1 = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1,1", SortOrder = 1, Text = "hello1", Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; scope.Database.Insert(node1); - var entity1 = Mock.Of(e => e.Id == node1.NodeId); + IEntity entity1 = Mock.Of(e => e.Id == node1.NodeId); var node2 = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1,2", SortOrder = 1, Text = "hello2", Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; scope.Database.Insert(node2); - var entity2 = Mock.Of(e => e.Id == node2.NodeId); + IEntity entity2 = Mock.Of(e => e.Id == node2.NodeId); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { var userDto = new UserDto { Email = "test" + i, Login = "test" + i, Password = "test", UserName = "test" + i, UserLanguage = "en", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; scope.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == userDto.Id); - var notification = repo.CreateNotification(userNew, (i%2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); + IUser userNew = Mock.Of(e => e.Id == userDto.Id); + Notification notification = repo.CreateNotification(userNew, (i % 2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); } - var notifications = repo.GetEntityNotifications(entity1); + IEnumerable notifications = repo.GetEntityNotifications(entity1); Assert.AreEqual(5, notifications.Count()); } @@ -112,27 +117,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Delete_By_Entity() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var node1 = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1,1", SortOrder = 1, Text = "hello1", Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; scope.Database.Insert(node1); - var entity1 = Mock.Of(e => e.Id == node1.NodeId); + IEntity entity1 = Mock.Of(e => e.Id == node1.NodeId); var node2 = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1,2", SortOrder = 1, Text = "hello2", Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; scope.Database.Insert(node2); - var entity2 = Mock.Of(e => e.Id == node2.NodeId); + IEntity entity2 = Mock.Of(e => e.Id == node2.NodeId); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { var userDto = new UserDto { Email = "test" + i, Login = "test" + i, Password = "test", UserName = "test" + i, UserLanguage = "en", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; scope.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == userDto.Id); - var notification = repo.CreateNotification(userNew, (i%2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); + IUser userNew = Mock.Of(e => e.Id == userDto.Id); + Notification notification = repo.CreateNotification(userNew, (i % 2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); } - var delCount = repo.DeleteNotifications(entity1); + int delCount = repo.DeleteNotifications(entity1); Assert.AreEqual(5, delCount); } @@ -141,26 +146,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Delete_By_User() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new NotificationsRepository((IScopeAccessor) provider); + var repo = new NotificationsRepository((IScopeAccessor)provider); var userDto = new UserDto { Email = "test", Login = "test", Password = "test", UserName = "test", UserLanguage = "en", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; scope.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == userDto.Id); - var userAdmin = Mock.Of(e => e.Id == Constants.Security.SuperUserId); + IUser userNew = Mock.Of(e => e.Id == userDto.Id); + IUser userAdmin = Mock.Of(e => e.Id == Constants.Security.SuperUserId); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { var node = new NodeDto { CreateDate = DateTime.Now, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, Path = "-1," + i, SortOrder = 1, Text = "hello" + i, Trashed = false, UniqueId = Guid.NewGuid(), UserId = -1 }; - var result = scope.Database.Insert(node); - var entity = Mock.Of(e => e.Id == node.NodeId); - var notification = repo.CreateNotification((i%2 == 0) ? userAdmin : userNew, entity, i.ToString(CultureInfo.InvariantCulture)); + object result = scope.Database.Insert(node); + IEntity entity = Mock.Of(e => e.Id == node.NodeId); + Notification notification = repo.CreateNotification((i % 2 == 0) ? userAdmin : userNew, entity, i.ToString(CultureInfo.InvariantCulture)); } - var delCount = repo.DeleteNotifications(userAdmin); + int delCount = repo.DeleteNotifications(userAdmin); Assert.AreEqual(5, delCount); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs index ffda46ed0d..d4a90e6fcb 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs @@ -1,15 +1,20 @@ -using Microsoft.Extensions.Logging; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories.Implement; -using Umbraco.Tests.Testing; -using System; -using System.IO; -using Umbraco.Core.Hosting; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; +using Umbraco.Tests.Testing; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories { @@ -18,19 +23,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class PartialViewRepositoryTests : UmbracoIntegrationTest { private IHostingEnvironment HostingEnvironment => GetRequiredService(); + private IFileSystem _fileSystem; [SetUp] - public void SetUp() - { + public void SetUp() => _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory.CreateLogger(), HostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.PartialViews), HostingEnvironment.ToAbsolute(Constants.SystemDirectories.PartialViews)); - } [TearDown] public void TearDownFiles() { - //Delete all files - Purge((PhysicalFileSystem)_fileSystem, ""); + // Delete all files + Purge((PhysicalFileSystem)_fileSystem, string.Empty); _fileSystem = null; } @@ -38,12 +42,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void PathTests() { // unless noted otherwise, no changes / 7.2.8 - - var fileSystems = Mock.Of(); + IFileSystems fileSystems = Mock.Of(); Mock.Get(fileSystems).Setup(x => x.PartialViewsFileSystem).Returns(_fileSystem); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { var repository = new PartialViewRepository(fileSystems, IOHelper); @@ -59,7 +62,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual("path-2\\test-path-2.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); // fixed in 7.3 - 7.2.8 does not update the path Assert.AreEqual("/Views/Partials/path-2/test-path-2.cshtml", partialView.VirtualPath); - partialView = (PartialView) repository.Get("path-2/test-path-2.cshtml"); + partialView = (PartialView)repository.Get("path-2/test-path-2.cshtml"); Assert.IsNotNull(partialView); Assert.AreEqual("path-2\\test-path-2.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); Assert.AreEqual("/Views/Partials/path-2/test-path-2.cshtml", partialView.VirtualPath); @@ -70,47 +73,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual("path-2\\test-path-3.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); Assert.AreEqual("/Views/Partials/path-2/test-path-3.cshtml", partialView.VirtualPath); - partialView = (PartialView) repository.Get("path-2/test-path-3.cshtml"); + partialView = (PartialView)repository.Get("path-2/test-path-3.cshtml"); Assert.IsNotNull(partialView); Assert.AreEqual("path-2\\test-path-3.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); Assert.AreEqual("/Views/Partials/path-2/test-path-3.cshtml", partialView.VirtualPath); - partialView = (PartialView) repository.Get("path-2\\test-path-3.cshtml"); + partialView = (PartialView)repository.Get("path-2\\test-path-3.cshtml"); Assert.IsNotNull(partialView); Assert.AreEqual("path-2\\test-path-3.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); Assert.AreEqual("/Views/Partials/path-2/test-path-3.cshtml", partialView.VirtualPath); partialView = new PartialView(PartialViewType.PartialView, "\\test-path-4.cshtml") { Content = "// partialView" }; Assert.Throws(() => // fixed in 7.3 - 7.2.8 used to strip the \ - { - repository.Save(partialView); - }); + repository.Save(partialView)); - partialView = (PartialView) repository.Get("missing.cshtml"); + partialView = (PartialView)repository.Get("missing.cshtml"); Assert.IsNull(partialView); // fixed in 7.3 - 7.2.8 used to... - Assert.Throws(() => - { - partialView = (PartialView) repository.Get("\\test-path-4.cshtml"); // outside the filesystem, does not exist - }); - Assert.Throws(() => - { - partialView = (PartialView) repository.Get("../../packages.config"); // outside the filesystem, exists - }); + Assert.Throws(() => partialView = (PartialView)repository.Get("\\test-path-4.cshtml")); + Assert.Throws(() => partialView = (PartialView)repository.Get("../../packages.config")); } } - private void Purge(PhysicalFileSystem fs, string path) { - var files = fs.GetFiles(path, "*.cshtml"); - foreach (var file in files) + IEnumerable files = fs.GetFiles(path, "*.cshtml"); + foreach (string file in files) { fs.DeleteFile(file); } - var dirs = fs.GetDirectories(path); - foreach (var dir in dirs) + + IEnumerable dirs = fs.GetDirectories(path); + foreach (string dir in dirs) { Purge(fs, dir); fs.DeleteDirectory(dir); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PublicAccessRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PublicAccessRepositoryTest.cs index a02889c6ae..20c3f98f45 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PublicAccessRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PublicAccessRepositoryTest.cs @@ -1,21 +1,18 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; -using Umbraco.Core.Configuration.Models; -using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; -using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; -using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; using Content = Umbraco.Core.Models.Content; @@ -26,32 +23,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class PublicAccessRepositoryTest : UmbracoIntegrationTest { private IContentTypeRepository ContentTypeRepository => GetRequiredService(); - private DocumentRepository DocumentRepository => (DocumentRepository) GetRequiredService(); + + private DocumentRepository DocumentRepository => (DocumentRepository)GetRequiredService(); [Test] public void Can_Delete() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + }, + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - repo.Delete(entry); - entry = repo.Get(entry.Key); Assert.IsNull(entry); } @@ -60,26 +57,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Add() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + }, + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - - var found = repo.GetMany().ToArray(); + PublicAccessEntry[] found = repo.GetMany().ToArray(); Assert.AreEqual(1, found.Length); Assert.AreEqual(content[0].Id, found[0].ProtectedNodeId); @@ -100,31 +97,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Add2() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - new PublicAccessRule - { - RuleValue = "test2", - RuleType = "RoleName2" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + }, + new PublicAccessRule + { + RuleValue = "test2", + RuleType = "RoleName2" + }, + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - - var found = repo.GetMany().ToArray(); + PublicAccessEntry[] found = repo.GetMany().ToArray(); Assert.AreEqual(1, found.Length); Assert.AreEqual(content[0].Id, found[0].ProtectedNodeId); @@ -143,34 +140,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Update() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + } + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - - //re-get + // re-get entry = repo.Get(entry.Key); entry.Rules.First().RuleValue = "blah"; entry.Rules.First().RuleType = "asdf"; repo.Save(entry); - - - //re-get + // re-get entry = repo.Get(entry.Key); Assert.AreEqual("blah", entry.Rules.First().RuleValue); @@ -181,25 +176,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_By_Id() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] - { - new PublicAccessRule + PublicAccessRule[] rules = new[] { - RuleValue = "test", - RuleType = "RoleName" - }, - }); + new PublicAccessRule + { + RuleValue = "test", + RuleType = "RoleName" + } + }; + var entry = new PublicAccessEntry(content[0], content[1], content[2], rules); repo.Save(entry); - - //re-get + // re-get entry = repo.Get(entry.Key); Assert.IsNotNull(entry); @@ -209,12 +204,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_All() { - var content = CreateTestData(30).ToArray(); + IContent[] content = CreateTestData(30).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); var allEntries = new List(); for (int i = 0; i < 10; i++) @@ -228,91 +223,91 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor RuleType = "RoleName" + j }); } + var entry1 = new PublicAccessEntry(content[i], content[i + 1], content[i + 2], rules); repo.Save(entry1); allEntries.Add(entry1); } - //now remove a few rules from a few of the items and then add some more, this will put things 'out of order' which - //we need to verify our sort order is working for the relator + // now remove a few rules from a few of the items and then add some more, this will put things 'out of order' which + // we need to verify our sort order is working for the relator // FIXME: no "relator" in v8?! for (int i = 0; i < allEntries.Count; i++) { - //all the even ones + // all the even ones if (i % 2 == 0) { - var rules = allEntries[i].Rules.ToArray(); + PublicAccessRule[] rules = allEntries[i].Rules.ToArray(); for (int j = 0; j < rules.Length; j++) { - //all the even ones + // all the even ones if (j % 2 == 0) { allEntries[i].RemoveRule(rules[j]); } } + allEntries[i].AddRule("newrule" + i, "newrule" + i); repo.Save(allEntries[i]); - } } - var found = repo.GetMany().ToArray(); + PublicAccessEntry[] found = repo.GetMany().ToArray(); Assert.AreEqual(10, found.Length); - foreach (var publicAccessEntry in found) + foreach (PublicAccessEntry publicAccessEntry in found) { - var matched = allEntries.First(x => x.Key == publicAccessEntry.Key); + PublicAccessEntry matched = allEntries.First(x => x.Key == publicAccessEntry.Key); Assert.AreEqual(matched.Rules.Count(), publicAccessEntry.Rules.Count()); } } } - [Test] public void Get_All_With_Id() { - var content = CreateTestData(3).ToArray(); + IContent[] content = CreateTestData(3).ToArray(); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); + var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - var entry1 = new PublicAccessEntry(content[0], content[1], content[2], new[] + PublicAccessRule[] rules1 = new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, - }); + }; + var entry1 = new PublicAccessEntry(content[0], content[1], content[2], rules1); repo.Save(entry1); - var entry2 = new PublicAccessEntry(content[1], content[0], content[2], new[] + PublicAccessRule[] rules2 = new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, - }); + }; + var entry2 = new PublicAccessEntry(content[1], content[0], content[2], rules2); repo.Save(entry2); - - - var found = repo.GetMany(entry1.Key).ToArray(); + PublicAccessEntry[] found = repo.GetMany(entry1.Key).ToArray(); Assert.AreEqual(1, found.Count()); } } private IEnumerable CreateTestData(int count) { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var ct = ContentTypeBuilder.CreateBasicContentType("testing"); + ContentType ct = ContentTypeBuilder.CreateBasicContentType("testing"); ContentTypeRepository.Save(ct); var result = new List(); @@ -322,6 +317,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor DocumentRepository.Save(c); result.Add(c); } + scope.Complete(); return result; diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RedirectUrlRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RedirectUrlRepositoryTests.cs index 54d83172f0..cc0624a2b8 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RedirectUrlRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RedirectUrlRepositoryTests.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 Microsoft.Extensions.Logging; using NUnit.Framework; @@ -18,19 +22,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class RedirectUrlRepositoryTests : UmbracoIntegrationTest { [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); [Test] public void CanSaveAndGet() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -42,10 +43,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var rurl = repo.GetMostRecentUrl("blah"); + IRedirectUrlRepository repo = CreateRepository(provider); + IRedirectUrl rurl = repo.GetMostRecentUrl("blah"); scope.Complete(); Assert.IsNotNull(rurl); @@ -56,10 +57,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CanSaveAndGetWithCulture() { - var culture = "en"; - using (var scope = ScopeProvider.CreateScope()) + string culture = "en"; + using (IScope scope = ScopeProvider.CreateScope()) { - var repo = CreateRepository(ScopeProvider); + IRedirectUrlRepository repo = CreateRepository(ScopeProvider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -72,10 +73,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repo = CreateRepository(ScopeProvider); - var rurl = repo.GetMostRecentUrl("blah"); + IRedirectUrlRepository repo = CreateRepository(ScopeProvider); + IRedirectUrl rurl = repo.GetMostRecentUrl("blah"); scope.Complete(); Assert.IsNotNull(rurl); @@ -84,17 +85,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - [Test] public void CanSaveAndGetMostRecent() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; Assert.AreNotEqual(_textpage.Id, _otherpage.Id); - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -109,7 +109,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // and... can that happen in real life? // we don't really *care* about the IX, only supposed to make things faster... // BUT in realife we AddOrUpdate in a trx so it should be safe, always - rurl = new RedirectUrl { ContentKey = _otherpage.Key, @@ -122,10 +121,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var rurl = repo.GetMostRecentUrl("blah"); + IRedirectUrlRepository repo = CreateRepository(provider); + IRedirectUrl rurl = repo.GetMostRecentUrl("blah"); scope.Complete(); Assert.IsNotNull(rurl); @@ -136,13 +135,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CanSaveAndGetMostRecentForCulture() { - var cultureA = "en"; - var cultureB = "de"; + string cultureA = "en"; + string cultureB = "de"; Assert.AreNotEqual(_textpage.Id, _otherpage.Id); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repo = CreateRepository(ScopeProvider); + IRedirectUrlRepository repo = CreateRepository(ScopeProvider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -158,7 +157,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // and... can that happen in real life? // we don't really *care* about the IX, only supposed to make things faster... // BUT in realife we AddOrUpdate in a trx so it should be safe, always - rurl = new RedirectUrl { ContentKey = _otherpage.Key, @@ -172,10 +170,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repo = CreateRepository(ScopeProvider); - var rurl = repo.GetMostRecentUrl("blah", cultureA); + IRedirectUrlRepository repo = CreateRepository(ScopeProvider); + IRedirectUrl rurl = repo.GetMostRecentUrl("blah", cultureA); scope.Complete(); Assert.IsNotNull(rurl); @@ -184,15 +182,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } } - [Test] public void CanSaveAndGetByContent() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -204,7 +201,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); // FIXME: goes too fast and bam, errors, first is blah - rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -217,10 +213,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); - var rurls = repo.GetContentUrls(_textpage.Key).ToArray(); + IRedirectUrlRepository repo = CreateRepository(provider); + IRedirectUrl[] rurls = repo.GetContentUrls(_textpage.Key).ToArray(); scope.Complete(); Assert.AreEqual(2, rurls.Length); @@ -232,11 +228,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void CanSaveAndDelete() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); var rurl = new RedirectUrl { ContentKey = _textpage.Key, @@ -258,57 +254,59 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreNotEqual(0, rurl.Id); } - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { - var repo = CreateRepository(provider); + IRedirectUrlRepository repo = CreateRepository(provider); repo.DeleteContentUrls(_textpage.Key); scope.Complete(); - var rurls = repo.GetContentUrls(_textpage.Key); + IEnumerable rurls = repo.GetContentUrls(_textpage.Key); Assert.AreEqual(0, rurls.Count()); } } - private IRedirectUrlRepository CreateRepository(IScopeProvider provider) - { - return new RedirectUrlRepository((IScopeAccessor) provider, AppCaches, LoggerFactory.CreateLogger()); - } + private IRedirectUrlRepository CreateRepository(IScopeProvider provider) => + new RedirectUrlRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger()); - private IContent _textpage, _subpage, _otherpage, _trashed; + private IContent _textpage; + private IContent _subpage; + private IContent _otherpage; + private IContent _trashed; public void CreateTestData() { - var fileService = GetRequiredService(); - var template = TemplateBuilder.CreateTextPageTemplate(); + IFileService fileService = GetRequiredService(); + Template template = TemplateBuilder.CreateTextPageTemplate(); fileService.SaveTemplate(template); // else, FK violation on contentType! - var contentService = GetRequiredService(); - var contentTypeService = GetRequiredService(); - //Create and Save ContentType "umbTextpage" -> (NodeDto.NodeIdSeed) - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); + IContentService contentService = GetRequiredService(); + IContentTypeService contentTypeService = GetRequiredService(); + + // Create and Save ContentType "umbTextpage" -> (NodeDto.NodeIdSeed) + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); contentType.Key = Guid.NewGuid(); contentTypeService.Save(contentType); - //Create and Save Content "Homepage" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 1) + // Create and Save Content "Homepage" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 1) _textpage = ContentBuilder.CreateSimpleContent(contentType); _textpage.Key = Guid.NewGuid(); contentService.Save(_textpage); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 2) + // Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 2) _subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 1", _textpage.Id); _subpage.Key = Guid.NewGuid(); contentService.Save(_subpage); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 3) + // Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 3) _otherpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 2", _textpage.Id); _otherpage.Key = Guid.NewGuid(); contentService.Save(_otherpage); - //Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 4) + // Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 4) _trashed = ContentBuilder.CreateSimpleContent(contentType, "Text Page Deleted", -20); _trashed.Key = Guid.NewGuid(); - ((Content) _trashed).Trashed = true; + ((Content)_trashed).Trashed = true; contentService.Save(_trashed); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationRepositoryTest.cs index b73af3fdfc..cccae431a7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationRepositoryTest.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Linq; @@ -8,6 +11,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; @@ -48,10 +52,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IFileService FileService => GetRequiredService(); [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); private RelationRepository CreateRepository(IScopeProvider provider, out RelationTypeRepository relationTypeRepository) { @@ -72,7 +73,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var relation = new Relation(_textpage.Id, _subpage.Id, relationType); repository.Save(relation); - // Assert Assert.That(relation, Is.Not.Null); Assert.That(relation.HasIdentity, Is.True); @@ -92,7 +92,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor relation.Comment = "This relation has been updated"; repository.Save(relation); - IRelation relationUpdated = repository.Get(1); // Assert @@ -114,8 +113,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor IRelation relation = repository.Get(2); repository.Delete(relation); - - var exists = repository.Exists(2); + bool exists = repository.Exists(2); // Assert Assert.That(exists, Is.False); @@ -187,10 +185,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (IScope scope = ScopeProvider.CreateScope()) { - RelationRepository repository = CreateRepository(ScopeProvider, out var relationTypeRepository); + RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository relationTypeRepository); // Get parent entities for child id - var parents = repository.GetPagedParentEntitiesByChildId(createdMedia[0].Id, 0, 11, out var totalRecords).ToList(); + var parents = repository.GetPagedParentEntitiesByChildId(createdMedia[0].Id, 0, 11, out long totalRecords).ToList(); Assert.AreEqual(6, totalRecords); Assert.AreEqual(6, parents.Count); @@ -232,10 +230,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (IScope scope = ScopeProvider.CreateScope()) { - RelationRepository repository = CreateRepository(ScopeProvider, out var relationTypeRepository); + RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository relationTypeRepository); // Get parent entities for child id - var parents = repository.GetPagedParentEntitiesByChildId(media.Id, 0, 10, out var totalRecords).ToList(); + var parents = repository.GetPagedParentEntitiesByChildId(media.Id, 0, 10, out long totalRecords).ToList(); Assert.AreEqual(1, totalRecords); Assert.AreEqual(1, parents.Count); @@ -249,14 +247,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Get_Paged_Child_Entities_By_Parent_Id() { - CreateTestDataForPagingTests(out var createdContent, out var createdMembers, out _); + CreateTestDataForPagingTests(out List createdContent, out List createdMembers, out _); using (IScope scope = ScopeProvider.CreateScope()) { RelationRepository repository = CreateRepository(ScopeProvider, out _); // Get parent entities for child id - var parents = repository.GetPagedChildEntitiesByParentId(createdContent[0].Id, 0, 6, out var totalRecords).ToList(); + var parents = repository.GetPagedChildEntitiesByParentId(createdContent[0].Id, 0, 6, out long totalRecords).ToList(); Assert.AreEqual(3, totalRecords); Assert.AreEqual(3, parents.Count); @@ -293,7 +291,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor ContentTypeService.Save(contentType); for (int i = 0; i < 3; i++) { - var c1 = ContentBuilder.CreateBasicContent(contentType); + Content c1 = ContentBuilder.CreateBasicContent(contentType); ContentService.Save(c1); createdContent.Add(c1); } @@ -340,13 +338,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_RelationRepository() { // Arrange - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); + RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); // Act - var exists = repository.Exists(2); - var doesntExist = repository.Exists(5); + bool exists = repository.Exists(2); + bool doesntExist = repository.Exists(5); // Assert Assert.That(exists, Is.True); @@ -358,12 +356,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_RelationRepository() { // Arrange - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); + RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); // Act - var query = scope.SqlContext.Query().Where(x => x.ParentId == _textpage.Id); + IQuery query = scope.SqlContext.Query().Where(x => x.ParentId == _textpage.Id); int count = repository.Count(query); // Assert @@ -380,7 +378,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor RelationRepository repository = CreateRepository(ScopeProvider, out RelationTypeRepository repositoryType); // Act - global::Umbraco.Core.Persistence.Querying.IQuery query = scope.SqlContext.Query().Where(x => x.RelationTypeId == _relateContent.Id); + IQuery query = scope.SqlContext.Query().Where(x => x.RelationTypeId == _relateContent.Id); IEnumerable relations = repository.Get(query); // Assert @@ -403,8 +401,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor ContentService.Delete(content, 0); // Act - var shouldntExist = repository.Exists(1); - var shouldExist = repository.Exists(2); + bool shouldntExist = repository.Exists(1); + bool shouldExist = repository.Exists(2); // Assert Assert.That(shouldntExist, Is.False); @@ -440,6 +438,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); + // Create and Save ContentType "umbTextpage" -> (NodeDto.NodeIdSeed) _contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationTypeRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationTypeRepositoryTest.cs index 8d436eeeed..8c28fad0de 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationTypeRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/RelationTypeRepositoryTest.cs @@ -1,9 +1,14 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Models; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; @@ -16,24 +21,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class RelationTypeRepositoryTest : UmbracoIntegrationTest { [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); - private RelationTypeRepository CreateRepository(IScopeProvider provider) - { - return new RelationTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); - } + private RelationTypeRepository CreateRepository(IScopeProvider provider) => + new RelationTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); [Test] public void Can_Perform_Add_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act var relateMemberToContent = new RelationType("Relate Member to Content", "relateMemberToContent", true, Constants.ObjectTypes.Member, Constants.ObjectTypes.Document); @@ -50,18 +50,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationType = repository.Get(3); - relationType.Alias = relationType.Alias + "Updated"; - relationType.Name = relationType.Name + " Updated"; + IRelationType relationType = repository.Get(3); + relationType.Alias += "Updated"; + relationType.Name += " Updated"; repository.Save(relationType); - var relationTypeUpdated = repository.Get(3); + IRelationType relationTypeUpdated = repository.Get(3); // Assert Assert.That(relationTypeUpdated, Is.Not.Null); @@ -75,16 +75,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationType = repository.Get(3); + IRelationType relationType = repository.Get(3); repository.Delete(relationType); - var exists = repository.Exists(3); + bool exists = repository.Exists(3); // Assert Assert.That(exists, Is.False); @@ -95,13 +95,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationType = repository.Get(8); + IRelationType relationType = repository.Get(8); // Assert Assert.That(relationType, Is.Not.Null); @@ -118,13 +118,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationTypes = repository.GetMany(); + IEnumerable relationTypes = repository.GetMany(); // Assert Assert.That(relationTypes, Is.Not.Null); @@ -138,13 +138,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_With_Params_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var relationTypes = repository.GetMany(2, 3); + IEnumerable relationTypes = repository.GetMany(2, 3); // Assert Assert.That(relationTypes, Is.Not.Null); @@ -158,14 +158,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var exists = repository.Exists(3); - var doesntExist = repository.Exists(9); + bool exists = repository.Exists(3); + bool doesntExist = repository.Exists(9); // Assert Assert.That(exists, Is.True); @@ -177,13 +177,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var query = scope.SqlContext.Query().Where(x => x.Alias.StartsWith("relate")); + IQuery query = scope.SqlContext.Query().Where(x => x.Alias.StartsWith("relate")); int count = repository.Count(query); // Assert @@ -195,15 +195,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_RelationTypeRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + RelationTypeRepository repository = CreateRepository(provider); // Act - var childObjType = Constants.ObjectTypes.DocumentType; - var query = scope.SqlContext.Query().Where(x => x.ChildObjectType == childObjType); - var result = repository.Get(query); + System.Guid childObjType = Constants.ObjectTypes.DocumentType; + IQuery query = scope.SqlContext.Query().Where(x => x.ChildObjectType == childObjType); + IEnumerable result = repository.Get(query); // Assert Assert.That(result, Is.Not.Null); @@ -219,14 +219,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var relateContentType = new RelationType("Relate ContentType on Copy", "relateContentTypeOnCopy", true, Constants.ObjectTypes.DocumentType, Constants.ObjectTypes.DocumentType); var relateContentMedia = new RelationType("Relate Content to Media", "relateContentToMedia", true, Constants.ObjectTypes.Document, Constants.ObjectTypes.Media); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = new RelationTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); + var repository = new RelationTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); - repository.Save(relateContent);//Id 2 - repository.Save(relateContentType);//Id 3 - repository.Save(relateContentMedia);//Id 4 + repository.Save(relateContent); // Id 2 + repository.Save(relateContentType); // Id 3 + repository.Save(relateContentMedia); // Id 4 scope.Complete(); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs index f9084332b7..514829a2dc 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.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; @@ -11,6 +15,7 @@ using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -29,10 +34,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void SetUpFileSystem() { _fileSystems = Mock.Of(); - var path = GlobalSettings.UmbracoScriptsPath; + string path = GlobalSettings.UmbracoScriptsPath; _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory.CreateLogger(), HostingEnvironment.MapPathWebRoot(path), HostingEnvironment.ToAbsolute(path)); Mock.Get(_fileSystems).Setup(x => x.ScriptsFileSystem).Returns(_fileSystem); - using (var stream = CreateStream("Umbraco.Sys.registerNamespace(\"Umbraco.Utils\");")) + using (Stream stream = CreateStream("Umbraco.Sys.registerNamespace(\"Umbraco.Utils\");")) { _fileSystem.AddFile("test-script.js", stream); } @@ -41,8 +46,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [TearDown] public void TearDownFileSystem() { - //Delete all files - Purge(_fileSystems.ScriptsFileSystem, ""); + // Delete all files + Purge(_fileSystems.ScriptsFileSystem, string.Empty); _fileSystems = null; } @@ -56,11 +61,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Instantiate_Repository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { // Act - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Assert Assert.That(repository, Is.Not.Null); @@ -71,17 +76,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act var script = new Script("test-add-script.js") { Content = "/// " }; repository.Save(script); - - //Assert + // Assert Assert.That(_fileSystem.FileExists("test-add-script.js"), Is.True); } } @@ -90,21 +94,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act var script = new Script("test-updated-script.js") { Content = "/// " }; repository.Save(script); - script.Content = "/// "; repository.Save(script); - - var scriptUpdated = repository.Get("test-updated-script.js"); + IScript scriptUpdated = repository.Get("test-updated-script.js"); // Assert Assert.That(_fileSystem.FileExists("test-updated-script.js"), Is.True); @@ -116,18 +118,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act - var script = repository.Get("test-script.js"); + IScript script = repository.Get("test-script.js"); repository.Delete(script); - // Assert - Assert.IsFalse(repository.Exists("test-script.js")); } } @@ -136,13 +135,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act - var exists = repository.Get("test-script.js"); + IScript exists = repository.Get("test-script.js"); // Assert Assert.That(exists, Is.Not.Null); @@ -155,10 +153,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); var script = new Script("test-script1.js") { Content = "/// " }; repository.Save(script); @@ -167,9 +164,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var script3 = new Script("test-script3.js") { Content = "/// " }; repository.Save(script3); - // Act - var scripts = repository.GetMany(); + IEnumerable scripts = repository.GetMany(); // Assert Assert.That(scripts, Is.Not.Null); @@ -183,10 +179,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_With_Params_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); var script = new Script("test-script1.js") { Content = "/// " }; repository.Save(script); @@ -195,9 +190,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var script3 = new Script("test-script3.js") { Content = "/// " }; repository.Save(script3); - // Act - var scripts = repository.GetMany("test-script1.js", "test-script2.js"); + IEnumerable scripts = repository.GetMany("test-script1.js", "test-script2.js"); // Assert Assert.That(scripts, Is.Not.Null); @@ -211,13 +205,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_ScriptRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); // Act - var exists = repository.Exists("test-script.js"); + bool exists = repository.Exists("test-script.js"); // Assert Assert.That(exists, Is.True); @@ -230,23 +223,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor const string content = "/// "; // Arrange - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); IScript script = new Script("test-move-script.js") { Content = content }; repository.Save(script); - // Act script = repository.Get("test-move-script.js"); script.Path = "moved/test-move-script.js"; repository.Save(script); - - var existsOld = repository.Exists("test-move-script.js"); - var existsNew = repository.Exists("moved/test-move-script.js"); + bool existsOld = repository.Exists("test-move-script.js"); + bool existsNew = repository.Exists("moved/test-move-script.js"); script = repository.Get("moved/test-move-script.js"); @@ -262,11 +252,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void PathTests() { // unless noted otherwise, no changes / 7.2.8 - - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IScriptRepository repository = CreateRepository(); IScript script = new Script("test-path-1.js") { Content = "// script" }; repository.Save(script); @@ -275,7 +263,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.AreEqual("test-path-1.js", script.Path); Assert.AreEqual("/scripts/test-path-1.js", script.VirtualPath); - //ensure you can prefix the same path as the root path name + // ensure you can prefix the same path as the root path name script = new Script("scripts/path-2/test-path-2.js") { Content = "// script" }; repository.Save(script); @@ -287,7 +275,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(script); Assert.IsTrue(_fileSystem.FileExists("path-2/test-path-2.js")); - Assert.AreEqual("path-2\\test-path-2.js".Replace("\\", $"{Path.DirectorySeparatorChar}"), script.Path);// fixed in 7.3 - 7.2.8 does not update the path + Assert.AreEqual("path-2\\test-path-2.js".Replace("\\", $"{Path.DirectorySeparatorChar}"), script.Path); // fixed in 7.3 - 7.2.8 does not update the path Assert.AreEqual("/scripts/path-2/test-path-2.js", script.VirtualPath); script = repository.Get("path-2/test-path-2.js"); @@ -314,34 +302,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor script = new Script("\\test-path-4.js") { Content = "// script" }; Assert.Throws(() => // fixed in 7.3 - 7.2.8 used to strip the \ - { - repository.Save(script); - }); + repository.Save(script)); script = repository.Get("missing.js"); Assert.IsNull(script); // fixed in 7.3 - 7.2.8 used to... - Assert.Throws(() => - { - script = repository.Get("\\test-path-4.js"); // outside the filesystem, does not exist - }); - Assert.Throws(() => - { - script = repository.Get("../packages.config"); // outside the filesystem, exists - }); + Assert.Throws(() => script = repository.Get("\\test-path-4.js")); + Assert.Throws(() => script = repository.Get("../packages.config")); } } private void Purge(IFileSystem fs, string path) { - var files = fs.GetFiles(path, "*.js"); - foreach (var file in files) + IEnumerable files = fs.GetFiles(path, "*.js"); + foreach (string file in files) { fs.DeleteFile(file); } - var dirs = fs.GetDirectories(path); - foreach (var dir in dirs) + + IEnumerable dirs = fs.GetDirectories(path); + foreach (string dir in dirs) { Purge(fs, dir); fs.DeleteDirectory(dir); @@ -351,9 +332,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor protected Stream CreateStream(string contents = null) { if (string.IsNullOrEmpty(contents)) + { contents = "/* test */"; + } - var bytes = Encoding.UTF8.GetBytes(contents); + byte[] bytes = Encoding.UTF8.GetBytes(contents); var stream = new MemoryStream(bytes); return stream; diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs index e5304e1e31..80226da9a5 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using Microsoft.Extensions.Logging; @@ -25,19 +29,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor CreateTestData(); } - private ServerRegistrationRepository CreateRepository(IScopeProvider provider) - { - return new ServerRegistrationRepository((IScopeAccessor) provider, LoggerFactory.CreateLogger()); - } + private ServerRegistrationRepository CreateRepository(IScopeProvider provider) => + new ServerRegistrationRepository((IScopeAccessor)provider, LoggerFactory.CreateLogger()); [Test] public void Cannot_Add_Duplicate_Server_Identities() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); var server = new ServerRegistration("http://shazwazza.com", "COMPUTER1", DateTime.Now); @@ -49,12 +51,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Cannot_Update_To_Duplicate_Server_Identities() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); - var server = repository.Get(1); + IServerRegistration server = repository.Get(1); server.ServerIdentity = "COMPUTER2"; Assert.Throws(() => repository.Save(server)); @@ -65,10 +67,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Instantiate_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Assert Assert.That(repository, Is.Not.Null); @@ -79,13 +81,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var server = repository.Get(1); + IServerRegistration server = repository.Get(1); // Assert Assert.That(server, Is.Not.Null); @@ -98,13 +100,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var servers = repository.GetMany(); + IEnumerable servers = repository.GetMany(); // Assert Assert.That(servers.Count(), Is.EqualTo(3)); @@ -112,49 +114,48 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor } // queries are not supported due to in-memory caching + //// [Test] + //// public void Can_Perform_GetByQuery_On_Repository() + //// { + //// // Arrange + //// var provider = ScopeProvider; + //// using (var unitOfWork = provider.GetUnitOfWork()) + //// using (var repository = CreateRepository(provider)) + //// { + //// // Act + //// var query = Query.Builder.Where(x => x.ServerIdentity.ToUpper() == "COMPUTER3"); + //// var result = repository.GetByQuery(query); - //[Test] - //public void Can_Perform_GetByQuery_On_Repository() - //{ - // // Arrange - // var provider = ScopeProvider; - // using (var unitOfWork = provider.GetUnitOfWork()) - // using (var repository = CreateRepository(provider)) - // { - // // Act - // var query = Query.Builder.Where(x => x.ServerIdentity.ToUpper() == "COMPUTER3"); - // var result = repository.GetByQuery(query); + //// // Assert + //// Assert.AreEqual(1, result.Count()); + //// } + //// } - // // Assert - // Assert.AreEqual(1, result.Count()); - // } - //} + //// [Test] + //// public void Can_Perform_Count_On_Repository() + //// { + //// // Arrange + //// var provider = ScopeProvider; + //// using (var unitOfWork = provider.GetUnitOfWork()) + //// using (var repository = CreateRepository(provider)) + //// { + //// // Act + //// var query = Query.Builder.Where(x => x.ServerAddress.StartsWith("http://")); + //// int count = repository.Count(query); - //[Test] - //public void Can_Perform_Count_On_Repository() - //{ - // // Arrange - // var provider = ScopeProvider; - // using (var unitOfWork = provider.GetUnitOfWork()) - // using (var repository = CreateRepository(provider)) - // { - // // Act - // var query = Query.Builder.Where(x => x.ServerAddress.StartsWith("http://")); - // int count = repository.Count(query); - - // // Assert - // Assert.That(count, Is.EqualTo(2)); - // } - //} + //// // Assert + //// Assert.That(count, Is.EqualTo(2)); + //// } + //// } [Test] public void Can_Perform_Add_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act var server = new ServerRegistration("http://shazwazza.com", "COMPUTER4", DateTime.Now); @@ -162,7 +163,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Assert Assert.That(server.HasIdentity, Is.True); - Assert.That(server.Id, Is.EqualTo(4));//With 3 existing entries the Id should be 4 + Assert.That(server.Id, Is.EqualTo(4)); // With 3 existing entries the Id should be 4 } } @@ -170,19 +171,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var server = repository.Get(2); + IServerRegistration server = repository.Get(2); server.ServerAddress = "https://umbraco.com"; server.IsActive = true; repository.Save(server); - var serverUpdated = repository.Get(2); + IServerRegistration serverUpdated = repository.Get(2); // Assert Assert.That(serverUpdated, Is.Not.Null); @@ -195,17 +196,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var server = repository.Get(3); + IServerRegistration server = repository.Get(3); Assert.IsNotNull(server); repository.Delete(server); - var exists = repository.Exists(3); + bool exists = repository.Exists(3); // Assert Assert.That(exists, Is.False); @@ -216,14 +217,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); // Act - var exists = repository.Exists(3); - var doesntExist = repository.Exists(10); + bool exists = repository.Exists(3); + bool doesntExist = repository.Exists(10); // Assert Assert.That(exists, Is.True); @@ -233,10 +234,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void CreateTestData() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + ServerRegistrationRepository repository = CreateRepository(provider); repository.Save(new ServerRegistration("http://localhost", "COMPUTER1", DateTime.Now) { IsActive = true }); repository.Save(new ServerRegistration("http://www.mydomain.com", "COMPUTER2", DateTime.Now)); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/SimilarNodeNameTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/SimilarNodeNameTests.cs index 747bb542cd..215303d981 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/SimilarNodeNameTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/SimilarNodeNameTests.cs @@ -1,4 +1,6 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + using NUnit.Framework; using Umbraco.Core.Persistence.Repositories.Implement; @@ -9,39 +11,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { public void Name_Is_Suffixed() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Zulu" } }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Zulu"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Zulu"); Assert.AreEqual("Zulu (1)", res); } [Test] public void Suffixed_Name_Is_Incremented() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Zulu" }, new SimilarNodeName { Id = 2, Name = "Kilo (1)" }, new SimilarNodeName { Id = 3, Name = "Kilo" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Kilo (1)"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Kilo (1)"); Assert.AreEqual("Kilo (2)", res); } [Test] public void Lower_Number_Suffix_Is_Inserted() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Golf" }, new SimilarNodeName { Id = 2, Name = "Golf (2)" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Golf"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Golf"); Assert.AreEqual("Golf (1)", res); } @@ -50,13 +52,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [TestCase(0, "alpha", "alpha (3)")] public void Case_Is_Ignored(int nodeId, string nodeName, string expected) { - var names = new[] - { + SimilarNodeName[] names = new[] + { new SimilarNodeName { Id = 1, Name = "Alpha" }, new SimilarNodeName { Id = 2, Name = "Alpha (1)" }, new SimilarNodeName { Id = 3, Name = "Alpha (2)" }, }; - var res = SimilarNodeName.GetUniqueName(names, nodeId, nodeName); + string res = SimilarNodeName.GetUniqueName(names, nodeId, nodeName); Assert.AreEqual(expected, res); } @@ -66,7 +68,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { var names = new SimilarNodeName[] { }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Charlie"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Charlie"); Assert.AreEqual("Charlie", res); } @@ -78,7 +80,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { var names = new SimilarNodeName[] { }; - var res = SimilarNodeName.GetUniqueName(names, nodeId, nodeName); + string res = SimilarNodeName.GetUniqueName(names, nodeId, nodeName); Assert.AreEqual(expected, res); } @@ -86,14 +88,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Matching_NoedId_Causes_No_Change() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Kilo (1)" }, new SimilarNodeName { Id = 2, Name = "Yankee" }, new SimilarNodeName { Id = 3, Name = "Kilo" }, }; - var res = SimilarNodeName.GetUniqueName(names, 1, "Kilo (1)"); + string res = SimilarNodeName.GetUniqueName(names, 1, "Kilo (1)"); Assert.AreEqual("Kilo (1)", res); } @@ -103,16 +105,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { // Sequesnce is: Test, Test (1), Test (2) // Ignore: Test (1) (1) - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Alpha (2)" }, - new SimilarNodeName { Id = 2, Name = "Test" }, - new SimilarNodeName { Id = 3, Name = "Test (1)" }, - new SimilarNodeName { Id = 4, Name = "Test (2)" }, - new SimilarNodeName { Id = 5, Name = "Test (1) (1)" }, + new SimilarNodeName { Id = 2, Name = "Test" }, + new SimilarNodeName { Id = 3, Name = "Test (1)" }, + new SimilarNodeName { Id = 4, Name = "Test (2)" }, + new SimilarNodeName { Id = 5, Name = "Test (1) (1)" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Test"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Test"); Assert.AreEqual("Test (3)", res); } @@ -120,12 +122,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Matched_Name_Is_Suffixed() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Test" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Test"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Test"); Assert.AreEqual("Test (1)", res); } @@ -136,13 +138,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // "Test (1)" is treated as the "original" version of the name. // "Test (1) (1)" is the suffixed result of a copy, and therefore is incremented // Hence this test result should be the same as Suffixed_Name_Is_Incremented - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Test (1)" }, new SimilarNodeName { Id = 2, Name = "Test (1) (1)" }, }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Test (1) (1)"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Test (1) (1)"); Assert.AreEqual("Test (1) (2)", res); } @@ -150,32 +152,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Suffixed_Name_Causes_Secondary_Suffix() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 6, Name = "Alpha (1)" } }; - var res = SimilarNodeName.GetUniqueName(names, 0, "Alpha (1)"); + string res = SimilarNodeName.GetUniqueName(names, 0, "Alpha (1)"); Assert.AreEqual("Alpha (1) (1)", res); } - [TestCase("Test (0)", "Test (0) (1)")] [TestCase("Test (-1)", "Test (-1) (1)")] [TestCase("Test (1) (-1)", "Test (1) (-1) (1)")] public void NonPositive_Suffix_Is_Ignored(string suffix, string expected) { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 6, Name = suffix } }; - var res = SimilarNodeName.GetUniqueName(names, 0, suffix); + string res = SimilarNodeName.GetUniqueName(names, 0, suffix); Assert.AreEqual(expected, res); } - - /* Original Tests - Can be deleted, as new tests cover all cases */ [TestCase(0, "Charlie", "Charlie")] @@ -183,15 +182,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [TestCase(0, "Golf", "Golf (1)")] [TestCase(0, "Kilo", "Kilo (2)")] [TestCase(0, "Alpha", "Alpha (3)")] - //[TestCase(0, "Kilo (1)", "Kilo (1) (1)")] // though... we might consider "Kilo (2)" - [TestCase(0, "Kilo (1)", "Kilo (2)")] // names[] contains "Kilo" AND "Kilo (1)", which implies that result should be "Kilo (2)" + //// [TestCase(0, "Kilo (1)", "Kilo (1) (1)")] // though... we might consider "Kilo (2)" + [TestCase(0, "Kilo (1)", "Kilo (2)")] // names[] contains "Kilo" AND "Kilo (1)", which implies that result should be "Kilo (2)" [TestCase(6, "Kilo (1)", "Kilo (1)")] // because of the id [TestCase(0, "alpha", "alpha (3)")] [TestCase(0, "", " (1)")] [TestCase(0, null, " (1)")] public void Test(int nodeId, string nodeName, string expected) { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Alpha (2)" }, new SimilarNodeName { Id = 2, Name = "Alpha" }, @@ -212,7 +211,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Explicit("This test fails! We need to fix up the logic")] public void TestMany() { - var names = new[] + SimilarNodeName[] names = new[] { new SimilarNodeName { Id = 1, Name = "Alpha (2)" }, new SimilarNodeName { Id = 2, Name = "Test" }, @@ -221,7 +220,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor new SimilarNodeName { Id = 22, Name = "Test (1) (1)" }, }; - //fixme - this will yield "Test (2)" which is already in use + // fixme - this will yield "Test (2)" which is already in use Assert.AreEqual("Test (3)", SimilarNodeName.GetUniqueName(names, 0, "Test")); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs index b4b8316f83..e142c2a1fa 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs @@ -1,4 +1,8 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; @@ -25,25 +29,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IFileSystems _fileSystems; private IFileSystem _fileSystem; - private IIOHelper IOHelper => GetRequiredService(); private IHostingEnvironment HostingEnvironment => GetRequiredService(); [SetUp] public void SetUpFileSystem() { _fileSystems = Mock.Of(); - var path = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoCssPath); + string path = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoCssPath); _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService>(), path, "/css"); Mock.Get(_fileSystems).Setup(x => x.StylesheetsFileSystem).Returns(_fileSystem); - var stream = CreateStream("body {background:#EE7600; color:#FFF;}"); + Stream stream = CreateStream("body {background:#EE7600; color:#FFF;}"); _fileSystem.AddFile("styles.css", stream); } [TearDown] public void TearDownFileSystem() { - //Delete all files - Purge((PhysicalFileSystem) _fileSystem, ""); + // Delete all files + Purge((PhysicalFileSystem)_fileSystem, string.Empty); _fileSystem = null; } @@ -60,8 +63,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor using (ScopeProvider.CreateScope()) { // Act - var repository = CreateRepository(); - + IStylesheetRepository repository = CreateRepository(); // Assert Assert.That(repository, Is.Not.Null); @@ -74,14 +76,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act var stylesheet = new Stylesheet("test-add.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - - //Assert + // Assert Assert.That(_fileSystem.FileExists("test-add.css"), Is.True); } } @@ -92,21 +93,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act var stylesheet = new Stylesheet("test-update.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - - var stylesheetUpdate = repository.Get("test-update.css"); + IStylesheet stylesheetUpdate = repository.Get("test-update.css"); stylesheetUpdate.Content = "body { color:#000; }"; repository.Save(stylesheetUpdate); + IStylesheet stylesheetUpdated = repository.Get("test-update.css"); - var stylesheetUpdated = repository.Get("test-update.css"); - - //Assert + // Assert Assert.That(stylesheetUpdated, Is.Not.Null); Assert.That(stylesheetUpdated.HasIdentity, Is.True); Assert.That(stylesheetUpdated.Content, Is.EqualTo("body { color:#000; }")); @@ -119,22 +118,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act IStylesheet stylesheet = new Stylesheet("test-update.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - stylesheet.AddProperty(new StylesheetProperty("Test", "p", "font-size:2em;")); repository.Save(stylesheet); - - //re-get + // re-get stylesheet = repository.Get(stylesheet.Name); - //Assert + // Assert Assert.That(stylesheet.Content, Is.EqualTo("body { color:#000; } .bold {font-weight:bold;}\r\n\r\n/**umb_name:Test*/\r\np {\r\n\tfont-size:2em;\r\n}".Replace("\r\n", Environment.NewLine))); Assert.AreEqual(1, stylesheet.Properties.Count()); } @@ -146,13 +143,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act var stylesheet = new Stylesheet("test-update.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - stylesheet.AddProperty(new StylesheetProperty("Test", "p", "font-size:2em;")); Assert.Throws(() => stylesheet.AddProperty(new StylesheetProperty("test", "p", "font-size:2em;"))); @@ -165,17 +161,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act var stylesheet = new Stylesheet("test-delete.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - repository.Delete(stylesheet); - - //Assert + // Assert Assert.That(_fileSystem.FileExists("test-delete.css"), Is.False); } } @@ -186,16 +180,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act - var stylesheet = repository.Get("styles.css"); + IStylesheet stylesheet = repository.Get("styles.css"); // Assert Assert.That(stylesheet, Is.Not.Null); Assert.That(stylesheet.HasIdentity, Is.True); Assert.That(stylesheet.Content, Is.EqualTo("body {background:#EE7600; color:#FFF;}")); - //Assert.That(repository.ValidateStylesheet(stylesheet), Is.True); //TODO this can't be activated before we handle file systems correct + //// Assert.That(repository.ValidateStylesheet(stylesheet), Is.True); //TODO this can't be activated before we handle file systems correct } } @@ -205,14 +199,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); var stylesheet = new Stylesheet("styles-v2.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - // Act - var stylesheets = repository.GetMany(); + IEnumerable stylesheets = repository.GetMany(); // Assert Assert.That(stylesheets, Is.Not.Null); @@ -228,14 +221,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); var stylesheet = new Stylesheet("styles-v2.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); - // Act - var stylesheets = repository.GetMany("styles-v2.css", "styles.css"); + IEnumerable stylesheets = repository.GetMany("styles-v2.css", "styles.css"); // Assert Assert.That(stylesheets, Is.Not.Null); @@ -251,10 +243,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor // Arrange using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); // Act - var exists = repository.Exists("styles.css"); + bool exists = repository.Exists("styles.css"); // Assert Assert.That(exists, Is.True); @@ -265,10 +257,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void PathTests() { // unless noted otherwise, no changes / 7.2.8 - using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(); + IStylesheetRepository repository = CreateRepository(); IStylesheet stylesheet = new Stylesheet("test-path-1.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; repository.Save(stylesheet); @@ -281,7 +272,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(stylesheet); Assert.IsTrue(_fileSystem.FileExists("path-2/test-path-2.css")); - Assert.AreEqual("path-2\\test-path-2.css".Replace("\\", $"{Path.DirectorySeparatorChar}"), stylesheet.Path);// fixed in 7.3 - 7.2.8 does not update the path + Assert.AreEqual("path-2\\test-path-2.css".Replace("\\", $"{Path.DirectorySeparatorChar}"), stylesheet.Path); // fixed in 7.3 - 7.2.8 does not update the path Assert.AreEqual("/css/path-2/test-path-2.css", stylesheet.VirtualPath); stylesheet = repository.Get("path-2/test-path-2.css"); @@ -308,9 +299,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor stylesheet = new Stylesheet("\\test-path-4.css") { Content = "body { color:#000; } .bold {font-weight:bold;}" }; Assert.Throws(() => // fixed in 7.3 - 7.2.8 used to strip the \ - { - repository.Save(stylesheet); - }); + repository.Save(stylesheet)); // fixed in 7.3 - 7.2.8 used to throw stylesheet = repository.Get("missing.css"); @@ -328,13 +317,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private void Purge(PhysicalFileSystem fs, string path) { - var files = fs.GetFiles(path, "*.css"); - foreach (var file in files) + IEnumerable files = fs.GetFiles(path, "*.css"); + foreach (string file in files) { fs.DeleteFile(file); } - var dirs = fs.GetDirectories(path); - foreach (var dir in dirs) + + IEnumerable dirs = fs.GetDirectories(path); + foreach (string dir in dirs) { Purge(fs, dir); fs.DeleteDirectory(dir); @@ -344,9 +334,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor protected Stream CreateStream(string contents = null) { if (string.IsNullOrEmpty(contents)) + { contents = "/* test */"; + } - var bytes = Encoding.UTF8.GetBytes(contents); + byte[] bytes = Encoding.UTF8.GetBytes(contents); var stream = new MemoryStream(bytes); return stream; diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs index 47164a0ee0..7744173f3f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs @@ -1,4 +1,8 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core.Cache; @@ -18,18 +22,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class TagRepositoryTest : UmbracoIntegrationTest { private IFileService FileService => GetRequiredService(); + private IContentTypeRepository ContentTypeRepository => GetRequiredService(); + private IDocumentRepository DocumentRepository => GetRequiredService(); + private IMediaRepository MediaRepository => GetRequiredService(); + private IMediaTypeRepository MediaTypeRepository => GetRequiredService(); [Test] public void Can_Perform_Add_On_Repository() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); var tag = new Tag { @@ -46,10 +54,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Multiple_Adds_On_Repository() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); var tag = new Tag { @@ -76,29 +84,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Create_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + tags, + false); Assert.AreEqual(2, repository.GetTagsForEntity(content.Id).Count()); } @@ -107,38 +117,42 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Append_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"}, - }, false); + tags2, + false); Assert.AreEqual(4, repository.GetTagsForEntity(content.Id).Count()); } @@ -147,40 +161,44 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Replace_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"}, - }, true); + tags2, + true); - var result = repository.GetTagsForEntity(content.Id).ToArray(); + ITag[] result = repository.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(2, result.Length); Assert.AreEqual("tag3", result[0].Text); Assert.AreEqual("tag4", result[1].Text); @@ -190,40 +208,44 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Merge_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - }, false); + tags2, + false); - var result = repository.GetTagsForEntity(content.Id); + IEnumerable result = repository.GetTagsForEntity(content.Id); Assert.AreEqual(3, result.Count()); } } @@ -231,36 +253,39 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Clear_Tag_Relations() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); - repository.Assign( - content.Id, - contentType.PropertyTypes.First().Id, - new[] + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - }, false); + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + }; + repository.Assign( + content.Id, + contentType.PropertyTypes.First().Id, + tags, + false); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - Enumerable.Empty(), true); + Enumerable.Empty(), + true); - var result = repository.GetTagsForEntity(content.Id); + IEnumerable result = repository.GetTagsForEntity(content.Id); Assert.AreEqual(0, result.Count()); } } @@ -268,42 +293,45 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Remove_Specific_Tags_From_Property() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tagsToRemove = new[] + { + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" } + }; repository.Remove( content.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"} - }); + tagsToRemove); - var result = repository.GetTagsForEntity(content.Id).ToArray(); + ITag[] result = repository.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(2, result.Length); Assert.AreEqual("tag1", result[0].Text); Assert.AreEqual("tag4", result[1].Text); @@ -313,44 +341,48 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Content_By_Id() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content2.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - var result = repository.GetTagsForEntity(content2.Id); + IEnumerable result = repository.GetTagsForEntity(content2.Id); Assert.AreEqual(2, result.Count()); } } @@ -358,45 +390,49 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Content_By_Key() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content2.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - //get by key - var result = repository.GetTagsForEntity(content2.Key); + // get by key + IEnumerable result = repository.GetTagsForEntity(content2.Key); Assert.AreEqual(2, result.Count()); } } @@ -404,35 +440,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_All() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); - var result = repository.GetMany(); + IEnumerable result = repository.GetMany(); Assert.AreEqual(4, result.Count()); } } @@ -440,40 +478,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_All_With_Ids() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); - var tags = new[] + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - tags, false); + tags, + false); // TODO: This would be nice to be able to map the ids back but unfortunately we are not doing this - //var result = repository.GetAll(new[] {tags[0].Id, tags[1].Id, tags[2].Id}); - var all = repository.GetMany().ToArray(); + // var result = repository.GetAll(new[] {tags[0].Id, tags[1].Id, tags[2].Id}); + ITag[] all = repository.GetMany().ToArray(); - var result = repository.GetMany(all[0].Id, all[1].Id, all[2].Id); + IEnumerable result = repository.GetMany(all[0].Id, all[1].Id, all[2].Id); Assert.AreEqual(3, result.Count()); } } @@ -481,44 +520,48 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Content_For_Group() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test1" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test1"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content2.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - var result = repository.GetTagsForEntity(content1.Id, "test1"); + IEnumerable result = repository.GetTagsForEntity(content1.Id, "test1"); Assert.AreEqual(2, result.Count()); } } @@ -526,43 +569,47 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Property_By_Id() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias).ToArray(); - var result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias).ToArray(); + ITag[] result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias).ToArray(); + ITag[] result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias).ToArray(); Assert.AreEqual(4, result1.Length); Assert.AreEqual(2, result2.Length); } @@ -571,43 +618,47 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Property_By_Key() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.First().Alias).ToArray(); - var result2 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.Last().Alias).ToArray(); + ITag[] result1 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.First().Alias).ToArray(); + ITag[] result2 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.Last().Alias).ToArray(); Assert.AreEqual(4, result1.Length); Assert.AreEqual(2, result2.Length); } @@ -616,43 +667,47 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Property_For_Group() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test1" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test1"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias, "test1").ToArray(); - var result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias, "test1").ToArray(); + ITag[] result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias, "test1").ToArray(); + ITag[] result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias, "test1").ToArray(); Assert.AreEqual(2, result1.Length); Assert.AreEqual(1, result2.Length); @@ -662,49 +717,53 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Entity_Type() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); MediaTypeRepository.Save(mediaType); - var media1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaRepository.Save(media1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag4", Group = "test1" } + }; repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag4", Group = "test1"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content).ToArray(); - var result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media).ToArray(); - var result3 = repository.GetTagsForEntityType(TaggableObjectTypes.All).ToArray(); + ITag[] result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content).ToArray(); + ITag[] result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media).ToArray(); + ITag[] result3 = repository.GetTagsForEntityType(TaggableObjectTypes.All).ToArray(); Assert.AreEqual(3, result1.Length); Assert.AreEqual(2, result2.Length); @@ -719,49 +778,53 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tags_For_Entity_Type_For_Group() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); MediaTypeRepository.Save(mediaType); - var media1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaRepository.Save(media1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test1" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test1"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" } + }; repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"} - }, false); + tags2, + false); - var result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content, "test1").ToArray(); - var result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media, "test1").ToArray(); + ITag[] result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content, "test1").ToArray(); + ITag[] result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media, "test1").ToArray(); Assert.AreEqual(2, result1.Length); Assert.AreEqual(1, result2.Length); @@ -771,31 +834,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Cascade_Deletes_Tag_Relations() { - var provider = ScopeProvider; - using (var scope = ScopeProvider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test" }, + new Tag { Text = "tag3", Group = "test" }, + new Tag { Text = "tag4", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test"}, - new Tag {Text = "tag3", Group = "test"}, - new Tag {Text = "tag4", Group = "test"} - }, false); + tags, + false); DocumentRepository.Delete(content1); @@ -808,79 +873,91 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tagged_Entities_For_Tag_Group() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - var mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); MediaTypeRepository.Save(mediaType); - var media1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaRepository.Save(media1); - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag {Text = "tag1", Group = "test"}, + new Tag {Text = "tag2", Group = "test1"}, + new Tag {Text = "tag3", Group = "test"} + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" } + }; repository.Assign( content2.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"} - }, false); + tags2, + false); + Tag[] tags3 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" } + }; repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"} - }, false); + tags3, + false); - var contentTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test").ToArray(); - //there are two content items tagged against the 'test' group + TaggedEntity[] contentTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test").ToArray(); + + // there are two content items tagged against the 'test' group Assert.AreEqual(2, contentTestIds.Length); - //there are a total of two property types tagged against the 'test' group + + // there are a total of two property types tagged against the 'test' group Assert.AreEqual(2, contentTestIds.SelectMany(x => x.TaggedProperties).Count()); - //there are a total of 2 tags tagged against the 'test' group + + // there are a total of 2 tags tagged against the 'test' group Assert.AreEqual(2, contentTestIds.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); - var contentTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test1").ToArray(); - //there are two content items tagged against the 'test1' group + TaggedEntity[] contentTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test1").ToArray(); + + // there are two content items tagged against the 'test1' group Assert.AreEqual(2, contentTest1Ids.Length); - //there are a total of two property types tagged against the 'test1' group + + // there are a total of two property types tagged against the 'test1' group Assert.AreEqual(2, contentTest1Ids.SelectMany(x => x.TaggedProperties).Count()); - //there are a total of 1 tags tagged against the 'test1' group + + // there are a total of 1 tags tagged against the 'test1' group Assert.AreEqual(1, contentTest1Ids.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); - var mediaTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test"); + IEnumerable mediaTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test"); Assert.AreEqual(1, mediaTestIds.Count()); - var mediaTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test1"); + IEnumerable mediaTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test1"); Assert.AreEqual(1, mediaTest1Ids.Count()); } } @@ -888,86 +965,92 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Tagged_Entities_For_Tag() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (ScopeProvider.CreateScope()) { - //create data to relate to + // create data to relate to // We have to create and save a template, otherwise we get an FK violation on contentType. - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id); ContentTypeRepository.Save(contentType); - - var content1 = ContentBuilder.CreateSimpleContent(contentType); + Content content1 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content1); - - var content2 = ContentBuilder.CreateSimpleContent(contentType); + Content content2 = ContentBuilder.CreateSimpleContent(contentType); DocumentRepository.Save(content2); - - var mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("image2"); MediaTypeRepository.Save(mediaType); - var media1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaRepository.Save(media1); - - var repository = CreateRepository(provider); + TagRepository repository = CreateRepository(provider); + Tag[] tags = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + new Tag { Text = "tag3", Group = "test" } + }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - new Tag {Text = "tag3", Group = "test"} - }, false); + tags, + false); + Tag[] tags2 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" }, + }; repository.Assign( content2.Id, contentType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"}, - }, false); + tags2, + false); + Tag[] tags3 = new[] + { + new Tag { Text = "tag1", Group = "test" }, + new Tag { Text = "tag2", Group = "test1" } + }; repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, - new[] - { - new Tag {Text = "tag1", Group = "test"}, - new Tag {Text = "tag2", Group = "test1"} - }, false); + tags3, + false); - var contentTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag1").ToArray(); - //there are two content items tagged against the 'tag1' tag + TaggedEntity[] contentTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag1").ToArray(); + + // there are two content items tagged against the 'tag1' tag Assert.AreEqual(2, contentTestIds.Length); - //there are a total of two property types tagged against the 'tag1' tag + + // there are a total of two property types tagged against the 'tag1' tag Assert.AreEqual(2, contentTestIds.SelectMany(x => x.TaggedProperties).Count()); - //there are a total of 1 tags since we're only looking against one tag + + // there are a total of 1 tags since we're only looking against one tag Assert.AreEqual(1, contentTestIds.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); - var contentTest1Ids = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag3").ToArray(); - //there are 1 content items tagged against the 'tag3' tag + TaggedEntity[] contentTest1Ids = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag3").ToArray(); + + // there are 1 content items tagged against the 'tag3' tag Assert.AreEqual(1, contentTest1Ids.Length); - //there are a total of two property types tagged against the 'tag3' tag + + // there are a total of two property types tagged against the 'tag3' tag Assert.AreEqual(1, contentTest1Ids.SelectMany(x => x.TaggedProperties).Count()); - //there are a total of 1 tags since we're only looking against one tag + + // there are a total of 1 tags since we're only looking against one tag Assert.AreEqual(1, contentTest1Ids.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); - var mediaTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Media, "tag1"); + IEnumerable mediaTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Media, "tag1"); Assert.AreEqual(1, mediaTestIds.Count()); } } - private TagRepository CreateRepository(IScopeProvider provider) - { - return new TagRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); - } + private TagRepository CreateRepository(IScopeProvider provider) => + new TagRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger()); } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TemplateRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TemplateRepositoryTest.cs index 5cab23c4c9..9780b53997 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TemplateRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TemplateRepositoryTest.cs @@ -1,10 +1,12 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; -using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; @@ -30,22 +32,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class TemplateRepositoryTest : UmbracoIntegrationTest { private IHostingEnvironment HostingEnvironment => GetRequiredService(); + private IFileSystems FileSystems => GetRequiredService(); - private ITemplateRepository CreateRepository(IScopeProvider provider) - { - return new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); - } + private ITemplateRepository CreateRepository(IScopeProvider provider) => + new TemplateRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), FileSystems, IOHelper, ShortStringHelper); [Test] public void Can_Instantiate_Repository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Assert Assert.That(repository, Is.Not.Null); @@ -56,18 +57,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_View() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test"); repository.Save(template); - - //Assert + // Assert Assert.That(repository.Get("test"), Is.Not.Null); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.True); } @@ -77,11 +77,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_View_With_Default_Content() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test") @@ -90,7 +90,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; repository.Save(template); - //Assert + // Assert Assert.That(repository.Get("test"), Is.Not.Null); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.True); Assert.AreEqual( @@ -103,13 +103,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_View_With_Default_Content_With_Parent() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); - //NOTE: This has to be persisted first + // NOTE: This has to be persisted first var template = new Template(ShortStringHelper, "test", "test"); repository.Save(template); @@ -118,7 +118,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor template2.SetMasterTemplate(template); repository.Save(template2); - //Assert + // Assert Assert.That(repository.Get("test2"), Is.Not.Null); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test2.cshtml"), Is.True); Assert.AreEqual( @@ -131,11 +131,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_Unique_Alias() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test") @@ -150,7 +150,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor }; repository.Save(template2); - //Assert + // Assert Assert.AreEqual("test1", template2.Alias); } } @@ -159,11 +159,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_Unique_Alias() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test") @@ -181,7 +181,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor template.Alias = "test1"; repository.Save(template); - //Assert + // Assert Assert.AreEqual("test11", template.Alias); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test11.cshtml"), Is.True); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.False); @@ -192,11 +192,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_View() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); // Act var template = new Template(ShortStringHelper, "test", "test") @@ -208,7 +208,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor template.Content += ""; repository.Save(template); - var updated = repository.Get("test"); + ITemplate updated = repository.Get("test"); // Assert Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.True); @@ -220,11 +220,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_View() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var template = new Template(ShortStringHelper, "test", "test") { @@ -233,7 +233,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(template); // Act - var templates = repository.Get("test"); + ITemplate templates = repository.Get("test"); Assert.That(FileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.True); repository.Delete(templates); @@ -247,14 +247,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_When_Assigned_To_Doc() { // Arrange - var provider = ScopeProvider; - var scopeAccessor = (IScopeAccessor) provider; - var dataTypeService = GetRequiredService(); - var fileService = GetRequiredService(); + IScopeProvider provider = ScopeProvider; + var scopeAccessor = (IScopeAccessor)provider; + IDataTypeService dataTypeService = GetRequiredService(); + IFileService fileService = GetRequiredService(); using (provider.CreateScope()) { - var templateRepository = CreateRepository(provider); + ITemplateRepository templateRepository = CreateRepository(provider); var globalSettings = new GlobalSettings(); var serializer = new JsonNetSerializer(); var tagRepository = new TagRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory.CreateLogger()); @@ -268,20 +268,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor var dataValueReferences = new DataValueReferenceFactoryCollection(Enumerable.Empty()); var contentRepo = new DocumentRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, contentTypeRepository, templateRepository, tagRepository, languageRepository, relationRepository, relationTypeRepository, propertyEditors, dataValueReferences, dataTypeService, serializer); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); fileService.SaveTemplate(template); // else, FK violation on contentType! - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage2", "Textpage", defaultTemplateId: template.Id); contentTypeRepository.Save(contentType); - var textpage = ContentBuilder.CreateSimpleContent(contentType); + Content textpage = ContentBuilder.CreateSimpleContent(contentType); contentRepo.Save(textpage); textpage.TemplateId = template.Id; contentRepo.Save(textpage); // Act - var templates = templateRepository.Get("textPage"); + ITemplate templates = templateRepository.Get("textPage"); templateRepository.Delete(templates); // Assert @@ -293,11 +293,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_Nested_Templates() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var parent = new Template(ShortStringHelper, "parent", "parent") { @@ -320,7 +320,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(baby); // Act - var templates = repository.Get("parent"); + ITemplate templates = repository.Get("parent"); repository.Delete(templates); // Assert @@ -332,18 +332,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Get_All() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); - var created = CreateHierarchy(repository).ToArray(); + ITemplate[] created = CreateHierarchy(repository).ToArray(); // Act - var all = repository.GetAll(); - var allByAlias = repository.GetAll("parent", "child2", "baby2", "notFound"); - var allById = repository.GetMany(created[0].Id, created[2].Id, created[4].Id, created[5].Id, 999999); + IEnumerable all = repository.GetAll(); + IEnumerable allByAlias = repository.GetAll("parent", "child2", "baby2", "notFound"); + IEnumerable allById = repository.GetMany(created[0].Id, created[2].Id, created[4].Id, created[5].Id, 999999); // Assert Assert.AreEqual(9, all.Count()); @@ -361,17 +361,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Get_Children() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); - var created = CreateHierarchy(repository).ToArray(); + ITemplate[] created = CreateHierarchy(repository).ToArray(); // Act - var childrenById = repository.GetChildren(created[1].Id); - var childrenByAlias = repository.GetChildren(created[1].Alias); + IEnumerable childrenById = repository.GetChildren(created[1].Id); + IEnumerable childrenByAlias = repository.GetChildren(created[1].Alias); // Assert Assert.AreEqual(2, childrenById.Count()); @@ -385,16 +385,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Get_Children_At_Root() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); CreateHierarchy(repository).ToArray(); // Act - var children = repository.GetChildren(-1); + IEnumerable children = repository.GetChildren(-1); // Assert Assert.AreEqual(1, children.Count()); @@ -406,16 +406,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Get_Descendants() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); - var created = CreateHierarchy(repository).ToArray(); + ITemplateRepository repository = CreateRepository(provider); + ITemplate[] created = CreateHierarchy(repository).ToArray(); // Act - var descendantsById = repository.GetDescendants(created[1].Id); - var descendantsByAlias = repository.GetDescendants(created[1].Alias); + IEnumerable descendantsById = repository.GetDescendants(created[1].Id); + IEnumerable descendantsByAlias = repository.GetDescendants(created[1].Alias); // Assert Assert.AreEqual(3, descendantsById.Count()); @@ -430,11 +430,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Path_Is_Set_Correctly_On_Creation() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var parent = new Template(ShortStringHelper, "parent", "parent"); var child1 = new Template(ShortStringHelper, "child1", "child1"); @@ -492,11 +492,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Path_Is_Set_Correctly_On_Update() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var parent = new Template(ShortStringHelper, "parent", "parent"); var child1 = new Template(ShortStringHelper, "child1", "child1"); @@ -519,11 +519,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(toddler1); repository.Save(toddler2); - //Act + // Act toddler2.SetMasterTemplate(child2); repository.Save(toddler2); - //Assert + // Assert Assert.AreEqual($"-1,{parent.Id},{child2.Id},{toddler2.Id}", toddler2.Path); } } @@ -532,26 +532,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Path_Is_Set_Correctly_On_Update_With_Master_Template_Removal() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + ITemplateRepository repository = CreateRepository(provider); var parent = new Template(ShortStringHelper, "parent", "parent"); - var child1 = new Template(ShortStringHelper, "child1", "child1"); - - child1.MasterTemplateAlias = parent.Alias; - child1.MasterTemplateId = new Lazy(() => parent.Id); + var child1 = new Template(ShortStringHelper, "child1", "child1") + { + MasterTemplateAlias = parent.Alias, + MasterTemplateId = new Lazy(() => parent.Id) + }; repository.Save(parent); repository.Save(child1); - //Act + // Act child1.SetMasterTemplate(null); repository.Save(child1); - //Assert + // Assert Assert.AreEqual($"-1,{child1.Id}", child1.Path); } } @@ -561,19 +562,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor { var testHelper = new TestHelper(); - //Delete all files + // Delete all files var fsViews = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory.CreateLogger(), HostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MvcViews), HostingEnvironment.ToAbsolute(Constants.SystemDirectories.MvcViews)); - var views = fsViews.GetFiles("", "*.cshtml"); - foreach (var file in views) + IEnumerable views = fsViews.GetFiles(string.Empty, "*.cshtml"); + foreach (string file in views) + { fsViews.DeleteFile(file); + } } protected Stream CreateStream(string contents = null) { if (string.IsNullOrEmpty(contents)) + { contents = "/* test */"; + } - var bytes = Encoding.UTF8.GetBytes(contents); + byte[] bytes = Encoding.UTF8.GetBytes(contents); var stream = new MemoryStream(bytes); return stream; @@ -620,7 +625,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Content = @"<%@ Master Language=""C#"" %>" }; - child1.MasterTemplateAlias = parent.Alias; child1.MasterTemplateId = new Lazy(() => parent.Id); child2.MasterTemplateAlias = parent.Alias; @@ -652,8 +656,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(baby1); repository.Save(baby2); - - return new[] {parent, child1, child2, toddler1, toddler2, toddler3, toddler4, baby1, baby2}; + return new[] { parent, child1, child2, toddler1, toddler2, toddler3, toddler4, baby1, baby2 }; } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserGroupRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserGroupRepositoryTest.cs index e67b9f9b60..72a2d073be 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserGroupRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserGroupRepositoryTest.cs @@ -1,7 +1,12 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core.Models.Membership; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; @@ -15,21 +20,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class UserGroupRepositoryTest : UmbracoIntegrationTest { - private UserGroupRepository CreateRepository(IScopeProvider provider) - { - return new UserGroupRepository((IScopeAccessor) provider, global::Umbraco.Core.Cache.AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); - } + private UserGroupRepository CreateRepository(IScopeProvider provider) => + new UserGroupRepository((IScopeAccessor)provider, global::Umbraco.Core.Cache.AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); [Test] public void Can_Perform_Add_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); // Act repository.Save(userGroup); @@ -44,13 +47,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Multiple_Adds_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup1 = UserGroupBuilder.CreateUserGroup(suffix: "1"); - var userGroup2 = UserGroupBuilder.CreateUserGroup(suffix: "2"); + UserGroup userGroup1 = UserGroupBuilder.CreateUserGroup(suffix: "1"); + UserGroup userGroup2 = UserGroupBuilder.CreateUserGroup(suffix: "2"); // Act repository.Save(userGroup1); @@ -68,17 +71,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Fresh_Entity_Is_Not_Dirty() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); repository.Save(userGroup); scope.Complete(); // Act - var resolved = repository.Get((int) userGroup.Id); + IUserGroup resolved = repository.Get((int)userGroup.Id); bool dirty = ((UserGroup)resolved).IsDirty(); // Assert @@ -90,21 +93,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Update_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); repository.Save(userGroup); // Act - var resolved = repository.Get((int) userGroup.Id); + IUserGroup resolved = repository.Get((int)userGroup.Id); resolved.Name = "New Name"; resolved.Permissions = new[] { "Z", "Y", "X" }; repository.Save(resolved); scope.Complete(); - var updatedItem = repository.Get((int) userGroup.Id); + IUserGroup updatedItem = repository.Get((int)userGroup.Id); // Assert Assert.That(updatedItem.Id, Is.EqualTo(resolved.Id)); @@ -116,23 +119,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Delete_On_UserGroupRepository() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); // Act repository.Save(userGroup); - var id = userGroup.Id; + int id = userGroup.Id; - var repository2 = new UserGroupRepository((IScopeAccessor) provider, global::Umbraco.Core.Cache.AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); + var repository2 = new UserGroupRepository((IScopeAccessor)provider, global::Umbraco.Core.Cache.AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); repository2.Delete(userGroup); scope.Complete(); - var resolved = repository2.Get((int) id); + IUserGroup resolved = repository2.Get((int)id); // Assert Assert.That(resolved, Is.Null); @@ -143,22 +146,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); repository.Save(userGroup); scope.Complete(); // Act - var resolved = repository.Get((int) userGroup.Id); + IUserGroup resolved = repository.Get((int)userGroup.Id); // Assert Assert.That(resolved.Id, Is.EqualTo(userGroup.Id)); - //Assert.That(resolved.CreateDate, Is.GreaterThan(DateTime.MinValue)); - //Assert.That(resolved.UpdateDate, Is.GreaterThan(DateTime.MinValue)); + //// Assert.That(resolved.CreateDate, Is.GreaterThan(DateTime.MinValue)); + //// Assert.That(resolved.UpdateDate, Is.GreaterThan(DateTime.MinValue)); Assert.That(resolved.Name, Is.EqualTo(userGroup.Name)); Assert.That(resolved.Alias, Is.EqualTo(userGroup.Alias)); Assert.That(resolved.Permissions, Is.EqualTo(userGroup.Permissions)); @@ -169,16 +172,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); CreateAndCommitMultipleUserGroups(repository); // Act - var query = scope.SqlContext.Query().Where(x => x.Alias == "testGroup1"); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Alias == "testGroup1"); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.GreaterThanOrEqualTo(1)); @@ -189,15 +192,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_By_Param_Ids_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] userGroups = CreateAndCommitMultipleUserGroups(repository); // Act - var result = repository.GetMany(userGroups[0].Id, userGroups[1].Id); + IEnumerable result = repository.GetMany(userGroups[0].Id, userGroups[1].Id); // Assert Assert.That(result, Is.Not.Null); @@ -210,15 +213,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); CreateAndCommitMultipleUserGroups(repository); // Act - var result = repository.GetMany(); + IEnumerable result = repository.GetMany(); // Assert Assert.That(result, Is.Not.Null); @@ -231,15 +234,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] userGroups = CreateAndCommitMultipleUserGroups(repository); // Act - var exists = repository.Exists(userGroups[0].Id); + bool exists = repository.Exists(userGroups[0].Id); // Assert Assert.That(exists, Is.True); @@ -250,16 +253,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_UserGroupRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var userGroups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] userGroups = CreateAndCommitMultipleUserGroups(repository); // Act - var query = scope.SqlContext.Query().Where(x => x.Alias == "testGroup1" || x.Alias == "testGroup2"); - var result = repository.Count(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Alias == "testGroup1" || x.Alias == "testGroup2"); + int result = repository.Count(query); // Assert Assert.That(result, Is.GreaterThanOrEqualTo(2)); @@ -270,16 +273,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Remove_Section_For_Group() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var groups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] groups = CreateAndCommitMultipleUserGroups(repository); // Act - //add and remove a few times, this tests the internal collection + // add and remove a few times, this tests the internal collection groups[0].RemoveAllowedSection("content"); groups[0].RemoveAllowedSection("content"); groups[0].AddAllowedSection("content"); @@ -293,7 +296,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); // Assert - var result = repository.GetMany((int)groups[0].Id, (int)groups[1].Id).ToArray(); + IUserGroup[] result = repository.GetMany((int)groups[0].Id, (int)groups[1].Id).ToArray(); Assert.AreEqual(1, result[0].AllowedSections.Count()); Assert.AreEqual("media", result[0].AllowedSections.First()); Assert.AreEqual(1, result[1].AllowedSections.Count()); @@ -305,16 +308,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Add_Section_ForGroup() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var groups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] groups = CreateAndCommitMultipleUserGroups(repository); // Act - //add and remove a few times, this tests the internal collection + // add and remove a few times, this tests the internal collection groups[0].ClearAllowedSections(); groups[0].AddAllowedSection("content"); groups[0].AddAllowedSection("media"); @@ -322,7 +325,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor groups[0].AddAllowedSection("content"); groups[0].AddAllowedSection("settings"); - //add the same even though it's already there + // add the same even though it's already there groups[0].AddAllowedSection("content"); groups[1].ClearAllowedSections(); @@ -335,11 +338,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor repository.Save(groups[2]); scope.Complete(); - for (var i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) + { Assert.IsNotNull(repository.Get(groups[i].Id)); + } // Assert - var result = repository.GetMany(groups[0].Id, groups[1].Id, groups[2].Id).ToArray(); + IUserGroup[] result = repository.GetMany(groups[0].Id, groups[1].Id, groups[2].Id).ToArray(); Assert.AreEqual(3, result.Length); Assert.AreEqual(3, result[0].AllowedSections.Count()); @@ -356,15 +361,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Update_Section_For_Group() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var groups = CreateAndCommitMultipleUserGroups(repository); + IUserGroup[] groups = CreateAndCommitMultipleUserGroups(repository); // Act - groups[0].RemoveAllowedSection("content"); groups[0].AddAllowedSection("settings"); @@ -372,7 +376,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Complete(); // Assert - var result = repository.Get(groups[0].Id); + IUserGroup result = repository.Get(groups[0].Id); Assert.AreEqual(2, result.AllowedSections.Count()); Assert.IsTrue(result.AllowedSections.Contains("settings")); Assert.IsTrue(result.AllowedSections.Contains("media")); @@ -383,25 +387,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Get_Groups_Assigned_To_Section() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserGroupRepository repository = CreateRepository(provider); - var user1 = UserGroupBuilder.CreateUserGroup(suffix: "1", allowedSections: new[] { "test1" }); - var user2 = UserGroupBuilder.CreateUserGroup(suffix: "2", allowedSections: new[] { "test2" }); - var user3 = UserGroupBuilder.CreateUserGroup(suffix: "3", allowedSections: new[] { "test1" }); + UserGroup user1 = UserGroupBuilder.CreateUserGroup(suffix: "1", allowedSections: new[] { "test1" }); + UserGroup user2 = UserGroupBuilder.CreateUserGroup(suffix: "2", allowedSections: new[] { "test2" }); + UserGroup user3 = UserGroupBuilder.CreateUserGroup(suffix: "3", allowedSections: new[] { "test1" }); repository.Save(user1); repository.Save(user2); repository.Save(user3); scope.Complete(); // Act - var groups = repository.GetGroupsAssignedToSection("test1"); + IEnumerable groups = repository.GetGroupsAssignedToSection("test1"); // Assert Assert.AreEqual(2, groups.Count()); - var names = groups.Select(x => x.Name).ToArray(); + string[] names = groups.Select(x => x.Name).ToArray(); Assert.IsTrue(names.Contains("Test Group1")); Assert.IsFalse(names.Contains("Test Group2")); Assert.IsTrue(names.Contains("Test Group3")); @@ -410,9 +414,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IUserGroup[] CreateAndCommitMultipleUserGroups(IUserGroupRepository repository) { - var userGroup1 = UserGroupBuilder.CreateUserGroup(suffix: "1"); - var userGroup2 = UserGroupBuilder.CreateUserGroup(suffix: "2"); - var userGroup3 = UserGroupBuilder.CreateUserGroup(suffix: "3"); + UserGroup userGroup1 = UserGroupBuilder.CreateUserGroup(suffix: "1"); + UserGroup userGroup2 = UserGroupBuilder.CreateUserGroup(suffix: "2"); + UserGroup userGroup3 = UserGroupBuilder.CreateUserGroup(suffix: "3"); repository.Save(userGroup1); repository.Save(userGroup2); repository.Save(userGroup3); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs index ba773716fd..a5164e0244 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs @@ -1,16 +1,22 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; +using System.Collections.Generic; using System.Linq; -using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Mappers; +using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; @@ -27,20 +33,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public class UserRepositoryTest : UmbracoIntegrationTest { private IDocumentRepository DocumentRepository => GetRequiredService(); + private IContentTypeRepository ContentTypeRepository => GetRequiredService(); + private IMediaTypeRepository MediaTypeRepository => GetRequiredService(); + private IMediaRepository MediaRepository => GetRequiredService(); private UserRepository CreateRepository(IScopeProvider provider) { - var accessor = (IScopeAccessor) provider; + var accessor = (IScopeAccessor)provider; var repository = new UserRepository(accessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), Mappers, Options.Create(GlobalSettings), Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer()); return repository; } private UserGroupRepository CreateUserGroupRepository(IScopeProvider provider) { - var accessor = (IScopeAccessor) provider; + var accessor = (IScopeAccessor)provider; return new UserGroupRepository(accessor, AppCaches.Disabled, LoggerFactory.CreateLogger(), LoggerFactory, ShortStringHelper); } @@ -48,17 +57,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Add_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var user = UserBuilderInstance.Build(); + User user = UserBuilderInstance.Build(); // Act repository.Save(user); - // Assert Assert.That(user.HasIdentity, Is.True); } @@ -68,20 +76,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Multiple_Adds_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var user1 = UserBuilderInstance.WithSuffix("1").Build(); - var use2 = UserBuilderInstance.WithSuffix("2").Build(); + User user1 = UserBuilderInstance.WithSuffix("1").Build(); + User use2 = UserBuilderInstance.WithSuffix("2").Build(); // Act repository.Save(user1); repository.Save(use2); - // Assert Assert.That(user1.HasIdentity, Is.True); Assert.That(use2.HasIdentity, Is.True); @@ -92,17 +99,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Verify_Fresh_Entity_Is_Not_Dirty() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var user = UserBuilderInstance.WithoutIdentity().Build(); + User user = UserBuilderInstance.WithoutIdentity().Build(); repository.Save(user); - // Act - var resolved = repository.Get((int)user.Id); + IUser resolved = repository.Get((int)user.Id); bool dirty = ((User)resolved).IsDirty(); // Assert @@ -114,24 +120,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Delete_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var user = UserBuilderInstance.Build(); + User user = UserBuilderInstance.Build(); // Act repository.Save(user); - var id = user.Id; + int id = user.Id; - var repository2 = new UserRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Mock.Of(), Options.Create(GlobalSettings), Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer()); + var repository2 = new UserRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger(), Mock.Of(), Options.Create(GlobalSettings), Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer()); repository2.Delete(user); - - var resolved = repository2.Get((int) id); + IUser resolved = repository2.Get((int)id); // Assert Assert.That(resolved, Is.Null); @@ -142,16 +147,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Get_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); - var userGroupRepository = CreateUserGroupRepository(provider); + UserRepository repository = CreateRepository(provider); + UserGroupRepository userGroupRepository = CreateUserGroupRepository(provider); - var user = CreateAndCommitUserWithGroup(repository, userGroupRepository); + User user = CreateAndCommitUserWithGroup(repository, userGroupRepository); // Act - var updatedItem = repository.Get(user.Id); + IUser updatedItem = repository.Get(user.Id); // FIXME: this test cannot work, user has 2 sections but the way it's created, // they don't show, so the comparison with updatedItem fails - fix! @@ -165,16 +170,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetByQuery_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); CreateAndCommitMultipleUsers(repository); // Act - var query = scope.SqlContext.Query().Where(x => x.Username == "TestUser1"); - var result = repository.Get(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Username == "TestUser1"); + IEnumerable result = repository.Get(query); // Assert Assert.That(result.Count(), Is.GreaterThanOrEqualTo(1)); @@ -185,15 +190,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_By_Param_Ids_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); + IUser[] users = CreateAndCommitMultipleUsers(repository); // Act - var result = repository.GetMany((int) users[0].Id, (int) users[1].Id); + IEnumerable result = repository.GetMany((int)users[0].Id, (int)users[1].Id); // Assert Assert.That(result, Is.Not.Null); @@ -206,15 +211,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_GetAll_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); CreateAndCommitMultipleUsers(repository); // Act - var result = repository.GetMany(); + IEnumerable result = repository.GetMany(); // Assert Assert.That(result, Is.Not.Null); @@ -227,15 +232,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Exists_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); + IUser[] users = CreateAndCommitMultipleUsers(repository); // Act - var exists = repository.Exists(users[0].Id); + bool exists = repository.Exists(users[0].Id); // Assert Assert.That(exists, Is.True); @@ -246,16 +251,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Perform_Count_On_UserRepository() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); + IUser[] users = CreateAndCommitMultipleUsers(repository); // Act - var query = scope.SqlContext.Query().Where(x => x.Username == "TestUser1" || x.Username == "TestUser2"); - var result = repository.Count(query); + IQuery query = scope.SqlContext.Query().Where(x => x.Username == "TestUser1" || x.Username == "TestUser2"); + int result = repository.Count(query); // Assert Assert.AreEqual(2, result); @@ -265,13 +270,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Get_Paged_Results_By_Query_And_Filter_And_Groups() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); - var query = provider.SqlContext.Query().Where(x => x.Username == "TestUser1" || x.Username == "TestUser2"); + IUser[] users = CreateAndCommitMultipleUsers(repository); + IQuery query = provider.SqlContext.Query().Where(x => x.Username == "TestUser1" || x.Username == "TestUser2"); try { @@ -279,9 +284,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Database.AsUmbracoDatabase().EnableSqlCount = true; // Act - var result = repository.GetPagedResultsByQuery(query, 0, 10, out var totalRecs, user => user.Id, Direction.Ascending, - excludeUserGroups: new[] { Constants.Security.TranslatorGroupAlias }, - filter: provider.SqlContext.Query().Where(x => x.Id > -1)); + IEnumerable result = repository.GetPagedResultsByQuery( + query, + 0, + 10, + out long totalRecs, + user => user.Id, + Direction.Ascending, + excludeUserGroups: new[] { Constants.Security.TranslatorGroupAlias }, + filter: provider.SqlContext.Query().Where(x => x.Id > -1)); // Assert Assert.AreEqual(2, totalRecs); @@ -292,18 +303,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Database.AsUmbracoDatabase().EnableSqlCount = false; } } - } [Test] public void Can_Get_Paged_Results_With_Filter_And_Groups() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); - var users = CreateAndCommitMultipleUsers(repository); + IUser[] users = CreateAndCommitMultipleUsers(repository); try { @@ -311,7 +321,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor scope.Database.AsUmbracoDatabase().EnableSqlCount = true; // Act - var result = repository.GetPagedResultsByQuery(null, 0, 10, out var totalRecs, user => user.Id, Direction.Ascending, + IEnumerable result = repository.GetPagedResultsByQuery( + null, + 0, + 10, + out long totalRecs, + user => user.Id, + Direction.Ascending, includeUserGroups: new[] { Constants.Security.AdminGroupAlias, Constants.Security.SensitiveDataGroupAlias }, excludeUserGroups: new[] { Constants.Security.TranslatorGroupAlias }, filter: provider.SqlContext.Query().Where(x => x.Id == -1)); @@ -331,25 +347,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Can_Invalidate_SecurityStamp_On_Username_Change() { // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = CreateRepository(provider); - var userGroupRepository = CreateUserGroupRepository(provider); + UserRepository repository = CreateRepository(provider); + UserGroupRepository userGroupRepository = CreateUserGroupRepository(provider); - var user = CreateAndCommitUserWithGroup(repository, userGroupRepository); - var originalSecurityStamp = user.SecurityStamp; + User user = CreateAndCommitUserWithGroup(repository, userGroupRepository); + string originalSecurityStamp = user.SecurityStamp; // Ensure when user generated a security stamp is present Assert.That(user.SecurityStamp, Is.Not.Null); Assert.That(user.SecurityStamp, Is.Not.Empty); // Update username - user.Username = user.Username + "UPDATED"; + user.Username += "UPDATED"; repository.Save(user); // Get the user - var updatedUser = repository.Get(user.Id); + IUser updatedUser = repository.Get(user.Id); // Ensure the Security Stamp is invalidated & no longer the same Assert.AreNotEqual(originalSecurityStamp, updatedUser.SecurityStamp); @@ -360,25 +376,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor public void Validate_Login_Session() { // Arrange - var provider = ScopeProvider; - var user = UserBuilder.CreateUser(); - using (var scope = provider.CreateScope(autoComplete: true)) + IScopeProvider provider = ScopeProvider; + User user = UserBuilder.CreateUser(); + using (IScope scope = provider.CreateScope(autoComplete: true)) { - var repository = CreateRepository(provider); + UserRepository repository = CreateRepository(provider); repository.Save(user); } - using (var scope = provider.CreateScope(autoComplete: true)) + using (IScope scope = provider.CreateScope(autoComplete: true)) { - var repository = CreateRepository(provider); - var sessionId = repository.CreateLoginSession(user.Id, "1.2.3.4"); + UserRepository repository = CreateRepository(provider); + Guid sessionId = repository.CreateLoginSession(user.Id, "1.2.3.4"); // manually update this record to be in the past scope.Database.Execute(scope.SqlContext.Sql() .Update(u => u.Set(x => x.LoggedOutUtc, DateTime.UtcNow.AddDays(-100))) .Where(x => x.SessionId == sessionId)); - var isValid = repository.ValidateLoginSession(user.Id, sessionId); + bool isValid = repository.ValidateLoginSession(user.Id, sessionId); Assert.IsFalse(isValid); // create a new one @@ -391,33 +407,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor [Test] public void Can_Perform_Update_On_UserRepository() { - var ct = ContentTypeBuilder.CreateBasicContentType("test"); - var mt = MediaTypeBuilder.CreateSimpleMediaType("testmedia", "TestMedia"); + ContentType ct = ContentTypeBuilder.CreateBasicContentType("test"); + MediaType mt = MediaTypeBuilder.CreateSimpleMediaType("testmedia", "TestMedia"); // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope(autoComplete: true)) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope(autoComplete: true)) { - var userRepository = CreateRepository(provider); - var userGroupRepository = CreateUserGroupRepository(provider); + UserRepository userRepository = CreateRepository(provider); + UserGroupRepository userGroupRepository = CreateUserGroupRepository(provider); ContentTypeRepository.Save(ct); MediaTypeRepository.Save(mt); - var content = ContentBuilder.CreateBasicContent(ct); - var media = MediaBuilder.CreateSimpleMedia(mt, "asdf", -1); + Content content = ContentBuilder.CreateBasicContent(ct); + Media media = MediaBuilder.CreateSimpleMedia(mt, "asdf", -1); DocumentRepository.Save(content); MediaRepository.Save(media); - var user = CreateAndCommitUserWithGroup(userRepository, userGroupRepository); + User user = CreateAndCommitUserWithGroup(userRepository, userGroupRepository); // Act - var resolved = (User) userRepository.Get(user.Id); + var resolved = (User)userRepository.Get(user.Id); resolved.Name = "New Name"; - //the db column is not used, default permissions are taken from the user type's permissions, this is a getter only - //resolved.DefaultPermissions = "ZYX"; + + // the db column is not used, default permissions are taken from the user type's permissions, this is a getter only + //// resolved.DefaultPermissions = "ZYX"; + resolved.Language = "fr"; resolved.IsApproved = false; resolved.RawPasswordValue = "new"; @@ -429,7 +447,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor userRepository.Save(resolved); - var updatedItem = (User) userRepository.Get(user.Id); + var updatedItem = (User)userRepository.Get(user.Id); // Assert Assert.That(updatedItem.Id, Is.EqualTo(resolved.Id)); @@ -443,8 +461,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(updatedItem.Email, Is.EqualTo(resolved.Email)); Assert.That(updatedItem.Username, Is.EqualTo(resolved.Username)); Assert.That(updatedItem.AllowedSections.Count(), Is.EqualTo(resolved.AllowedSections.Count())); - foreach (var allowedSection in resolved.AllowedSections) + foreach (string allowedSection in resolved.AllowedSections) + { Assert.IsTrue(updatedItem.AllowedSections.Contains(allowedSection)); + } } } @@ -461,16 +481,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor Assert.That(updatedItem.Email, Is.EqualTo(originalUser.Email)); Assert.That(updatedItem.Username, Is.EqualTo(originalUser.Username)); Assert.That(updatedItem.AllowedSections.Count(), Is.EqualTo(originalUser.AllowedSections.Count())); - foreach (var allowedSection in originalUser.AllowedSections) + foreach (string allowedSection in originalUser.AllowedSections) + { Assert.IsTrue(updatedItem.AllowedSections.Contains(allowedSection)); + } } private User CreateAndCommitUserWithGroup(IUserRepository repository, IUserGroupRepository userGroupRepository) { - var user = UserBuilderInstance.WithoutIdentity().Build(); + User user = UserBuilderInstance.WithoutIdentity().Build(); repository.Save(user); - var group = UserGroupBuilderInstance.Build(); + IUserGroup group = UserGroupBuilderInstance.Build(); userGroupRepository.AddOrUpdateGroupWithUsers(@group, new[] { user.Id }); user.AddGroup(UserGroupBuilderInstance.BuildReadOnly(group)); @@ -480,9 +502,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositor private IUser[] CreateAndCommitMultipleUsers(IUserRepository repository) { - var user1 = UserBuilderInstance.WithoutIdentity().WithSuffix("1").Build(); - var user2 = UserBuilderInstance.WithoutIdentity().WithSuffix("2").Build(); - var user3 = UserBuilderInstance.WithoutIdentity().WithSuffix("3").Build(); + User user1 = UserBuilderInstance.WithoutIdentity().WithSuffix("1").Build(); + User user2 = UserBuilderInstance.WithoutIdentity().WithSuffix("2").Build(); + User user3 = UserBuilderInstance.WithoutIdentity().WithSuffix("3").Build(); repository.Save(user1); repository.Save(user2); repository.Save(user3); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/UnitOfWorkTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/UnitOfWorkTests.cs index f6197e0193..aad6938d18 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/UnitOfWorkTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/UnitOfWorkTests.cs @@ -1,6 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Scoping; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -13,10 +17,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence [Test] public void ReadLockNonExisting() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; Assert.Throws(() => { - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { scope.ReadLock(-666); scope.Complete(); @@ -27,8 +31,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence [Test] public void ReadLockExisting() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.ReadLock(Constants.Locks.Servers); scope.Complete(); @@ -38,10 +42,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence [Test] public void WriteLockNonExisting() { - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; Assert.Throws(() => { - using (var scope = provider.CreateScope()) + using (IScope scope = provider.CreateScope()) { scope.WriteLock(-666); scope.Complete(); @@ -52,8 +56,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Persistence [Test] public void WriteLockExisting() { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { scope.WriteLock(Constants.Locks.Servers); scope.Complete(); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeFileSystemsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeFileSystemsTests.cs index 1c398f681a..3b486b565e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeFileSystemsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeFileSystemsTests.cs @@ -1,17 +1,18 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.IO; using System.Text; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Scoping; -using Umbraco.Tests.Testing; using Umbraco.Tests.Integration.Testing; +using Umbraco.Tests.Testing; using FileSystems = Umbraco.Core.IO.FileSystems; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping @@ -21,6 +22,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping public class ScopeFileSystemsTests : UmbracoIntegrationTest { private IMediaFileSystem MediaFileSystem => GetRequiredService(); + private IHostingEnvironment HostingEnvironment => GetRequiredService(); [SetUp] @@ -46,19 +48,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping } [Test] - public void test_MediaFileSystem_does_not_write_to_physical_file_system_when_scoped_if_scope_does_not_complete() + public void MediaFileSystem_does_not_write_to_physical_file_system_when_scoped_if_scope_does_not_complete() { - var rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); - var rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); + string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); + string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService>(), rootPath, rootUrl); - var mediaFileSystem = MediaFileSystem; + IMediaFileSystem mediaFileSystem = MediaFileSystem; Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); using (ScopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) + { mediaFileSystem.AddFile("f1.txt", ms); + } + Assert.IsTrue(mediaFileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); @@ -72,19 +77,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping } [Test] - public void test_MediaFileSystem_writes_to_physical_file_system_when_scoped_and_scope_is_completed() + public void MediaFileSystem_writes_to_physical_file_system_when_scoped_and_scope_is_completed() { - var rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); - var rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); + string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); + string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService>(), rootPath, rootUrl); - var mediaFileSystem = MediaFileSystem; + IMediaFileSystem mediaFileSystem = MediaFileSystem; Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); - using (var scope = ScopeProvider.CreateScope(scopeFileSystems: true)) + using (IScope scope = ScopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) + { mediaFileSystem.AddFile("f1.txt", ms); + } + Assert.IsTrue(mediaFileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); @@ -102,16 +110,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void MultiThread() { - var rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); - var rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); + string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); + string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService>(), rootPath, rootUrl); - var mediaFileSystem = MediaFileSystem; + IMediaFileSystem mediaFileSystem = MediaFileSystem; - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope(scopeFileSystems: true)) + IScopeProvider scopeProvider = ScopeProvider; + using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) + { mediaFileSystem.AddFile("f1.txt", ms); + } + Assert.IsTrue(mediaFileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); @@ -120,7 +131,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsFalse(mediaFileSystem.FileExists("f1.txt")); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) + { mediaFileSystem.AddFile("f2.txt", ms); + } + Assert.IsTrue(mediaFileSystem.FileExists("f2.txt")); Assert.IsTrue(physMediaFileSystem.FileExists("f2.txt")); } @@ -133,13 +147,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void SingleShadow() { - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope(scopeFileSystems: true)) + IScopeProvider scopeProvider = ScopeProvider; + using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { using (new SafeCallContext()) // not nesting! { // ok to create a 'normal' other scope - using (var other = scopeProvider.CreateScope()) + using (IScope other = scopeProvider.CreateScope()) { other.Complete(); } @@ -148,7 +162,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping // because at the moment we don't support concurrent scoped filesystems Assert.Throws(() => { - var other = scopeProvider.CreateScope(scopeFileSystems: true); + IScope other = scopeProvider.CreateScope(scopeFileSystems: true); }); } } @@ -158,7 +172,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping public void SingleShadowEvenDetached() { var scopeProvider = (ScopeProvider)ScopeProvider; - using (var scope = scopeProvider.CreateScope(scopeFileSystems: true)) + using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { using (new SafeCallContext()) // not nesting! { @@ -167,20 +181,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping // even a detached one Assert.Throws(() => { - var other = scopeProvider.CreateDetachedScope(scopeFileSystems: true); + IScope other = scopeProvider.CreateDetachedScope(scopeFileSystems: true); }); } } - var detached = scopeProvider.CreateDetachedScope(scopeFileSystems: true); + IScope detached = scopeProvider.CreateDetachedScope(scopeFileSystems: true); Assert.IsNull(scopeProvider.AmbientScope); Assert.Throws(() => { // even if there is no ambient scope, there's a single shadow - using (var other = scopeProvider.CreateScope(scopeFileSystems: true)) - { } + using (IScope other = scopeProvider.CreateScope(scopeFileSystems: true)) + { + } }); scopeProvider.AttachScope(detached); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeTests.cs index 85331bb2af..bb3bc99e19 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopeTests.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.Core.Persistence; @@ -12,36 +15,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [UmbracoTest(Database = UmbracoTestOptions.Database.NewEmptyPerFixture)] public class ScopeTests : UmbracoIntegrationTest { - private new ScopeProvider ScopeProvider => (ScopeProvider) base.ScopeProvider; + private new ScopeProvider ScopeProvider => (ScopeProvider)base.ScopeProvider; [SetUp] - public void SetUp() - { - Assert.IsNull(ScopeProvider.AmbientScope); // gone - } + public void SetUp() => Assert.IsNull(ScopeProvider.AmbientScope); // gone [Test] public void SimpleCreateScope() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(ScopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); } + Assert.IsNull(scopeProvider.AmbientScope); } [Test] public void SimpleCreateScopeContext() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -50,6 +51,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(scopeProvider.AmbientContext); Assert.IsNotNull(scopeProvider.Context); } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } @@ -57,12 +59,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void SimpleCreateScopeDatabase() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; IUmbracoDatabase database; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -71,6 +73,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(database); Assert.IsNotNull(database.Connection); // in a transaction } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(database.Connection); // poof gone } @@ -78,15 +81,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedCreateScope() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -94,51 +97,54 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreSame(scope, ((Scope)nested).ParentScope); } } + Assert.IsNull(scopeProvider.AmbientScope); } [Test] public void NestedMigrateScope() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); - // only if Core.DEBUG_SCOPES are defined - //Assert.IsEmpty(scopeProvider.CallContextObjects); - using (var nested = scopeProvider.CreateScope(callContext: true)) + // only if Core.DEBUG_SCOPES are defined + //// Assert.IsEmpty(scopeProvider.CallContextObjects); + + using (IScope nested = scopeProvider.CreateScope(callContext: true)) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(nested, scopeProvider.AmbientScope); - Assert.AreSame(scope, ((Scope) nested).ParentScope); + Assert.AreSame(scope, ((Scope)nested).ParentScope); // it's moved over to call context - var callContextScope = CallContext.GetData(ScopeProvider.ScopeItemKey); + IScope callContextScope = CallContext.GetData(ScopeProvider.ScopeItemKey); Assert.IsNotNull(callContextScope); // only if Core.DEBUG_SCOPES are defined - //var ccnested = scopeProvider.CallContextObjects[callContextKey]; - //Assert.AreSame(nested, ccnested); + // var ccnested = scopeProvider.CallContextObjects[callContextKey]; + // Assert.AreSame(nested, ccnested); } // it's naturally back in http context } + Assert.IsNull(scopeProvider.AmbientScope); } [Test] public void NestedCreateScopeContext() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -146,12 +152,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(scopeProvider.AmbientContext); IScopeContext context; - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(nested, scopeProvider.AmbientScope); - Assert.AreSame(scope, ((Scope) nested).ParentScope); + Assert.AreSame(scope, ((Scope)nested).ParentScope); Assert.IsNotNull(scopeProvider.Context); Assert.IsNotNull(scopeProvider.AmbientContext); @@ -161,6 +167,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(scopeProvider.AmbientContext); Assert.AreSame(context, scopeProvider.AmbientContext); } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } @@ -168,37 +175,42 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedCreateScopeInnerException() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; bool? scopeCompleted = null; Assert.IsNull(scopeProvider.AmbientScope); try { - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scopeProvider.Context.Enlist("test", completed => scopeCompleted = completed); Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(nested, scopeProvider.AmbientScope); - Assert.AreSame(scope, ((Scope) nested).ParentScope); + Assert.AreSame(scope, ((Scope)nested).ParentScope); nested.Complete(); throw new Exception("bang!"); } + scope.Complete(); } + Assert.Fail("Expected exception."); } catch (Exception e) { if (e.Message != "bang!") + { Assert.Fail("Wrong exception."); + } } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNotNull(scopeCompleted); Assert.IsFalse(scopeCompleted.Value); @@ -207,12 +219,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedCreateScopeDatabase() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; IUmbracoDatabase database; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -220,16 +232,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping database = scope.Database; // populates scope's database Assert.IsNotNull(database); Assert.IsNotNull(database.Connection); // in a transaction - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.IsInstanceOf(nested); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(nested, scopeProvider.AmbientScope); - Assert.AreSame(scope, ((Scope) nested).ParentScope); + Assert.AreSame(scope, ((Scope)nested).ParentScope); Assert.AreSame(database, nested.Database); } + Assert.IsNotNull(database.Connection); // still } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(database.Connection); // poof gone } @@ -237,36 +251,36 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void Transaction() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("CREATE TABLE tmp3 (id INT, name NVARCHAR(64))"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp3 (id, name) VALUES (1, 'a')"); - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); Assert.AreEqual("a", n); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); Assert.IsNull(n); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp3 (id, name) VALUES (1, 'a')"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp3 WHERE id=1"); Assert.AreEqual("a", n); } } @@ -274,24 +288,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedTransactionInnerFail() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute($"CREATE TABLE tmp1 (id INT, name NVARCHAR(64))"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp1 (id, name) VALUES (1, 'a')"); - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=1"); Assert.AreEqual("a", n); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { nested.Database.Execute("INSERT INTO tmp1 (id, name) VALUES (2, 'b')"); - var nn = nested.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=2"); + string nn = nested.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=2"); Assert.AreEqual("b", nn); } @@ -301,9 +315,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=1"); Assert.IsNull(n); n = scope.Database.ExecuteScalar("SELECT name FROM tmp1 WHERE id=2"); Assert.IsNull(n); @@ -313,24 +327,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedTransactionOuterFail() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("CREATE TABLE tmp2 (id INT, name NVARCHAR(64))"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp2 (id, name) VALUES (1, 'a')"); - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=1"); Assert.AreEqual("a", n); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { nested.Database.Execute("INSERT INTO tmp2 (id, name) VALUES (2, 'b')"); - var nn = nested.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=2"); + string nn = nested.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=2"); Assert.AreEqual("b", nn); nested.Complete(); } @@ -339,9 +353,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual("b", n); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=1"); Assert.IsNull(n); n = scope.Database.ExecuteScalar("SELECT name FROM tmp2 WHERE id=2"); Assert.IsNull(n); @@ -351,24 +365,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void NestedTransactionComplete() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("CREATE TABLE tmp (id INT, name NVARCHAR(64))"); scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scope.Database.Execute("INSERT INTO tmp (id, name) VALUES (1, 'a')"); - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=1"); Assert.AreEqual("a", n); - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { nested.Database.Execute("INSERT INTO tmp (id, name) VALUES (2, 'b')"); - var nn = nested.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=2"); + string nn = nested.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=2"); Assert.AreEqual("b", nn); nested.Complete(); } @@ -378,9 +392,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping scope.Complete(); } - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=1"); + string n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=1"); Assert.AreEqual("a", n); n = scope.Database.ExecuteScalar("SELECT name FROM tmp WHERE id=2"); Assert.AreEqual("b", n); @@ -390,8 +404,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void CallContextScope1() { - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + ScopeProvider scopeProvider = ScopeProvider; + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsNotNull(scopeProvider.AmbientScope); Assert.IsNotNull(scopeProvider.AmbientContext); @@ -400,7 +414,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); - using (var newScope = scopeProvider.CreateScope()) + using (IScope newScope = scopeProvider.CreateScope()) { Assert.IsNotNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientScope.ParentScope); @@ -410,6 +424,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } + Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); } @@ -421,10 +436,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void CallContextScope2() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsNotNull(scopeProvider.AmbientScope); Assert.IsNotNull(scopeProvider.AmbientContext); @@ -433,7 +448,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); - using (var newScope = scopeProvider.CreateScope()) + using (IScope newScope = scopeProvider.CreateScope()) { Assert.IsNotNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientScope.ParentScope); @@ -443,33 +458,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } + Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); } Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); - - } [Test] public void ScopeReference() { - var scopeProvider = ScopeProvider; - var scope = scopeProvider.CreateScope(); - var nested = scopeProvider.CreateScope(); + ScopeProvider scopeProvider = ScopeProvider; + IScope scope = scopeProvider.CreateScope(); + IScope nested = scopeProvider.CreateScope(); Assert.IsNotNull(scopeProvider.AmbientScope); var scopeRef = new ScopeReference(scopeProvider); scopeRef.Dispose(); Assert.IsNull(scopeProvider.AmbientScope); Assert.Throws(() => { - var db = scope.Database; + IUmbracoDatabase db = scope.Database; }); Assert.Throws(() => { - var db = nested.Database; + IUmbracoDatabase db = nested.Database; }); } @@ -477,14 +491,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [TestCase(false)] public void ScopeContextEnlist(bool complete) { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; bool? completed = null; IScope ambientScope = null; IScopeContext ambientContext = null; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scopeProvider.Context.Enlist("name", c => { @@ -493,8 +507,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping ambientContext = scopeProvider.AmbientContext; }); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); Assert.IsNotNull(completed); @@ -507,66 +524,61 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [TestCase(false)] public void ScopeContextEnlistAgain(bool complete) { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; bool? completed = null; bool? completed2 = null; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { scopeProvider.Context.Enlist("name", c => { completed = c; // at that point the scope is gone, but the context is still there - var ambientContext = scopeProvider.AmbientContext; - ambientContext.Enlist("another", c2 => { completed2 = c2; }); + IScopeContext ambientContext = scopeProvider.AmbientContext; + ambientContext.Enlist("another", c2 => completed2 = c2); }); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); Assert.IsNotNull(completed); - Assert.AreEqual(complete,completed.Value); + Assert.AreEqual(complete, completed.Value); Assert.AreEqual(complete, completed2.Value); } [Test] public void ScopeContextException() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; bool? completed = null; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { - var detached = scopeProvider.CreateDetachedScope(); + IScope detached = scopeProvider.CreateDetachedScope(); scopeProvider.AttachScope(detached); + // the exception does not prevent other enlisted items to run // *and* it does not prevent the scope from properly going down - scopeProvider.Context.Enlist("name", c => - { - throw new Exception("bang"); - }); - scopeProvider.Context.Enlist("other", c => - { - completed = c; - }); + scopeProvider.Context.Enlist("name", c => throw new Exception("bang")); + scopeProvider.Context.Enlist("other", c => completed = c); detached.Complete(); - Assert.Throws(() => - { - detached.Dispose(); - }); + Assert.Throws(() => detached.Dispose()); // even though disposing of the scope has thrown, it has exited // properly ie it has removed itself, and the app remains clean - Assert.AreSame(scope, scopeProvider.AmbientScope); scope.Complete(); } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); @@ -577,10 +589,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping [Test] public void DetachableScope() { - var scopeProvider = ScopeProvider; + ScopeProvider scopeProvider = ScopeProvider; Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope()) + using (IScope scope = scopeProvider.CreateScope()) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); @@ -588,22 +600,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.IsNotNull(scopeProvider.AmbientContext); // the ambient context Assert.IsNotNull(scopeProvider.Context); // the ambient context too (getter only) - var context = scopeProvider.Context; + IScopeContext context = scopeProvider.Context; - var detached = scopeProvider.CreateDetachedScope(); + IScope detached = scopeProvider.CreateDetachedScope(); scopeProvider.AttachScope(detached); Assert.AreEqual(detached, scopeProvider.AmbientScope); Assert.AreNotSame(context, scopeProvider.Context); // nesting under detached! - using (var nested = scopeProvider.CreateScope()) + using (IScope nested = scopeProvider.CreateScope()) { Assert.Throws(() => - { + // cannot detach a non-detachable scope - scopeProvider.DetachScope(); - }); + scopeProvider.DetachScope()); nested.Complete(); } @@ -617,21 +628,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreSame(context, scopeProvider.AmbientContext); Assert.Throws(() => - { + // cannot disposed a non-attached scope // in fact, only the ambient scope can be disposed - detached.Dispose(); - }); + detached.Dispose()); scopeProvider.AttachScope(detached); detached.Complete(); detached.Dispose(); // has self-detached, and is gone! - Assert.AreSame(scope, scopeProvider.AmbientScope); Assert.AreSame(context, scopeProvider.AmbientContext); } + Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopedRepositoryTests.cs index 11f4095f53..259df0d753 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Scoping/ScopedRepositoryTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Linq; @@ -29,8 +32,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping private DistributedCacheBinder _distributedCacheBinder; private IUserService UserService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IServerMessenger ServerMessenger => GetRequiredService(); + private CacheRefresherCollection CacheRefresherCollection => GetRequiredService(); protected override void CustomTestSetup(IUmbracoBuilder builder) @@ -63,12 +69,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping { var scopeProvider = (ScopeProvider)ScopeProvider; var service = (UserService)UserService; - var globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(IUser)); + IAppPolicyCache globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(IUser)); var user = (IUser)new User(GlobalSettings, "name", "email", "username", "rawPassword"); service.Save(user); // global cache contains the entity - var globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); + var globalCached = (IUser)globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); @@ -80,37 +86,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping _distributedCacheBinder.BindEvents(true); Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) + using (IScope scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (IUser)); + IAppPolicyCache scopedCache = scope.IsolatedCaches.GetOrCreate(typeof(IUser)); Assert.AreNotSame(globalCache, scopedCache); user.Name = "changed"; service.Save(user); // scoped cache contains the "new" entity - var scopeCached = (IUser) scopedCache.Get(GetCacheIdKey(user.Id), () => null); + var scopeCached = (IUser)scopedCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(user.Id, scopeCached.Id); Assert.AreEqual("changed", scopeCached.Name); // global cache is unchanged - globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser)globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); - globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser)globalCache.Get(GetCacheIdKey(user.Id), () => null); if (complete) { // global cache has been cleared @@ -127,7 +136,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual(complete ? "changed" : "name", user.Name); // global cache contains the entity again - globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser)globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual(complete ? "changed" : "name", globalCached.Name); @@ -138,21 +147,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping public void FullDataSetRepositoryCachePolicy(bool complete) { var scopeProvider = (ScopeProvider)ScopeProvider; - var service = LocalizationService; - var globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof (ILanguage)); + ILocalizationService service = LocalizationService; + IAppPolicyCache globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(ILanguage)); - var lang = (ILanguage) new Language(GlobalSettings, "fr-FR"); + var lang = (ILanguage)new Language(GlobalSettings, "fr-FR"); service.Save(lang); // global cache has been flushed, reload - var globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + var globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNull(globalFullCached); - var reload = service.GetLanguageById(lang.Id); + ILanguage reload = service.GetLanguageById(lang.Id); // global cache contains the entity - globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); - var globalCached = globalFullCached.First(x => x.Id == lang.Id); + ILanguage globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); Assert.AreEqual(lang.Id, globalCached.Id); Assert.AreEqual("fr-FR", globalCached.IsoCode); @@ -161,35 +170,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping _distributedCacheBinder.BindEvents(true); Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) + using (IScope scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (ILanguage)); + IAppPolicyCache scopedCache = scope.IsolatedCaches.GetOrCreate(typeof(ILanguage)); Assert.AreNotSame(globalCache, scopedCache); - //Use IsMandatory of isocode to ensure publishedContent cache is not also rebuild + // Use IsMandatory of isocode to ensure publishedContent cache is not also rebuild lang.IsMandatory = true; service.Save(lang); // scoped cache has been flushed, reload - var scopeFullCached = (IEnumerable) scopedCache.Get(GetCacheTypeKey(), () => null); + var scopeFullCached = (IEnumerable)scopedCache.Get(GetCacheTypeKey(), () => null); Assert.IsNull(scopeFullCached); reload = service.GetLanguageById(lang.Id); // scoped cache contains the "new" entity - scopeFullCached = (IEnumerable) scopedCache.Get(GetCacheTypeKey(), () => null); + scopeFullCached = (IEnumerable)scopedCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(scopeFullCached); - var scopeCached = scopeFullCached.First(x => x.Id == lang.Id); + ILanguage scopeCached = scopeFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(scopeCached); Assert.AreEqual(lang.Id, scopeCached.Id); Assert.AreEqual(true, scopeCached.IsMandatory); // global cache is unchanged - globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -197,11 +206,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual(false, globalCached.IsMandatory); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); - globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); if (complete) { // global cache has been cleared @@ -218,7 +230,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual(complete ? true : false, lang.IsMandatory); // global cache contains the entity again - globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable)globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -231,13 +243,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping public void SingleItemsOnlyRepositoryCachePolicy(bool complete) { var scopeProvider = (ScopeProvider)ScopeProvider; - var service = LocalizationService; - var globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); + ILocalizationService service = LocalizationService; + IAppPolicyCache globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(IDictionaryItem)); var lang = (ILanguage)new Language(GlobalSettings, "fr-FR"); service.Save(lang); - var item = (IDictionaryItem) new DictionaryItem("item-key"); + var item = (IDictionaryItem)new DictionaryItem("item-key"); item.Translations = new IDictionaryTranslation[] { new DictionaryTranslation(lang.Id, "item-value"), @@ -245,7 +257,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping service.Save(item); // global cache contains the entity - var globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); + var globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); @@ -254,37 +266,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping _distributedCacheBinder.BindEvents(true); Assert.IsNull(scopeProvider.AmbientScope); - using (var scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) + using (IScope scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) { Assert.IsInstanceOf(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); + IAppPolicyCache scopedCache = scope.IsolatedCaches.GetOrCreate(typeof(IDictionaryItem)); Assert.AreNotSame(globalCache, scopedCache); item.ItemKey = "item-changed"; service.Save(item); // scoped cache contains the "new" entity - var scopeCached = (IDictionaryItem) scopedCache.Get(GetCacheIdKey(item.Id), () => null); + var scopeCached = (IDictionaryItem)scopedCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(item.Id, scopeCached.Id); Assert.AreEqual("item-changed", scopeCached.ItemKey); // global cache is unchanged - globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); if (complete) + { scope.Complete(); + } } + Assert.IsNull(scopeProvider.AmbientScope); - globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey(item.Id), () => null); if (complete) { // global cache has been cleared @@ -301,27 +316,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping Assert.AreEqual(complete ? "item-changed" : "item-key", item.ItemKey); // global cache contains the entity again - globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual(complete ? "item-changed" : "item-key", globalCached.ItemKey); } - public static string GetCacheIdKey(object id) - { - return $"{GetCacheTypeKey()}{id}"; - } + public static string GetCacheIdKey(object id) => $"{GetCacheTypeKey()}{id}"; - public static string GetCacheTypeKey() - { - return $"uRepo_{typeof (T).Name}_"; - } + public static string GetCacheTypeKey() => $"uRepo_{typeof(T).Name}_"; public class PassiveEventDispatcher : QueuingEventDispatcherBase { public PassiveEventDispatcher() : base(false) - { } + { + } protected override void ScopeExitCompleted() { @@ -333,12 +343,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Scoping { public LocalServerMessenger() : base(false) - { } - - protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) { - throw new NotImplementedException(); } + + protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) => + throw new NotImplementedException(); } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditServiceTests.cs index d7385a7acf..6260d8adbb 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditServiceTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; @@ -18,24 +21,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void GetPage() { - var sut = (AuditService) GetRequiredService(); - var expected = new AuditEntryBuilder().Build(); + var sut = (AuditService)GetRequiredService(); + IAuditEntry expected = new AuditEntryBuilder().Build(); - - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { sut.Write( expected.PerformingUserId + i, expected.PerformingDetails, expected.PerformingIp, expected.EventDateUtc.AddMinutes(i), - expected.AffectedUserId+ i, + expected.AffectedUserId + i, expected.AffectedDetails, expected.EventType, expected.EventDetails); } - var entries = sut.GetPage(2, 2, out var count).ToArray(); + IAuditEntry[] entries = sut.GetPage(2, 2, out long count).ToArray(); Assert.Multiple(() => { @@ -48,20 +50,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void GetUserLogs() { - var sut = (AuditService) Services.GetRequiredService(); + var sut = (AuditService)Services.GetRequiredService(); - var eventDateUtc = DateTime.UtcNow.AddDays(-1); + DateTime eventDateUtc = DateTime.UtcNow.AddDays(-1); - var numberOfEntries = 10; - for (var i = 0; i < numberOfEntries; i++) + int numberOfEntries = 10; + for (int i = 0; i < numberOfEntries; i++) { eventDateUtc = eventDateUtc.AddMinutes(1); - sut.Add(AuditType.Unpublish, -1, 33, "", "blah"); + sut.Add(AuditType.Unpublish, -1, 33, string.Empty, "blah"); } - sut.Add(AuditType.Publish, -1, 33, "", "blah"); + sut.Add(AuditType.Publish, -1, 33, string.Empty, "blah"); - var logs = sut.GetUserLogs(-1, AuditType.Unpublish).ToArray(); + IAuditItem[] logs = sut.GetUserLogs(-1, AuditType.Unpublish).ToArray(); Assert.Multiple(() => { @@ -75,10 +77,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Write_and_GetAll() { - var sut = (AuditService) Services.GetRequiredService(); - var expected = new AuditEntryBuilder().Build(); + var sut = (AuditService)Services.GetRequiredService(); + IAuditEntry expected = new AuditEntryBuilder().Build(); - var actual = sut.Write( + IAuditEntry actual = sut.Write( expected.PerformingUserId, expected.PerformingDetails, expected.PerformingIp, @@ -88,7 +90,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services expected.EventType, expected.EventDetails); - var entries = sut.GetAll().ToArray(); + IAuditEntry[] entries = sut.GetAll().ToArray(); Assert.Multiple(() => { diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CachedDataTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CachedDataTypeServiceTests.cs index 3c03be2a95..c57eac686b 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CachedDataTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/CachedDataTypeServiceTests.cs @@ -1,4 +1,8 @@ -using System.Threading; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; +using System.Threading; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; @@ -18,9 +22,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class CachedDataTypeServiceTests : UmbracoIntegrationTest { private IDataTypeService DataTypeService => GetRequiredService(); + private ILocalizedTextService LocalizedTextService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IConfigurationEditorJsonSerializer ConfigurationEditorJsonSerializer => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); /// @@ -33,9 +41,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IDataType dataType = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { Name = "Testing Textfield", DatabaseType = ValueStorageType.Ntext }; DataTypeService.Save(dataType); - //Get all the first time (no cache) - var all = DataTypeService.GetAll(); - //Get all a second time (with cache) + // Get all the first time (no cache) + IEnumerable all = DataTypeService.GetAll(); + + // Get all a second time (with cache) all = DataTypeService.GetAll(); Assert.Pass(); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ConsentServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ConsentServiceTests.cs index 905697159d..c489fe68af 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ConsentServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ConsentServiceTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using NUnit.Framework; using Umbraco.Core.Models; @@ -18,8 +21,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void CanCrudConsent() { // can register - - var consent = ConsentService.RegisterConsent("user/1234", "app1", "do-something", ConsentState.Granted, "no comment"); + IConsent consent = ConsentService.RegisterConsent("user/1234", "app1", "do-something", ConsentState.Granted, "no comment"); Assert.AreNotEqual(0, consent.Id); Assert.IsTrue(consent.Current); @@ -32,14 +34,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(consent.IsGranted()); // can register more - ConsentService.RegisterConsent("user/1234", "app1", "do-something-else", ConsentState.Granted, "no comment"); ConsentService.RegisterConsent("user/1236", "app1", "do-something", ConsentState.Granted, "no comment"); ConsentService.RegisterConsent("user/1237", "app2", "do-something", ConsentState.Granted, "no comment"); // can get by source - - var consents = ConsentService.LookupConsent(source: "user/1235").ToArray(); + IConsent[] consents = ConsentService.LookupConsent(source: "user/1235").ToArray(); Assert.IsEmpty(consents); consents = ConsentService.LookupConsent(source: "user/1234").ToArray(); @@ -49,7 +49,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(consents.Any(x => x.Action == "do-something-else")); // can get by context - consents = ConsentService.LookupConsent(context: "app3").ToArray(); Assert.IsEmpty(consents); @@ -62,7 +61,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(consents.Any(x => x.Action == "do-something-else")); // can get by action - consents = ConsentService.LookupConsent(action: "do-whatever").ToArray(); Assert.IsEmpty(consents); @@ -73,7 +71,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(consents.Any(x => x.Source == "user/1236")); // can revoke - consent = ConsentService.RegisterConsent("user/1234", "app1", "do-something", ConsentState.Revoked, "no comment"); consents = ConsentService.LookupConsent(source: "user/1234", context: "app1", action: "do-something").ToArray(); @@ -82,27 +79,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(ConsentState.Revoked, consents[0].State); // can filter - consents = ConsentService.LookupConsent(context: "app1", action: "do-", actionStartsWith: true).ToArray(); Assert.AreEqual(3, consents.Length); Assert.IsTrue(consents.All(x => x.Context == "app1")); Assert.IsTrue(consents.All(x => x.Action.StartsWith("do-"))); // can get history - consents = ConsentService.LookupConsent(source: "user/1234", context: "app1", action: "do-something", includeHistory: true).ToArray(); Assert.AreEqual(1, consents.Length); Assert.IsTrue(consents[0].Current); Assert.AreEqual(ConsentState.Revoked, consents[0].State); Assert.IsTrue(consents[0].IsRevoked()); Assert.IsNotNull(consents[0].History); - var history = consents[0].History.ToArray(); + IConsent[] history = consents[0].History.ToArray(); Assert.AreEqual(1, history.Length); Assert.IsFalse(history[0].Current); Assert.AreEqual(ConsentState.Granted, history[0].State); // cannot be stupid - Assert.Throws(() => ConsentService.RegisterConsent("user/1234", "app1", "do-something", ConsentState.Granted | ConsentState.Revoked, "no comment")); } @@ -114,7 +108,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ConsentService.RegisterConsent("user/1234", "app1", "consentWithoutComment", ConsentState.Granted); // Attempt to retrieve the consent we just added without a comment - var consents = ConsentService.LookupConsent(source: "user/1234", action: "consentWithoutComment").ToArray(); + IConsent[] consents = ConsentService.LookupConsent(source: "user/1234", action: "consentWithoutComment").ToArray(); // Confirm we got our expected consent record Assert.AreEqual(1, consents.Length); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentEventsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentEventsTests.cs index 80bf464c31..81143be7cb 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentEventsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentEventsTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Linq; @@ -25,12 +28,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { private CacheRefresherCollection CacheRefresherCollection => GetRequiredService(); + + private IUmbracoContextFactory UmbracoContextFactory => GetRequiredService(); private ILogger Logger => GetRequiredService>(); - - #region Setup - [SetUp] public void SetUp() { @@ -45,7 +47,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentCacheRefresher.CacheUpdated += ContentCacheUpdated; // prepare content type - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); _contentType = ContentTypeBuilder.CreateSimpleContentType("whatever", "Whatever", defaultTemplateId: template.Id); @@ -61,8 +63,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { _h1?.UnbindEvents(); - // clear ALL events - + // Clear ALL events DocumentRepository.ScopedEntityRefresh -= ContentRepositoryRefreshed; DocumentRepository.ScopeEntityRemove -= ContentRepositoryRemoved; DocumentRepository.ScopeVersionRemove -= ContentRepositoryRemovedVersion; @@ -83,92 +84,88 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private IContent CreateContent(int parentId = -1) { - var content1 = ContentBuilder.CreateSimpleContent(_contentType, "Content1", parentId); + Content content1 = ContentBuilder.CreateSimpleContent(_contentType, "Content1", parentId); ContentService.Save(content1); return content1; } private IContent CreateBranch() { - var content1 = ContentBuilder.CreateSimpleContent(_contentType, "Content1"); + Content content1 = ContentBuilder.CreateSimpleContent(_contentType, "Content1"); ContentService.SaveAndPublish(content1); // 2 (published) // .1 (published) // .2 (not published) - var content2 = ContentBuilder.CreateSimpleContent(_contentType, "Content2", content1); + Content content2 = ContentBuilder.CreateSimpleContent(_contentType, "Content2", content1); ContentService.SaveAndPublish(content2); - var content21 = ContentBuilder.CreateSimpleContent(_contentType, "Content21", content2); + Content content21 = ContentBuilder.CreateSimpleContent(_contentType, "Content21", content2); ContentService.SaveAndPublish(content21); - var content22 = ContentBuilder.CreateSimpleContent(_contentType, "Content22", content2); + Content content22 = ContentBuilder.CreateSimpleContent(_contentType, "Content22", content2); ContentService.Save(content22); // 3 (not published) // .1 (not published) // .2 (not published) - var content3 = ContentBuilder.CreateSimpleContent(_contentType, "Content3", content1); + Content content3 = ContentBuilder.CreateSimpleContent(_contentType, "Content3", content1); ContentService.Save(content3); - var content31 = ContentBuilder.CreateSimpleContent(_contentType, "Content31", content3); + Content content31 = ContentBuilder.CreateSimpleContent(_contentType, "Content31", content3); ContentService.Save(content31); - var content32 = ContentBuilder.CreateSimpleContent(_contentType, "Content32", content3); + Content content32 = ContentBuilder.CreateSimpleContent(_contentType, "Content32", content3); ContentService.Save(content32); // 4 (published + saved) // .1 (published) // .2 (not published) - var content4 = ContentBuilder.CreateSimpleContent(_contentType, "Content4", content1); + Content content4 = ContentBuilder.CreateSimpleContent(_contentType, "Content4", content1); ContentService.SaveAndPublish(content4); content4.Name = "Content4X"; ContentService.Save(content4); - var content41 = ContentBuilder.CreateSimpleContent(_contentType, "Content41", content4); + Content content41 = ContentBuilder.CreateSimpleContent(_contentType, "Content41", content4); ContentService.SaveAndPublish(content41); - var content42 = ContentBuilder.CreateSimpleContent(_contentType, "Content42", content4); + Content content42 = ContentBuilder.CreateSimpleContent(_contentType, "Content42", content4); ContentService.Save(content42); // 5 (not published) // .1 (published) // .2 (not published) - var content5 = ContentBuilder.CreateSimpleContent(_contentType, "Content5", content1); + Content content5 = ContentBuilder.CreateSimpleContent(_contentType, "Content5", content1); ContentService.SaveAndPublish(content5); - var content51 = ContentBuilder.CreateSimpleContent(_contentType, "Content51", content5); + Content content51 = ContentBuilder.CreateSimpleContent(_contentType, "Content51", content5); ContentService.SaveAndPublish(content51); - var content52 = ContentBuilder.CreateSimpleContent(_contentType, "Content52", content5); + Content content52 = ContentBuilder.CreateSimpleContent(_contentType, "Content52", content5); ContentService.Save(content52); ContentService.Unpublish(content5); return content1; } - #endregion - - #region Validate Setup - [Test] public void CreatedBranchIsOk() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); - var children1 = Children(content1).ToArray(); + IContent[] children1 = Children(content1).ToArray(); - var content2 = children1[0]; - var children2 = Children(content2).ToArray(); - var content21 = children2[0]; - var content22 = children2[1]; + IContent content2 = children1[0]; + IContent[] children2 = Children(content2).ToArray(); + IContent content21 = children2[0]; + IContent content22 = children2[1]; - var content3 = children1[1]; - var children3 = Children(content3).ToArray(); - var content31 = children3[0]; - var content32 = children3[1]; + IContent content3 = children1[1]; + IContent[] children3 = Children(content3).ToArray(); + IContent content31 = children3[0]; + IContent content32 = children3[1]; - var content4 = children1[2]; - var children4 = Children(content4).ToArray(); - var content41 = children4[0]; - var content42 = children4[1]; + IContent content4 = children1[2]; + IContent[] children4 = Children(content4).ToArray(); + IContent content41 = children4[0]; + IContent content42 = children4[1]; - var content5 = children1[3]; - var children5 = Children(content5).ToArray(); - var content51 = children5[0]; - var content52 = children5[1]; + IContent content5 = children1[3]; + IContent[] children5 = Children(content5).ToArray(); + IContent content51 = children5[0]; + IContent content52 = children5[1]; Assert.IsTrue(content1.Published); Assert.IsFalse(content1.Edited); @@ -202,29 +199,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(content52.Edited); } - #endregion - - #region Events tracer - private class EventInstance { // ReSharper disable MemberCanBePrivate.Local // ReSharper disable UnusedAutoPropertyAccessor.Local public int Message { get; set; } + public string Sender { get; set; } + public string Name { get; set; } + public string Args { get; set; } + public object EventArgs { get; set; } + // ReSharper restore MemberCanBePrivate.Local // ReSharper restore UnusedAutoPropertyAccessor.Local - - public override string ToString() - { - return $"{Message:000}: {Sender.Replace(" ", "")}/{Name}/{Args}"; - } + public override string ToString() => $"{Message:000}: {Sender.Replace(" ", string.Empty)}/{Name}/{Args}"; } - private static readonly string[] PropertiesImpactingAllVersions = { "SortOrder", "ParentId", "Level", "Path", "Trashed" }; + private static readonly string[] s_propertiesImpactingAllVersions = { "SortOrder", "ParentId", "Level", "Path", "Trashed" }; private static bool HasChangesImpactingAllVersions(IContent icontent) { @@ -233,10 +227,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // UpdateDate will be dirty // Published may be dirty if saving a Published entity // so cannot do this (would always be true): - //return content.IsEntityDirty(); + // return content.IsEntityDirty(); // have to be more precise & specify properties - return PropertiesImpactingAllVersions.Any(content.IsPropertyDirty); + return s_propertiesImpactingAllVersions.Any(content.IsPropertyDirty); } private void ContentRepositoryRefreshed(DocumentRepository sender, DocumentRepository.ScopedEntityEventArgs args) @@ -261,8 +255,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // x is u|p and is the (un)published state of the event content // y is +|-|= and is the action (publish, unpublish, no change) // z is u|p|m and is the (un)published state after the event - - var entities = new[] { args.Entity }; // args.Entities + IContent[] entities = new[] { args.Entity }; // args.Entities var e = new EventInstance { @@ -271,23 +264,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Name = "Refresh", Args = string.Join(",", entities.Select(x => { - var publishedState = ((Content) x).PublishedState; + PublishedState publishedState = ((Content)x).PublishedState; - var xstate = x.Published ? "p" : "u"; + string xstate = x.Published ? "p" : "u"; if (publishedState == PublishedState.Publishing) - xstate += "+" + (x.ParentId == - 1 || sender.IsPathPublished(sender.Get(x.ParentId)) ? "p" : "m"); + { + xstate += "+" + (x.ParentId == -1 || sender.IsPathPublished(sender.Get(x.ParentId)) ? "p" : "m"); + } else if (publishedState == PublishedState.Unpublishing) + { xstate += "-u"; + } else + { xstate += "=" + (x.Published ? (sender.IsPathPublished(x) ? "p" : "m") : "u"); + } return $"{x.Id}.{xstate}"; - - var willBePublished = publishedState == PublishedState.Publishing || x.Published; // && ((Content) x).PublishedState == PublishedState.Unpublishing; + bool willBePublished = publishedState == PublishedState.Publishing || x.Published; // && ((Content) x).PublishedState == PublishedState.Unpublishing; // saved content - var state = willBePublished ? "p" : "u"; + string state = willBePublished ? "p" : "u"; if (publishedState == PublishedState.Publishing) { @@ -295,11 +293,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // figure out whether it is masked or not - what to do exactly in each case // would depend on the handler implementation - ie is it still updating // data for masked version or not - var isPathPublished = sender.IsPathPublished(x); // expensive! + bool isPathPublished = sender.IsPathPublished(x); // expensive! if (isPathPublished) + { state += "p"; // refresh (using x) + } else + { state += "m"; // masked + } } else if (publishedState == PublishedState.Unpublishing) { @@ -309,13 +311,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } else if (publishedState == PublishedState.Published) { - var isPathPublished = sender.IsPathPublished(x); // expensive! + bool isPathPublished = sender.IsPathPublished(x); // expensive! if (isPathPublished == false) + { state += "m"; // masked + } else if (HasChangesImpactingAllVersions(x)) + { state += "p"; // refresh (using published = sender.GetByVersion(x.PublishedVersionGuid)) + } else + { state += "u"; // no impact on published version + } } else // Unpublished { @@ -323,11 +331,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } //// published version - //if (x.Published == false) - //{ + // if (x.Published == false) + // { // // x is not a published version - // // unpublishing content, clear + // // unpublishing content, clear // // handlers would probably clear data // if (((Content)x).PublishedState == PublishedState.Unpublishing) // { @@ -345,9 +353,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // } // else // state += "u"; // no published version - //} - //else - //{ + // } + // else + // { // // content is published and x is the published version // // figure out whether it is masked or not - what to do exactly in each case // // would depend on the handler implementation - ie is it still updating @@ -357,8 +365,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // state += "p"; // refresh (using x) // else // state += "m"; // masked - //} - + // } return $"{state}-{x.Id}"; })) }; @@ -370,8 +377,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // reports the event as : "ContentRepository/Remove/X" // where // X is the event content ID - - var entities = new[] { args.Entity }; // args.Entities + IContent[] entities = new[] { args.Entity }; // args.Entities var e = new EventInstance { @@ -379,7 +385,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Sender = "ContentRepository", EventArgs = args, Name = "Remove", - //Args = string.Join(",", args.Entities.Select(x => (x.Published ? "p" : "u") + x.Id)) + //// Args = string.Join(",", args.Entities.Select(x => (x.Published ? "p" : "u") + x.Id)) Args = string.Join(",", entities.Select(x => x.Id)) }; _events.Add(e); @@ -391,14 +397,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // where // X is the event content ID // Y is the event content version GUID - var e = new EventInstance { Message = _msgCount++, Sender = "ContentRepository", EventArgs = args, Name = "RemoveVersion", - //Args = string.Join(",", args.Versions.Select(x => string.Format("{0}:{1}", x.Item1, x.Item2))) + //// Args = string.Join(",", args.Versions.Select(x => string.Format("{0}:{1}", x.Item1, x.Item2))) Args = $"{args.EntityId}:{args.VersionId}" }; _events.Add(e); @@ -410,18 +415,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // where // is(are) the action(s) // X is the event content ID - if (args.MessageType != MessageType.RefreshByPayload) + { throw new NotSupportedException(); + } - foreach (var payload in (ContentCacheRefresher.JsonPayload[]) args.MessageObject) + foreach (ContentCacheRefresher.JsonPayload payload in (ContentCacheRefresher.JsonPayload[])args.MessageObject) { var e = new EventInstance { Message = _msgCount, Sender = sender.Name, EventArgs = payload, - Name = payload.ChangeTypes.ToString().Replace(" ", ""), + Name = payload.ChangeTypes.ToString().Replace(" ", string.Empty), Args = payload.Id.ToInvariantString() }; _events.Add(e); @@ -433,20 +439,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void WriteEvents() { Console.WriteLine("EVENTS"); - foreach (var e in _events) + foreach (EventInstance e in _events) + { Console.WriteLine(e); + } } - #endregion - - #region Utils - private IEnumerable Children(IContent content) - => ContentService.GetPagedChildren(content.Id, 0, int.MaxValue, out var total); - - #endregion - - #region Save, Publish & Unpublish single content + => ContentService.GetPagedChildren(content.Id, 0, int.MaxValue, out long total); [Test] public void SaveUnpublishedContent() @@ -454,8 +454,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved, // - repository : refresh u=u // - content cache : refresh newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ResetEvents(); @@ -464,8 +463,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); @@ -477,8 +476,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved, // - repository : refresh (u) // - content cache :: refresh newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -488,8 +486,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); @@ -513,8 +511,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved, // - repository : refresh (u) // - content cache :: refresh newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -524,8 +521,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); @@ -549,8 +546,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved, // - repository : refresh (u) // - content cache :: refresh newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -560,8 +556,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); @@ -585,8 +581,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved&published, // - repository : refresh (p) // - content cache :: refresh published, newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ResetEvents(); @@ -595,8 +590,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u+p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i++].ToString()); @@ -608,8 +603,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is saved&published, // - repository : refresh (p) // - content cache :: refresh published, newest - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -619,8 +613,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p+p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i++].ToString()); @@ -635,8 +629,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // note: whenever the published cache is refreshed, subscribers must // assume that the unpublished cache is also refreshed, with the same // values, and deal with it. - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ResetEvents(); @@ -645,8 +638,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u+p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i++].ToString()); @@ -658,8 +651,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is unpublished, // - repository : refresh (u) // - content cache :: refresh newest, remove published - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -668,8 +660,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p-u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); @@ -681,8 +673,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content is unpublished, // - repository : refresh (u) // - content cache :: refresh newest, remove published - - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); content.Name = "changed"; @@ -693,19 +684,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p-u", _events[i++].ToString()); m++; - //Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content.Id), _events[i++].ToString()); - //Assert.AreEqual("changed", ContentService.GetById(((ContentCacheRefresher.JsonPayload)_events[i - 1].EventArgs).Id).Name); + + //// Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content.Id), _events[i++].ToString()); + //// Assert.AreEqual("changed", ContentService.GetById(((ContentCacheRefresher.JsonPayload)_events[i - 1].EventArgs).Id).Name); + Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); } - #endregion - - #region Publish & Unpublish branch - [Test] public void UnpublishContentBranch() { @@ -717,19 +706,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // the whole branch by themselves. Examine does it in UmbracoContentIndexer, // content caches have to do it too... wondering whether we should instead // trigger RemovePublished for all of the removed content? - - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ResetEvents(); ContentService.Unpublish(content1); Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p-u", _events[i++].ToString()); m++; - //Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1.Id), _events[i++].ToString()); + + //// Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1.Id), _events[i++].ToString()); + Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); } @@ -739,8 +729,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rule: when a content branch is published, // - repository :: refresh root (p) // - published page cache :: refresh root & descendants, database (level, sortOrder) order - - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ContentService.Unpublish(content1); ResetEvents(); @@ -748,8 +737,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.u+p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); // repub content1 @@ -771,97 +760,97 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void PublishContentBranchWithPublishedChildren() { // rule? - - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ContentService.Unpublish(content1); // branch is: - ResetEvents(); ContentService.SaveAndPublishBranch(content1, force: false); // force = false, don't publish unpublished items - foreach (var e in _events) + foreach (EventInstance e in _events) + { Console.WriteLine(e); + } Assert.AreEqual(3, _msgCount); Assert.AreEqual(3, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. // force:false => only republish the root node + nodes that are edited Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.u+p", _events[i++].ToString()); // content1 was unpublished, now published // change: only content4 shows here, because it has changes - others don't need to be published - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p+p", _events[i++].ToString()); // content1/content2 + // Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p+p", _events[i++].ToString()); // content1/content2 Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[2].Id}.p+p", _events[i++].ToString()); // content1/content4 - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p+p", _events[i++].ToString()); // content1/content2/content21 - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[0].Id}.p+p", _events[i++].ToString()); // content1/content4/content41 + // Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p+p", _events[i++].ToString()); // content1/content2/content21 + // Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[0].Id}.p+p", _events[i++].ToString()); // content1/content4/content41 Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); // repub content1 +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void PublishContentBranchWithAllChildren() { // rule? - - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ContentService.Unpublish(content1); ResetEvents(); ContentService.SaveAndPublishBranch(content1, force: true); // force = true, also publish unpublished items - foreach (var e in _events) + foreach (EventInstance e in _events) + { Console.WriteLine(e); + } Assert.AreEqual(10, _msgCount); Assert.AreEqual(10, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. // force:true => all nodes are republished, refreshing all nodes - but only with changes - published w/out changes are not repub Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.u+p", _events[i++].ToString()); - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p+p", _events[i++].ToString()); - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p+p", _events[i++].ToString()); + //// Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p+p", _events[i++].ToString()); + //// Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content3C[0].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content3C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[2].Id}.p+p", _events[i++].ToString()); - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[0].Id}.p+p", _events[i++].ToString()); + //// Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[0].Id}.p+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content4C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[3].Id}.u+p", _events[i++].ToString()); - //Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content5C[0].Id}.p+p", _events[i++].ToString()); + //// Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content5C[0].Id}.p+p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content5C[1].Id}.u+p", _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); // repub content1 +#pragma warning restore SA1003 // Symbols should be spaced correctly } - #endregion - - #region Sort - [Test] public void SortAll() { // rule: ? - - var content1 = CreateBranch(); - var content1C = Children(content1).ToArray(); + IContent content1 = CreateBranch(); + IContent[] content1C = Children(content1).ToArray(); Assert.AreEqual(4, content1C.Length); - var content1Csorted = new[] { content1C[3], content1C[0], content1C[1], content1C[2] }; + IContent[] content1Csorted = new[] { content1C[3], content1C[0], content1C[1], content1C[2] }; ResetEvents(); ContentService.Sort(content1Csorted); - var content1Cagain = Children(content1).ToArray(); + IContent[] content1Cagain = Children(content1).ToArray(); Assert.AreEqual(4, content1Cagain.Length); Assert.AreEqual(content1C[0].Id, content1Cagain[1].Id); Assert.AreEqual(content1C[1].Id, content1Cagain[2].Id); @@ -870,8 +859,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, _msgCount); Assert.AreEqual(8, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[3].Id}.u=u", _events[i++].ToString()); // content5 is not published Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); // content2 is published Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[1].Id}.u=u", _events[i++].ToString()); // content3 is not published @@ -881,22 +871,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[0].Id}", _events[i++].ToString()); // content2 is published Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[1].Id}", _events[i++].ToString()); // content3 is not published Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[2].Id}", _events[i].ToString()); // content4 is published +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void SortSome() { // rule: ? - - var content1 = CreateBranch(); - var content1C = Children(content1).ToArray(); + IContent content1 = CreateBranch(); + IContent[] content1C = Children(content1).ToArray(); Assert.AreEqual(4, content1C.Length); - var content1Csorted = new[] { content1C[0], content1C[1], content1C[3], content1C[2] }; + IContent[] content1Csorted = new[] { content1C[0], content1C[1], content1C[3], content1C[2] }; ResetEvents(); ContentService.Sort(content1Csorted); - var content1Cagain = Children(content1).ToArray(); + IContent[] content1Cagain = Children(content1).ToArray(); Assert.AreEqual(4, content1Cagain.Length); Assert.AreEqual(content1C[0].Id, content1Cagain[0].Id); Assert.AreEqual(content1C[1].Id, content1Cagain[1].Id); @@ -905,27 +895,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(3, _msgCount); Assert.AreEqual(4, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[3].Id}.u=u", _events[i++].ToString()); // content5 is not published Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1C[2].Id}.p=p", _events[i++].ToString()); // content4 is published + changes m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[3].Id}", _events[i++].ToString()); // content5 is not published Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content1C[2].Id}", _events[i].ToString()); // content4 is published +#pragma warning restore SA1003 // Symbols should be spaced correctly } - #endregion - - #region Trash - // incl. trashing a published, unpublished content, w/changes // incl. trashing a branch, untrashing a single masked content // including emptying the recycle bin - [Test] public void TrashUnpublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ResetEvents(); @@ -933,8 +920,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); @@ -943,7 +930,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void UntrashUnpublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.MoveToRecycleBin(content); @@ -953,8 +940,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); @@ -964,8 +951,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void TrashPublishedContent() { // does 1) unpublish and 2) trash - - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -975,11 +961,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=m", _events[i++].ToString()); m++; - //Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content.Id), _events[i++].ToString()); + + // Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content.Id), _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); } @@ -987,8 +974,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void UntrashPublishedContent() { // same as unpublished as it's been unpublished - - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -999,8 +985,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; + // trashing did /pm- (published, masked) // un-trashing cannot re-publish so /u?- (not-published, unchanged) // but because we *have* to change state to unpublished, it's /ux- and not /uu- @@ -1012,7 +999,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TrashPublishedContentWithChanges() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -1024,32 +1011,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content.Id}.p=m", _events[i++].ToString()); m++; - //Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content.Id), _events[i++].ToString()); + + // Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content.Id), _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content.Id}", _events[i].ToString()); } [Test] public void TrashContentBranch() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); ResetEvents(); ContentService.MoveToRecycleBin(content1); Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=m", _events[i++].ToString()); @@ -1063,9 +1052,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[3].Id}.u=u", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content5C[0].Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); - m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] @@ -1073,7 +1062,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.MoveToRecycleBin(content); @@ -1083,8 +1072,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content.Id}", _events[i].ToString()); @@ -1095,11 +1084,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.MoveToRecycleBin(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.MoveToRecycleBin(content2); @@ -1108,13 +1097,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(3, _msgCount); Assert.AreEqual(4, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content1.Id}", _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content2.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content1.Id}", _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content2.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] @@ -1122,26 +1113,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); ContentService.MoveToRecycleBin(content1); ResetEvents(); - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content5C[1].Id}", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content5C[0].Id}", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content1C[3].Id}", _events[i++].ToString()); @@ -1157,16 +1149,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content1.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content1.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } - #endregion - - #region Delete - [Test] public void DeleteUnpublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ResetEvents(); @@ -1174,8 +1163,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content.Id}", _events[i].ToString()); @@ -1184,7 +1173,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void DeletePublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); @@ -1193,8 +1182,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content.Id}", _events[i].ToString()); @@ -1203,7 +1192,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void DeletePublishedContentWithChanges() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); content.Properties.First().SetValue("changed"); @@ -1214,8 +1203,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content.Id}", _events[i].ToString()); @@ -1224,10 +1213,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void DeleteMaskedPublishedContent() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); @@ -1237,8 +1226,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content2.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content2.Id}", _events[i].ToString()); @@ -1247,23 +1236,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void DeleteBranch() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); // get them before they are deleted! - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); ResetEvents(); ContentService.Delete(content1); Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content5C[1].Id}", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content5C[0].Id}", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Remove/{content1C[3].Id}", _events[i++].ToString()); @@ -1279,18 +1269,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Remove/{content1.Id}", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/Remove/{content1.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } - #endregion - - #region Move - [Test] public void MoveUnpublishedContentUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ResetEvents(); @@ -1298,8 +1285,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1308,10 +1295,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ResetEvents(); @@ -1319,8 +1306,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); @@ -1329,12 +1316,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentWithChangesUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); content1.Properties.First().SetValue("changed"); ContentService.Save(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ResetEvents(); @@ -1342,8 +1329,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); @@ -1352,9 +1339,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveUnpublishedContentUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1363,8 +1350,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1373,12 +1360,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveUnpublishedContentUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1388,8 +1375,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1398,10 +1385,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1410,8 +1397,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1420,13 +1407,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(content2.Id); + IContent content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1436,8 +1423,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1446,12 +1433,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentWithChangesUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); content1.Properties.First().SetValue("changed"); ContentService.Save(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1460,8 +1447,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1470,15 +1457,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MovePublishedContentWithChangesUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); content1.Properties.First().SetValue("changed"); ContentService.Save(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(content2.Id); + IContent content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1488,8 +1475,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i].ToString()); @@ -1498,14 +1485,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); @@ -1514,8 +1501,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1524,17 +1511,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); - var content4 = CreateContent(content3.Id); + IContent content4 = CreateContent(content3.Id); Assert.IsNotNull(content4); ContentService.SaveAndPublish(content4); ContentService.Unpublish(content3); @@ -1544,8 +1531,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1554,16 +1541,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentWithChangesUnderPublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); content2.Properties.First().SetValue("changed"); ContentService.Save(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); @@ -1572,8 +1559,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=p", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1582,19 +1569,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentWithChangesUnderMasked() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); content2.Properties.First().SetValue("changed"); ContentService.Save(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); - var content4 = CreateContent(content3.Id); + IContent content4 = CreateContent(content3.Id); Assert.IsNotNull(content4); ContentService.SaveAndPublish(content4); ContentService.Unpublish(content3); @@ -1604,8 +1591,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1614,14 +1601,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ResetEvents(); @@ -1629,8 +1616,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1639,16 +1626,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveMaskedPublishedContentWithChangesUnderUnpublished() { - var content1 = CreateContent(); + IContent content1 = CreateContent(); Assert.IsNotNull(content1); ContentService.SaveAndPublish(content1); - var content2 = CreateContent(content1.Id); + IContent content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); content2.Properties.First().SetValue("changed"); ContentService.Save(content2); ContentService.Unpublish(content1); - var content3 = CreateContent(); + IContent content3 = CreateContent(); Assert.IsNotNull(content3); ResetEvents(); @@ -1656,8 +1643,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content2.Id}.p=m", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content2.Id}", _events[i].ToString()); @@ -1666,10 +1653,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void MoveContentBranchUnderUnpublished() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ResetEvents(); @@ -1677,13 +1664,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=m", _events[i++].ToString()); @@ -1699,29 +1687,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchUnderPublished() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1730,13 +1705,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=p", _events[i++].ToString()); @@ -1752,32 +1728,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchUnderMasked() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(content2.Id); + IContent content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1787,13 +1750,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=m", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=m", _events[i++].ToString()); @@ -1809,29 +1773,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchBackFromPublished() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); @@ -1842,13 +1793,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=p", _events[i++].ToString()); @@ -1864,29 +1816,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchBackFromUnpublished() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.Move(content1, content2.Id); @@ -1896,13 +1835,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=p", _events[i++].ToString()); @@ -1918,32 +1858,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } [Test] public void MoveContentBranchBackFromMasked() { - var content1 = CreateBranch(); + IContent content1 = CreateBranch(); Assert.IsNotNull(content1); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.SaveAndPublish(content2); - var content3 = CreateContent(content2.Id); + IContent content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); ContentService.SaveAndPublish(content3); ContentService.Unpublish(content2); @@ -1955,13 +1882,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; - var content1C = Children(content1).ToArray(); - var content2C = Children(content1C[0]).ToArray(); - var content3C = Children(content1C[1]).ToArray(); - var content4C = Children(content1C[2]).ToArray(); - var content5C = Children(content1C[3]).ToArray(); + int i = 0; + int m = 0; + IContent[] content1C = Children(content1).ToArray(); + IContent[] content2C = Children(content1C[0]).ToArray(); + IContent[] content3C = Children(content1C[1]).ToArray(); + IContent[] content4C = Children(content1C[2]).ToArray(); + IContent[] content5C = Children(content1C[3]).ToArray(); +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content1C[0].Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content2C[0].Id}.p=p", _events[i++].ToString()); @@ -1977,39 +1905,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{content5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{content1.Id}", _events[i++].ToString()); - /* - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content1C[2].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content1C[3].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content2C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RefreshPublished,Refresh/{1}", m, content4C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/RemovePublished,Refresh/{1}", m, content5C[0].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content2C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content3C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content4C[1].Id), _events[i++].ToString()); - Assert.AreEqual(string.Format("{0:000}: ContentCacheRefresher/Refresh/{1}", m, content5C[1].Id), _events[i++].ToString()); - */ +#pragma warning restore SA1003 // Symbols should be spaced correctly } - #endregion - - #region Copy - [Test] public void CopyUnpublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ResetEvents(); - var copy = ContentService.Copy(content, Constants.System.Root, false); + IContent copy = ContentService.Copy(content, Constants.System.Root, false); Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{copy.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{copy.Id}", _events[i].ToString()); @@ -2018,17 +1929,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void CopyPublishedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); ResetEvents(); - var copy = ContentService.Copy(content, Constants.System.Root, false); + IContent copy = ContentService.Copy(content, Constants.System.Root, false); Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{copy.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{copy.Id}", _events[i].ToString()); @@ -2037,20 +1948,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void CopyMaskedContent() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); - var content2 = CreateContent(); + IContent content2 = CreateContent(); Assert.IsNotNull(content2); ContentService.Move(content, content2.Id); ResetEvents(); - var copy = ContentService.Copy(content, Constants.System.Root, false); + IContent copy = ContentService.Copy(content, Constants.System.Root, false); Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{copy.Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{copy.Id}", _events[i].ToString()); @@ -2059,23 +1970,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void CopyBranch() { - var content = CreateBranch(); + IContent content = CreateBranch(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); ResetEvents(); - var copy = ContentService.Copy(content, Constants.System.Root, false); + IContent copy = ContentService.Copy(content, Constants.System.Root, false); - var copyC = Children(copy).ToArray(); - var copy2C = Children(copyC[0]).ToArray(); - var copy3C = Children(copyC[1]).ToArray(); - var copy4C = Children(copyC[2]).ToArray(); - var copy5C = Children(copyC[3]).ToArray(); + IContent[] copyC = Children(copy).ToArray(); + IContent[] copy2C = Children(copyC[0]).ToArray(); + IContent[] copy3C = Children(copyC[1]).ToArray(); + IContent[] copy4C = Children(copyC[2]).ToArray(); + IContent[] copy5C = Children(copyC[3]).ToArray(); Assert.AreEqual(14, _msgCount); Assert.AreEqual(14, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{copy.Id}.u=u", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{copyC[0].Id}.u=u", _events[i++].ToString()); Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{copy2C[0].Id}.u=u", _events[i++].ToString()); @@ -2091,27 +2003,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual($"{m:000}: ContentRepository/Refresh/{copy5C[1].Id}.u=u", _events[i++].ToString()); m++; Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshBranch/{copy.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } - #endregion - - #region Rollback - [Test] public void Rollback() { - var content = CreateContent(); + IContent content = CreateContent(); Assert.IsNotNull(content); ContentService.SaveAndPublish(content); - var v1 = content.VersionId; + int v1 = content.VersionId; content.Properties.First().SetValue("changed"); ContentService.SaveAndPublish(content); - var v2 = content.VersionId; + int v2 = content.VersionId; content.Properties.First().SetValue("again"); ContentService.SaveAndPublish(content); - var v3 = content.VersionId; + int v3 = content.VersionId; Console.WriteLine(v1); Console.WriteLine(v2); @@ -2123,20 +2032,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, _msgCount); Assert.AreEqual(2, _events.Count); - var i = 0; - var m = 0; + int i = 0; + int m = 0; +#pragma warning disable SA1003 // Symbols should be spaced correctly (suppression necessary and justified here as it's used in an interpolated string format. Assert.AreEqual($"{m++:000}: ContentRepository/Refresh/{content.Id}.p=p", _events[i++].ToString()); Assert.AreEqual($"{m:000}: ContentCacheRefresher/RefreshNode/{content.Id}", _events[i].ToString()); +#pragma warning restore SA1003 // Symbols should be spaced correctly } - #endregion - - #region Misc - [Test] public void ContentRemembers() { - var content = ContentService.GetRootContent().FirstOrDefault(); + IContent content = ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); ContentService.Save(content); @@ -2153,23 +2060,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } [Test] - public void HasInitialContent() - { - Assert.AreEqual(4, ContentService.Count()); - } - - #endregion - - #region TODO - - // all content type events - - #endregion + public void HasInitialContent() => Assert.AreEqual(4, ContentService.Count()); public class LocalServerMessenger : ServerMessengerBase { - public LocalServerMessenger() : base(false) - { } + public LocalServerMessenger() + : base(false) + { + } protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) { diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceEventTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceEventTests.cs index 83d669a06e..3a5d90b24f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceEventTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceEventTests.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; using Umbraco.Core.Configuration.Models; @@ -14,15 +17,19 @@ using Umbraco.Tests.Testing; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { [TestFixture] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, + [UmbracoTest( + Database = UmbracoTestOptions.Database.NewSchemaPerTest, PublishedRepositoryEvents = true, WithApplication = true, Logger = UmbracoTestOptions.Logger.Console)] public class ContentServiceEventTests : UmbracoIntegrationTest { private IContentTypeService ContentTypeService => GetRequiredService(); + private ContentService ContentService => (ContentService)GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); private GlobalSettings _globalSettings; @@ -33,6 +40,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { ContentRepositoryBase.ThrowOnWarning = true; _globalSettings = new GlobalSettings(); + // TODO: remove this once IPublishedSnapShotService has been implemented with nucache. global::Umbraco.Core.Services.Implement.ContentTypeService.ClearScopeEvents(); CreateTestData(); @@ -40,7 +48,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void CreateTestData() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // else, FK violation on contentType! _contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); @@ -48,10 +56,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } [TearDown] - public void Teardown() - { - ContentRepositoryBase.ThrowOnWarning = false; - } + public void Teardown() => ContentRepositoryBase.ThrowOnWarning = false; [Test] public void Saving_Culture() @@ -59,8 +64,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(new Language(_globalSettings, "fr-FR")); _contentType.Variations = ContentVariation.Culture; - foreach (var propertyType in _contentType.PropertyTypes) + foreach (IPropertyType propertyType in _contentType.PropertyTypes) + { propertyType.Variations = ContentVariation.Culture; + } + ContentTypeService.Save(_contentType); IContent document = new Content("content", -1, _contentType); @@ -68,7 +76,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services document.SetCultureName("bonjour", "fr-FR"); ContentService.Save(document); - //re-get - dirty properties need resetting + // re-get - dirty properties need resetting document = ContentService.GetById(document.Id); // properties: title, bodyText, keywords, description @@ -76,7 +84,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaving(IContentService sender, ContentSavingEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.AreSame(document, saved); @@ -86,7 +94,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaved(IContentService sender, ContentSavedEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.AreSame(document, saved); @@ -114,7 +122,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaving(IContentService sender, ContentSavingEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.IsTrue(document.GetValue("title").IsNullOrWhiteSpace()); @@ -123,12 +131,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaved(IContentService sender, ContentSavedEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.AreSame("title", document.GetValue("title")); - //we're only dealing with invariant here - var propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null); + // we're only dealing with invariant here + IPropertyValue propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null); Assert.AreEqual("title", propValue.EditedValue); Assert.IsNull(propValue.PublishedValue); @@ -153,8 +161,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(new Language(_globalSettings, "fr-FR")); _contentType.Variations = ContentVariation.Culture; - foreach (var propertyType in _contentType.PropertyTypes) + foreach (IPropertyType propertyType in _contentType.PropertyTypes) + { propertyType.Variations = ContentVariation.Culture; + } + ContentTypeService.Save(_contentType); IContent document = new Content("content", -1, _contentType); @@ -165,12 +176,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsFalse(document.IsCulturePublished("fr-FR")); Assert.IsFalse(document.IsCulturePublished("en-US")); - //re-get - dirty properties need resetting + // re-get - dirty properties need resetting document = ContentService.GetById(document.Id); void OnPublishing(IContentService sender, ContentPublishingEventArgs e) { - var publishing = e.PublishedEntities.First(); + IContent publishing = e.PublishedEntities.First(); Assert.AreSame(document, publishing); @@ -180,7 +191,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnPublished(IContentService sender, ContentPublishedEventArgs e) { - var published = e.PublishedEntities.First(); + IContent published = e.PublishedEntities.First(); Assert.AreSame(document, published); @@ -214,7 +225,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaving(IContentService sender, ContentSavingEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.IsTrue(document.GetValue("title").IsNullOrWhiteSpace()); @@ -223,12 +234,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaved(IContentService sender, ContentSavedEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.AreSame("title", document.GetValue("title")); // We're only dealing with invariant here. - var propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null); + IPropertyValue propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null); Assert.AreEqual("title", propValue.EditedValue); Assert.AreEqual("title", propValue.PublishedValue); @@ -253,13 +264,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Publishing_Set_Mandatory_Value() { - var titleProperty = _contentType.PropertyTypes.First(x => x.Alias == "title"); + IPropertyType titleProperty = _contentType.PropertyTypes.First(x => x.Alias == "title"); titleProperty.Mandatory = true; // make this required! ContentTypeService.Save(_contentType); IContent document = new Content("content", -1, _contentType); - var result = ContentService.SaveAndPublish(document); + PublishResult result = ContentService.SaveAndPublish(document); Assert.IsFalse(result.Success); Assert.AreEqual("title", result.InvalidProperties.First().Alias); @@ -269,7 +280,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnSaving(IContentService sender, ContentSavingEventArgs e) { - var saved = e.SavedEntities.First(); + IContent saved = e.SavedEntities.First(); Assert.IsTrue(document.GetValue("title").IsNullOrWhiteSpace()); @@ -283,7 +294,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services try { result = ContentService.SaveAndPublish(document); - Assert.IsTrue(result.Success); //will succeed now because we were able to specify the required value in the Saving event + Assert.IsTrue(result.Success); // will succeed now because we were able to specify the required value in the Saving event } finally { @@ -297,8 +308,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(new Language(_globalSettings, "fr-FR")); _contentType.Variations = ContentVariation.Culture; - foreach (var propertyType in _contentType.PropertyTypes) + foreach (IPropertyType propertyType in _contentType.PropertyTypes) + { propertyType.Variations = ContentVariation.Culture; + } + ContentTypeService.Save(_contentType); var contentService = (ContentService)ContentService; @@ -311,12 +325,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(document.IsCulturePublished("fr-FR")); Assert.IsTrue(document.IsCulturePublished("en-US")); - //re-get - dirty properties need resetting + // re-get - dirty properties need resetting document = contentService.GetById(document.Id); void OnPublishing(IContentService sender, ContentPublishingEventArgs e) { - var publishing = e.PublishedEntities.First(); + IContent publishing = e.PublishedEntities.First(); Assert.AreSame(document, publishing); @@ -329,7 +343,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services void OnPublished(IContentService sender, ContentPublishedEventArgs e) { - var published = e.PublishedEntities.First(); + IContent published = e.PublishedEntities.First(); Assert.AreSame(document, published); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePerformanceTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePerformanceTest.cs index 072fbe04a3..e48f1fe52b 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePerformanceTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePerformanceTest.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; @@ -10,6 +13,7 @@ using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; @@ -23,27 +27,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class ContentServicePerformanceTest : UmbracoIntegrationTest { protected DocumentRepository DocumentRepository => (DocumentRepository)GetRequiredService(); + protected IFileService FileService => GetRequiredService(); + protected IContentTypeService ContentTypeService => GetRequiredService(); + protected IContentService ContentService => GetRequiredService(); protected IContentType ContentType { get; set; } [SetUp] - public void SetUpData() - { - CreateTestData(); - } + public void SetUpData() => CreateTestData(); [Test] - public void Profiler() - { - Assert.IsInstanceOf(GetRequiredService()); - } + public void Profiler() => Assert.IsInstanceOf(GetRequiredService()); private static IProfilingLogger GetTestProfilingLogger() { - var profiler = new TestProfiler(); return new ProfilingLogger(new NullLogger(), profiler); } @@ -51,7 +51,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Retrieving_All_Content_In_Site() { - //NOTE: Doing this the old 1 by 1 way and based on the results of the ContentServicePerformanceTest.Retrieving_All_Content_In_Site + // NOTE: Doing this the old 1 by 1 way and based on the results of the ContentServicePerformanceTest.Retrieving_All_Content_In_Site // the old way takes 143795ms, the new above way takes: // 14249ms // @@ -62,13 +62,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // // ... NOPE, made even more nice changes, it is now... // 4452ms !!!!!!! - - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType1 = ContentTypeBuilder.CreateTextPageContentType("test1", "test1", defaultTemplateId: template.Id); - var contentType2 = ContentTypeBuilder.CreateTextPageContentType("test2", "test2", defaultTemplateId: template.Id); - var contentType3 = ContentTypeBuilder.CreateTextPageContentType("test3", "test3", defaultTemplateId: template.Id); + ContentType contentType1 = ContentTypeBuilder.CreateTextPageContentType("test1", "test1", defaultTemplateId: template.Id); + ContentType contentType2 = ContentTypeBuilder.CreateTextPageContentType("test2", "test2", defaultTemplateId: template.Id); + ContentType contentType3 = ContentTypeBuilder.CreateTextPageContentType("test3", "test3", defaultTemplateId: template.Id); ContentTypeService.Save(new[] { contentType1, contentType2, contentType3 }); contentType1.AllowedContentTypes = new[] { @@ -87,13 +86,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services }; ContentTypeService.Save(new[] { contentType1, contentType2, contentType3 }); - var roots = ContentBuilder.CreateTextpageContent(contentType1, -1, 10); + IEnumerable roots = ContentBuilder.CreateTextpageContent(contentType1, -1, 10); ContentService.Save(roots); - foreach (var root in roots) + foreach (Content root in roots) { - var item1 = ContentBuilder.CreateTextpageContent(contentType1, root.Id, 10); - var item2 = ContentBuilder.CreateTextpageContent(contentType2, root.Id, 10); - var item3 = ContentBuilder.CreateTextpageContent(contentType3, root.Id, 10); + IEnumerable item1 = ContentBuilder.CreateTextpageContent(contentType1, root.Id, 10); + IEnumerable item2 = ContentBuilder.CreateTextpageContent(contentType2, root.Id, 10); + IEnumerable item3 = ContentBuilder.CreateTextpageContent(contentType3, root.Id, 10); ContentService.Save(item1.Concat(item2).Concat(item3)); } @@ -104,10 +103,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { TestProfiler.Enable(); total.AddRange(ContentService.GetRootContent()); - foreach (var content in total.ToArray()) + foreach (IContent content in total.ToArray()) { - total.AddRange(ContentService.GetPagedDescendants(content.Id, 0, int.MaxValue, out var _)); + total.AddRange(ContentService.GetPagedDescendants(content.Id, 0, int.MaxValue, out long _)); } + TestProfiler.Disable(); StaticApplicationLogging.Logger.LogInformation("Returned {Total} items", total.Count); } @@ -117,14 +117,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Creating_100_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); // Act - Stopwatch watch = Stopwatch.StartNew(); + var watch = Stopwatch.StartNew(); ContentService.Save(pages, 0); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("100 content items saved in {0} ms", elapsed); @@ -136,14 +136,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Creating_1000_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); // Act - Stopwatch watch = Stopwatch.StartNew(); + var watch = Stopwatch.StartNew(); ContentService.Save(pages, 0); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("100 content items saved in {0} ms", elapsed); @@ -155,20 +155,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Getting_100_Uncached_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); ContentService.Save(pages, 0); - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) + IScopeProvider provider = ScopeProvider; + using (IScope scope = provider.CreateScope()) { - var repository = DocumentRepository; + DocumentRepository repository = DocumentRepository; // Act - Stopwatch watch = Stopwatch.StartNew(); - var contents = repository.GetMany(); + var watch = Stopwatch.StartNew(); + IEnumerable contents = repository.GetMany(); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("100 content items retrieved in {0} ms without caching", elapsed); @@ -176,33 +176,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(contents.Any(x => x.HasIdentity == false), Is.False); Assert.That(contents.Any(x => x == null), Is.False); } - - } [Test] public void Getting_1000_Uncached_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); ContentService.Save(pages, 0); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = DocumentRepository; + DocumentRepository repository = DocumentRepository; // Act - Stopwatch watch = Stopwatch.StartNew(); - var contents = repository.GetMany(); + var watch = Stopwatch.StartNew(); + IEnumerable contents = repository.GetMany(); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("1000 content items retrieved in {0} ms without caching", elapsed); // Assert - //Assert.That(contents.Any(x => x.HasIdentity == false), Is.False); - //Assert.That(contents.Any(x => x == null), Is.False); + // Assert.That(contents.Any(x => x.HasIdentity == false), Is.False); + // Assert.That(contents.Any(x => x == null), Is.False); } } @@ -210,21 +208,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Getting_100_Cached_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100); ContentService.Save(pages, 0); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = DocumentRepository; + DocumentRepository repository = DocumentRepository; // Act - var contents = repository.GetMany(); + IEnumerable contents = repository.GetMany(); - Stopwatch watch = Stopwatch.StartNew(); - var contentsCached = repository.GetMany(); + var watch = Stopwatch.StartNew(); + IEnumerable contentsCached = repository.GetMany(); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("100 content items retrieved in {0} ms with caching", elapsed); @@ -239,38 +237,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Getting_1000_Cached_Items() { // Arrange - var contentType = ContentTypeService.Get(ContentType.Id); - var pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); + IContentType contentType = ContentTypeService.Get(ContentType.Id); + IEnumerable pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000); ContentService.Save(pages, 0); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = DocumentRepository; + DocumentRepository repository = DocumentRepository; // Act - var contents = repository.GetMany(); + IEnumerable contents = repository.GetMany(); - Stopwatch watch = Stopwatch.StartNew(); - var contentsCached = repository.GetMany(); + var watch = Stopwatch.StartNew(); + IEnumerable contentsCached = repository.GetMany(); watch.Stop(); - var elapsed = watch.ElapsedMilliseconds; + long elapsed = watch.ElapsedMilliseconds; Debug.Print("1000 content items retrieved in {0} ms with caching", elapsed); // Assert - //Assert.That(contentsCached.Any(x => x.HasIdentity == false), Is.False); - //Assert.That(contentsCached.Any(x => x == null), Is.False); - //Assert.That(contentsCached.Count(), Is.EqualTo(contents.Count())); + // Assert.That(contentsCached.Any(x => x.HasIdentity == false), Is.False); + // Assert.That(contentsCached.Any(x => x == null), Is.False); + // Assert.That(contentsCached.Count(), Is.EqualTo(contents.Count())); } } public void CreateTestData() { - - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Create and Save ContentType "textpage" -> ContentType.Id + // Create and Save ContentType "textpage" -> ContentType.Id ContentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); ContentTypeService.Save(ContentType); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs index fccd708286..b890f186b5 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServicePublishBranchTests.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; @@ -18,14 +21,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class ContentServicePublishBranchTests : UmbracoIntegrationTest { private IContentService ContentService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); [TestCase(1)] // use overload w/ culture: "*" [TestCase(2)] // use overload w/ cultures: new [] { "*" } public void Can_Publish_Invariant_Branch(int method) { - CreateTypes(out var iContentType, out _); + CreateTypes(out IContentType iContentType, out _); IContent iRoot = new Content("iroot", -1, iContentType); iRoot.SetValue("ip", "iroot"); @@ -43,17 +48,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // !force = publishes those that are actually published, and have changes // here: root (root is always published) - - var r = SaveAndPublishInvariantBranch(iRoot, false, method).ToArray(); + PublishResult[] r = SaveAndPublishInvariantBranch(iRoot, false, method).ToArray(); // not forcing, ii1 and ii2 not published yet: only root got published - AssertPublishResults(r, x => x.Content.Name, - "iroot"); - AssertPublishResults(r, x => x.Result, - PublishResultType.SuccessPublish); + AssertPublishResults(r, x => x.Content.Name, "iroot"); + AssertPublishResults(r, x => x.Result, PublishResultType.SuccessPublish); // prepare - ContentService.SaveAndPublish(iRoot); ContentService.SaveAndPublish(ii1); @@ -83,19 +84,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // !force = publishes those that are actually published, and have changes // here: nothing - r = SaveAndPublishInvariantBranch(iRoot, false, method).ToArray(); // not forcing, ii12 and ii2, ii21, ii22 not published yet: only root, ii1, ii11 got published - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "ii11"); - AssertPublishResults(r, x => x.Result, + AssertPublishResults(r, x => x.Content.Name, "iroot", "ii1", "ii11"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublishAlready); // prepare - iRoot.SetValue("ip", "changed"); ContentService.Save(iRoot); ii11.SetValue("ip", "changed"); @@ -114,20 +114,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // not forcing, ii12 and ii2, ii21, ii22 not published yet: only root, ii1, ii11 got published r = SaveAndPublishInvariantBranch(iRoot, false, method).ToArray(); - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "ii11"); - AssertPublishResults(r, x => x.Result, + AssertPublishResults(r, x => x.Content.Name, "iroot", "ii1", "ii11"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublish, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublish); // force = publishes everything that has changes // here: ii12, ii2, ii22 - ii21 was published already but masked - r = SaveAndPublishInvariantBranch(iRoot, true, method).ToArray(); - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "ii11", "ii12", "ii2", "ii21", "ii22"); - AssertPublishResults(r, x => x.Result, + AssertPublishResults( + r, + x => x.Content.Name, + "iroot", + "ii1", + "ii11", + "ii12", + "ii2", + "ii21", + "ii22"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublishAlready, @@ -143,9 +153,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Variant_Branch_When_No_Changes_On_Root_All_Cultures() { - CreateTypes(out _, out var vContentType); + CreateTypes(out _, out IContentType vContentType); - //create/publish root + // create/publish root IContent vRoot = new Content("vroot", -1, vContentType, "de"); vRoot.SetCultureName("vroot.de", "de"); vRoot.SetCultureName("vroot.ru", "ru"); @@ -156,7 +166,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services vRoot.SetValue("vp", "vroot.es", "es"); ContentService.SaveAndPublish(vRoot); - //create/publish child + // create/publish child IContent iv1 = new Content("iv1", vRoot, vContentType, "de"); iv1.SetCultureName("iv1.de", "de"); iv1.SetCultureName("iv1.ru", "ru"); @@ -167,11 +177,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services iv1.SetValue("vp", "iv1.es", "es"); ContentService.SaveAndPublish(iv1); - //update the child + // update the child iv1.SetValue("vp", "UPDATED-iv1.de", "de"); ContentService.Save(iv1); - var r = ContentService.SaveAndPublishBranch(vRoot, false).ToArray(); //no culture specified so "*" is used, so all cultures + PublishResult[] r = ContentService.SaveAndPublishBranch(vRoot, false).ToArray(); // no culture specified so "*" is used, so all cultures Assert.AreEqual(PublishResultType.SuccessPublishAlready, r[0].Result); Assert.AreEqual(PublishResultType.SuccessPublishCulture, r[1].Result); } @@ -179,9 +189,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Variant_Branch_When_No_Changes_On_Root_Specific_Culture() { - CreateTypes(out _, out var vContentType); + CreateTypes(out _, out IContentType vContentType); - //create/publish root + // create/publish root IContent vRoot = new Content("vroot", -1, vContentType, "de"); vRoot.SetCultureName("vroot.de", "de"); vRoot.SetCultureName("vroot.ru", "ru"); @@ -192,7 +202,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services vRoot.SetValue("vp", "vroot.es", "es"); ContentService.SaveAndPublish(vRoot); - //create/publish child + // create/publish child IContent iv1 = new Content("iv1", vRoot, vContentType, "de"); iv1.SetCultureName("iv1.de", "de"); iv1.SetCultureName("iv1.ru", "ru"); @@ -203,11 +213,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services iv1.SetValue("vp", "iv1.es", "es"); ContentService.SaveAndPublish(iv1); - //update the child + // update the child iv1.SetValue("vp", "UPDATED-iv1.de", "de"); - var saveResult = ContentService.Save(iv1); + OperationResult saveResult = ContentService.Save(iv1); - var r = ContentService.SaveAndPublishBranch(vRoot, false, "de").ToArray(); + PublishResult[] r = ContentService.SaveAndPublishBranch(vRoot, false, "de").ToArray(); Assert.AreEqual(PublishResultType.SuccessPublishAlready, r[0].Result); Assert.AreEqual(PublishResultType.SuccessPublishCulture, r[1].Result); } @@ -215,7 +225,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Variant_Branch() { - CreateTypes(out _, out var vContentType); + CreateTypes(out _, out IContentType vContentType); IContent vRoot = new Content("vroot", -1, vContentType, "de"); vRoot.SetCultureName("vroot.de", "de"); @@ -253,14 +263,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // !force = publishes those that are actually published, and have changes // here: nothing - - var r = ContentService.SaveAndPublishBranch(vRoot, false).ToArray(); // no culture specified = all cultures + PublishResult[] r = ContentService.SaveAndPublishBranch(vRoot, false).ToArray(); // no culture specified = all cultures // not forcing, iv1 and iv2 not published yet: only root got published - AssertPublishResults(r, x => x.Content.Name, - "vroot.de"); - AssertPublishResults(r, x => x.Result, - PublishResultType.SuccessPublishCulture); + AssertPublishResults(r, x => x.Content.Name, "vroot.de"); + AssertPublishResults(r, x => x.Result, PublishResultType.SuccessPublishCulture); // prepare vRoot.SetValue("ip", "changed"); @@ -269,7 +276,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services vRoot.SetValue("vp", "changed.es", "es"); ContentService.Save(vRoot); // now root has drafts in all cultures - ContentService.SaveAndPublish(iv1, new []{"de", "ru"}); // now iv1 de and ru are published + ContentService.SaveAndPublish(iv1, new[] { "de", "ru" }); // now iv1 de and ru are published iv1.SetValue("ip", "changed"); iv1.SetValue("vp", "changed.de", "de"); @@ -292,9 +299,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services r = ContentService.SaveAndPublishBranch(vRoot, false, "de").ToArray(); // not forcing, iv2 not published yet: only root and iv1 got published - AssertPublishResults(r, x => x.Content.Name, - "vroot.de", "iv1.de"); - AssertPublishResults(r, x => x.Result, + AssertPublishResults(r, x => x.Content.Name, "vroot.de", "iv1.de"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishCulture, PublishResultType.SuccessPublishCulture); @@ -329,8 +337,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // invariant root -> variant -> invariant // variant root -> variant -> invariant // variant root -> invariant -> variant - - CreateTypes(out var iContentType, out var vContentType); + CreateTypes(out IContentType iContentType, out IContentType vContentType); // invariant root -> invariant -> variant iRoot = new Content("iroot", -1, iContentType); @@ -349,7 +356,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.Save(iv11); iv11.SetCultureName("iv11.ru", "ru"); - var xxx = ContentService.SaveAndPublish(iv11, new []{"de", "ru"}); + PublishResult xxx = ContentService.SaveAndPublish(iv11, new[] { "de", "ru" }); Assert.AreEqual("iv11.de", iv11.GetValue("vp", "de", published: true)); Assert.AreEqual("iv11.ru", iv11.GetValue("vp", "ru", published: true)); @@ -363,12 +370,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Mixed_Branch_1() { - Can_Publish_Mixed_Branch(out var iRoot, out var ii1, out var iv11); + Can_Publish_Mixed_Branch(out IContent iRoot, out IContent ii1, out IContent iv11); - var r = ContentService.SaveAndPublishBranch(iRoot, false, "de").ToArray(); - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "iv11.de"); - AssertPublishResults(r, x => x.Result, + PublishResult[] r = ContentService.SaveAndPublishBranch(iRoot, false, "de").ToArray(); + AssertPublishResults(r, x => x.Content.Name, "iroot", "ii1", "iv11.de"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublish, PublishResultType.SuccessPublishCulture); @@ -379,7 +387,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // the invariant child has been published // the variant child has been published for 'de' only - Assert.AreEqual("changed", ii1.GetValue("ip", published: true)); Assert.AreEqual("changed", iv11.GetValue("ip", published: true)); Assert.AreEqual("changed.de", iv11.GetValue("vp", "de", published: true)); @@ -389,12 +396,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_MixedBranch_2() { - Can_Publish_Mixed_Branch(out var iRoot, out var ii1, out var iv11); + Can_Publish_Mixed_Branch(out IContent iRoot, out IContent ii1, out IContent iv11); - var r = ContentService.SaveAndPublishBranch(iRoot, false, new[] { "de", "ru" }).ToArray(); - AssertPublishResults(r, x => x.Content.Name, - "iroot", "ii1", "iv11.de"); - AssertPublishResults(r, x => x.Result, + PublishResult[] r = ContentService.SaveAndPublishBranch(iRoot, false, new[] { "de", "ru" }).ToArray(); + AssertPublishResults(r, x => x.Content.Name, "iroot", "ii1", "iv11.de"); + AssertPublishResults( + r, + x => x.Result, PublishResultType.SuccessPublishAlready, PublishResultType.SuccessPublish, PublishResultType.SuccessPublishCulture); @@ -405,7 +413,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // the invariant child has been published // the variant child has been published for 'de' and 'ru' - Assert.AreEqual("changed", ii1.GetValue("ip", published: true)); Assert.AreEqual("changed", iv11.GetValue("ip", published: true)); Assert.AreEqual("changed.de", iv11.GetValue("vp", "de", published: true)); @@ -415,12 +422,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void AssertPublishResults(PublishResult[] values, Func getter, params T[] expected) { if (expected.Length != values.Length) + { Console.WriteLine(string.Join(", ", values.Select(x => getter(x).ToString()))); + } + Assert.AreEqual(expected.Length, values.Length); - for (var i = 0; i < values.Length; i++) + for (int i = 0; i < values.Length; i++) { - var value = getter(values[i]); + T value = getter(values[i]); Assert.AreEqual(expected[i], value, $"Expected {expected[i]} at {i} but got {value}."); } } @@ -468,10 +478,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services case 1: return ContentService.SaveAndPublishBranch(content, force, culture: "*"); case 2: - return ContentService.SaveAndPublishBranch(content, force, cultures: new [] { "*" }); + return ContentService.SaveAndPublishBranch(content, force, cultures: new[] { "*" }); default: throw new ArgumentOutOfRangeException(nameof(method)); } + // ReSharper restore RedundantArgumentDefaultValue // ReSharper restore ArgumentsStyleOther } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs index 193f343305..b7f3609d89 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTagsTests.cs @@ -1,10 +1,15 @@ -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; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; @@ -15,40 +20,42 @@ using Umbraco.Tests.Testing; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { [TestFixture] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, + [UmbracoTest( + Database = UmbracoTestOptions.Database.NewSchemaPerTest, PublishedRepositoryEvents = true, WithApplication = true, Logger = UmbracoTestOptions.Logger.Console)] public class ContentServiceTagsTests : UmbracoIntegrationTest { private IContentTypeService ContentTypeService => GetRequiredService(); + private IContentService ContentService => GetRequiredService(); + private ITagService TagService => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IJsonSerializer Serializer => GetRequiredService(); + public PropertyEditorCollection PropertyEditorCollection => GetRequiredService(); [SetUp] - public void Setup() - { - ContentRepositoryBase.ThrowOnWarning = true; - } + public void Setup() => ContentRepositoryBase.ThrowOnWarning = true; [TearDown] - public void Teardown() - { - ContentRepositoryBase.ThrowOnWarning = false; - } + public void Teardown() => ContentRepositoryBase.ThrowOnWarning = false; [Test] public void TagsCanBeInvariant() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); @@ -58,16 +65,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content1 = ContentService.GetById(content1.Id); - var enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); + string[] enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); Assert.AreEqual(4, enTags.Length); Assert.Contains("one", enTags); Assert.AreEqual(-1, enTags.IndexOf("plus")); - var tagGroups = TagService.GetAllTags().GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags()) + IEnumerable> tagGroups = TagService.GetAllTags().GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags()) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -77,16 +87,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBeVariant() { - var languageService = LocalizationService; - var language = new LanguageBuilder() + ILocalizationService languageService = LocalizationService; + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); @@ -99,26 +109,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content1 = ContentService.GetById(content1.Id); - var frTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "fr-FR").ToArray(); + string[] frTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "fr-FR").ToArray(); Assert.AreEqual(5, frTags.Length); Assert.Contains("plus", frTags); Assert.AreEqual(-1, frTags.IndexOf("one")); - var enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "en-US").ToArray(); + string[] enTags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "en-US").ToArray(); Assert.AreEqual(4, enTags.Length); Assert.Contains("one", enTags); Assert.AreEqual(-1, enTags.IndexOf("plus")); - var tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags()) + IEnumerable> tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags()) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(2, tagGroups.Count()); - var frTagGroup = tagGroups.FirstOrDefault(x => x.Key == 2); + IGrouping frTagGroup = tagGroups.FirstOrDefault(x => x.Key == 2); Assert.IsNotNull(frTagGroup); Assert.AreEqual(5, frTagGroup.Count()); Assert.IsTrue(frTagGroup.Any(x => x.Text == "plus")); Assert.IsFalse(frTagGroup.Any(x => x.Text == "one")); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == 1); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == 1); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -128,13 +141,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeVariant() { - var enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; + int enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); - var propertyType = CreateAndAddTagsPropertyType(contentType); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + PropertyType propertyType = CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); @@ -147,16 +160,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // no changes content1 = ContentService.GetById(content1.Id); - var tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); + string[] tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); Assert.AreEqual(4, tags.Length); Assert.Contains("one", tags); Assert.AreEqual(-1, tags.IndexOf("plus")); - var tagGroups = TagService.GetAllTags().GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags()) + IEnumerable> tagGroups = TagService.GetAllTags().GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags()) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -179,8 +195,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // tags have been copied from invariant to en-US tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags("*")) + foreach (ITag tag in TagService.GetAllTags("*")) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); enTagGroup = tagGroups.FirstOrDefault(x => x.Key == enId); @@ -193,17 +212,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeInvariant() { - var language = new LanguageBuilder() + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; + int enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); @@ -224,18 +243,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsEmpty(content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "fr-FR")); Assert.IsEmpty(content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "en-US")); - var tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); + string[] tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); Assert.AreEqual(4, tags.Length); Assert.Contains("one", tags); Assert.AreEqual(-1, tags.IndexOf("plus")); // tags have been copied from en-US to invariant, fr-FR tags are gone - var tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags("*")) + IEnumerable> tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags("*")) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -245,18 +267,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeInvariant2() { - var language = new LanguageBuilder() + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; + int enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); - var propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + PropertyType propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); @@ -274,10 +296,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SaveAndPublish(content2); //// pretend we already have invariant values - //using (var scope = ScopeProvider.CreateScope()) - //{ + // using (var scope = ScopeProvider.CreateScope()) + // { // scope.Database.Execute("INSERT INTO [cmsTags] ([tag], [group], [languageId]) SELECT DISTINCT [tag], [group], NULL FROM [cmsTags] WHERE [languageId] IS NOT NULL"); - //} + // } // this should work propertyType.Variations = ContentVariation.Nothing; @@ -287,18 +309,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeInvariantByPropertyType() { - var language = new LanguageBuilder() + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; + int enId = LocalizationService.GetLanguageIdByIsoCode("en-US").Value; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); - var propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + PropertyType propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); @@ -318,18 +340,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsEmpty(content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "fr-FR")); Assert.IsEmpty(content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer, "en-US")); - var tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); + string[] tags = content1.Properties["tags"].GetTagsValue(PropertyEditorCollection, DataTypeService, Serializer).ToArray(); Assert.AreEqual(4, tags.Length); Assert.Contains("one", tags); Assert.AreEqual(-1, tags.IndexOf("plus")); // tags have been copied from en-US to invariant, fr-FR tags are gone - var tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); - foreach (var tag in TagService.GetAllTags("*")) + IEnumerable> tagGroups = TagService.GetAllTags(culture: "*").GroupBy(x => x.LanguageId); + foreach (ITag tag in TagService.GetAllTags("*")) + { Console.WriteLine($"{tag.Group}:{tag.Text} {tag.LanguageId}"); + } + Assert.AreEqual(1, tagGroups.Count()); - var enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); + IGrouping enTagGroup = tagGroups.FirstOrDefault(x => x.Key == null); Assert.IsNotNull(enTagGroup); Assert.AreEqual(4, enTagGroup.Count()); Assert.IsTrue(enTagGroup.Any(x => x.Text == "one")); @@ -339,16 +364,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsCanBecomeInvariantByPropertyTypeAndBackToVariant() { - var language = new LanguageBuilder() + ILanguage language = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(language); // en-US is already there - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); - var propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + PropertyType propertyType = CreateAndAddTagsPropertyType(contentType, ContentVariation.Culture); ContentTypeService.Save(contentType); IContent content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); @@ -371,25 +396,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsAreUpdatedWhenContentIsTrashedAndUnTrashed_One() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "plus" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); // verify - var tags = TagService.GetTagsForEntity(content1.Id); + IEnumerable tags = TagService.GetTagsForEntity(content1.Id); Assert.AreEqual(5, tags.Count()); - var allTags = TagService.GetAllContentTags(); + IEnumerable allTags = TagService.GetAllContentTags(); Assert.AreEqual(5, allTags.Count()); ContentService.MoveToRecycleBin(content1); @@ -398,25 +423,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsAreUpdatedWhenContentIsTrashedAndUnTrashed_All() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "bam" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); // verify - var tags = TagService.GetTagsForEntity(content1.Id); + IEnumerable tags = TagService.GetTagsForEntity(content1.Id); Assert.AreEqual(5, tags.Count()); - var allTags = TagService.GetAllContentTags(); + IEnumerable allTags = TagService.GetAllContentTags(); Assert.AreEqual(5, allTags.Count()); ContentService.Unpublish(content1); @@ -427,25 +452,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Ignore("https://github.com/umbraco/Umbraco-CMS/issues/3821 (U4-8442), will need to be fixed.")] public void TagsAreUpdatedWhenContentIsTrashedAndUnTrashed_Tree() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "plus" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", content1.Id); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", content1.Id); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); // verify - var tags = TagService.GetTagsForEntity(content1.Id); + IEnumerable tags = TagService.GetTagsForEntity(content1.Id); Assert.AreEqual(5, tags.Count()); - var allTags = TagService.GetAllContentTags(); + IEnumerable allTags = TagService.GetAllContentTags(); Assert.AreEqual(5, allTags.Count()); ContentService.MoveToRecycleBin(content1); @@ -499,18 +524,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagsAreUpdatedWhenContentIsUnpublishedAndRePublished() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "bam" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); @@ -522,24 +547,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Ignore("https://github.com/umbraco/Umbraco-CMS/issues/3821 (U4-8442), will need to be fixed.")] public void TagsAreUpdatedWhenContentIsUnpublishedAndRePublished_Tree() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags", "bam" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", content1); + Content content2 = ContentBuilder.CreateSimpleContent(contentType, "Tagged content 2", content1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content2); ContentService.Unpublish(content1); - var tags = TagService.GetTagsForEntity(content1.Id); + IEnumerable tags = TagService.GetTagsForEntity(content1.Id); Assert.AreEqual(0, tags.Count()); // FIXME: tag & tree issue @@ -547,7 +572,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // see similar note above tags = TagService.GetTagsForEntity(content2.Id); Assert.AreEqual(0, tags.Count()); - var allTags = TagService.GetAllContentTags(); + IEnumerable allTags = TagService.GetAllContentTags(); Assert.AreEqual(0, allTags.Count()); content1.PublishCulture(CultureImpact.Invariant); @@ -562,32 +587,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Tag_Data_Bulk_Publish_Operation() { - //Arrange - //set configuration - var dataType = DataTypeService.GetDataType(1041); + // Arrange + // set configuration + IDataType dataType = DataTypeService.GetDataType(1041); dataType.Configuration = new TagConfiguration { Group = "test", StorageType = TagsStorageType.Csv }; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); contentType.AllowedContentTypes = new[] { new ContentTypeSort(new Lazy(() => contentType.Id), 0, contentType.Alias) }; - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.Save(content); - var child1 = ContentBuilder.CreateSimpleContent(contentType, "child 1 content", content.Id); + Content child1 = ContentBuilder.CreateSimpleContent(contentType, "child 1 content", content.Id); child1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello1", "world1", "some1" }); ContentService.Save(child1); - var child2 = ContentBuilder.CreateSimpleContent(contentType, "child 2 content", content.Id); + Content child2 = ContentBuilder.CreateSimpleContent(contentType, "child 2 content", content.Id); child2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello2", "world2" }); ContentService.Save(child2); @@ -595,9 +620,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SaveAndPublishBranch(content, true); // Assert - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(4, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -618,16 +643,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Does_Not_Create_Tag_Data_For_Non_Published_Version() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // create content type with a tag property - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); // create a content with tags and publish - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content); @@ -639,8 +664,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, content.Properties["tags"].GetValue().ToString().Split(',').Distinct().Count()); // but the database still contains the initial two tags - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(4, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -652,16 +677,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Replace_Tag_Data_To_Published_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Arrange - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + // Arrange + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); - + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); // Act content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); @@ -669,8 +693,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.AreEqual(4, content.Properties["tags"].GetValue().ToString().Split(',').Distinct().Count()); - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(4, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -683,14 +707,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Append_Tag_Data_To_Published_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Arrange - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + // Arrange + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content); @@ -700,8 +724,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.AreEqual(5, content.Properties["tags"].GetValue().ToString().Split(',').Distinct().Count()); - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(5, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -714,14 +738,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Remove_Tag_Data_To_Published_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - //Arrange - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + // Arrange + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); CreateAndAddTagsPropertyType(contentType); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "hello", "world", "some", "tags" }); ContentService.SaveAndPublish(content); @@ -731,8 +755,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.AreEqual(2, content.Properties["tags"].GetValue().ToString().Split(',').Distinct().Count()); - var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; - using (var scope = ScopeProvider.CreateScope()) + int propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id; + using (IScope scope = ScopeProvider.CreateScope()) { Assert.AreEqual(2, scope.Database.ExecuteScalar( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", @@ -744,7 +768,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private PropertyType CreateAndAddTagsPropertyType(ContentType contentType, ContentVariation variations = ContentVariation.Nothing) { - var propertyType = new PropertyTypeBuilder() + PropertyType propertyType = new PropertyTypeBuilder() .WithPropertyEditorAlias("test") .WithAlias("tags") .WithDataTypeId(1041) diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTests.cs index c9f8dc5391..a8e251b6b3 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentServiceTests.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; @@ -8,10 +11,12 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Events; using Umbraco.Core.Models; +using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; @@ -35,6 +40,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // TODO: Add test to verify there is only ONE newest document/content in {Constants.DatabaseSchema.Tables.Document} table after updating. // TODO: Add test to delete specific version (with and without deleting prior versions) and versions by date. + + private IDataTypeService DataTypeService => GetRequiredService(); private ILocalizationService LocalizationService => GetRequiredService(); @@ -70,13 +77,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Blueprint() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); + Content blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); blueprint.SetValue("title", "blueprint 1"); blueprint.SetValue("bodyText", "blueprint 2"); blueprint.SetValue("keywords", "blueprint 3"); @@ -84,24 +91,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SaveBlueprint(blueprint); - var found = ContentService.GetBlueprintsForContentTypes().ToArray(); + IContent[] found = ContentService.GetBlueprintsForContentTypes().ToArray(); Assert.AreEqual(1, found.Length); - //ensures it's not found by normal content - var contentFound = ContentService.GetById(found[0].Id); + // ensures it's not found by normal content + IContent contentFound = ContentService.GetById(found[0].Id); Assert.IsNull(contentFound); } [Test] public void Delete_Blueprint() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); + Content blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); blueprint.SetValue("title", "blueprint 1"); blueprint.SetValue("bodyText", "blueprint 2"); blueprint.SetValue("keywords", "blueprint 3"); @@ -111,22 +118,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.DeleteBlueprint(blueprint); - var found = ContentService.GetBlueprintsForContentTypes().ToArray(); + IContent[] found = ContentService.GetBlueprintsForContentTypes().ToArray(); Assert.AreEqual(0, found.Length); } [Test] public void Create_Content_From_Blueprint() { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) + using (IScope scope = ScopeProvider.CreateScope(autoComplete: true)) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); + Content blueprint = ContentBuilder.CreateTextpageContent(contentType, "hello", Constants.System.Root); blueprint.SetValue("title", "blueprint 1"); blueprint.SetValue("bodyText", "blueprint 2"); blueprint.SetValue("keywords", "blueprint 3"); @@ -134,7 +141,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SaveBlueprint(blueprint); - var fromBlueprint = ContentService.CreateContentFromBlueprint(blueprint, "hello world"); + IContent fromBlueprint = ContentService.CreateContentFromBlueprint(blueprint, "hello world"); ContentService.Save(fromBlueprint); Assert.IsTrue(fromBlueprint.HasIdentity); @@ -143,29 +150,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("blueprint 3", fromBlueprint.Properties["keywords"].GetValue()); Assert.AreEqual("blueprint 4", fromBlueprint.Properties["description"].GetValue()); } - } [Test] public void Get_All_Blueprints() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var ct1 = ContentTypeBuilder.CreateTextPageContentType("ct1", defaultTemplateId: template.Id); + ContentType ct1 = ContentTypeBuilder.CreateTextPageContentType("ct1", defaultTemplateId: template.Id); FileService.SaveTemplate(ct1.DefaultTemplate); ContentTypeService.Save(ct1); - var ct2 = ContentTypeBuilder.CreateTextPageContentType("ct2", defaultTemplateId: template.Id); + ContentType ct2 = ContentTypeBuilder.CreateTextPageContentType("ct2", defaultTemplateId: template.Id); FileService.SaveTemplate(ct2.DefaultTemplate); ContentTypeService.Save(ct2); for (int i = 0; i < 10; i++) { - var blueprint = ContentBuilder.CreateTextpageContent(i % 2 == 0 ? ct1 : ct2, "hello" + i, Constants.System.Root); + Content blueprint = ContentBuilder.CreateTextpageContent(i % 2 == 0 ? ct1 : ct2, "hello" + i, Constants.System.Root); ContentService.SaveBlueprint(blueprint); } - var found = ContentService.GetBlueprintsForContentTypes().ToArray(); + IContent[] found = ContentService.GetBlueprintsForContentTypes().ToArray(); Assert.AreEqual(10, found.Length); found = ContentService.GetBlueprintsForContentTypes(ct1.Id).ToArray(); @@ -178,92 +184,103 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Perform_Scheduled_Publishing() { - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langUk); - var ctInvariant = ContentTypeBuilder.CreateBasicContentType("invariantPage"); + ContentType ctInvariant = ContentTypeBuilder.CreateBasicContentType("invariantPage"); ContentTypeService.Save(ctInvariant); - var ctVariant = ContentTypeBuilder.CreateBasicContentType("variantPage"); + ContentType ctVariant = ContentTypeBuilder.CreateBasicContentType("variantPage"); ctVariant.Variations = ContentVariation.Culture; ContentTypeService.Save(ctVariant); - var now = DateTime.Now; + DateTime now = DateTime.Now; - //10x invariant content, half is scheduled to be published in 5 seconds, the other half is scheduled to be unpublished in 5 seconds + // 10x invariant content, half is scheduled to be published in 5 seconds, the other half is scheduled to be unpublished in 5 seconds var invariant = new List(); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c = ContentBuilder.CreateBasicContent(ctInvariant); + Content c = ContentBuilder.CreateBasicContent(ctInvariant); c.Name = "name" + i; if (i % 2 == 0) { - c.ContentSchedule.Add(now.AddSeconds(5), null); //release in 5 seconds - var r = ContentService.Save(c); + c.ContentSchedule.Add(now.AddSeconds(5), null); // release in 5 seconds + OperationResult r = ContentService.Save(c); Assert.IsTrue(r.Success, r.Result.ToString()); } else { - c.ContentSchedule.Add(null, now.AddSeconds(5)); //expire in 5 seconds - var r = ContentService.SaveAndPublish(c); + c.ContentSchedule.Add(null, now.AddSeconds(5)); // expire in 5 seconds + PublishResult r = ContentService.SaveAndPublish(c); Assert.IsTrue(r.Success, r.Result.ToString()); } + invariant.Add(c); } - //10x variant content, half is scheduled to be published in 5 seconds, the other half is scheduled to be unpublished in 5 seconds + // 10x variant content, half is scheduled to be published in 5 seconds, the other half is scheduled to be unpublished in 5 seconds var variant = new List(); - var alternatingCulture = langFr.IsoCode; - for (var i = 0; i < 10; i++) + string alternatingCulture = langFr.IsoCode; + for (int i = 0; i < 10; i++) { - var c = ContentBuilder.CreateBasicContent(ctVariant); + Content c = ContentBuilder.CreateBasicContent(ctVariant); c.SetCultureName("name-uk" + i, langUk.IsoCode); c.SetCultureName("name-fr" + i, langFr.IsoCode); if (i % 2 == 0) { - c.ContentSchedule.Add(alternatingCulture, now.AddSeconds(5), null); //release in 5 seconds - var r = ContentService.Save(c); + c.ContentSchedule.Add(alternatingCulture, now.AddSeconds(5), null); // release in 5 seconds + OperationResult r = ContentService.Save(c); Assert.IsTrue(r.Success, r.Result.ToString()); alternatingCulture = alternatingCulture == langFr.IsoCode ? langUk.IsoCode : langFr.IsoCode; } else { - c.ContentSchedule.Add(alternatingCulture, null, now.AddSeconds(5)); //expire in 5 seconds - var r = ContentService.SaveAndPublish(c); + c.ContentSchedule.Add(alternatingCulture, null, now.AddSeconds(5)); // expire in 5 seconds + PublishResult r = ContentService.SaveAndPublish(c); Assert.IsTrue(r.Success, r.Result.ToString()); } + variant.Add(c); } - var runSched = ContentService.PerformScheduledPublish( - now.AddMinutes(1)).ToList(); //process anything scheduled before a minute from now + now.AddMinutes(1)).ToList(); // process anything scheduled before a minute from now - //this is 21 because the test data installed before this test runs has a scheduled item! + // this is 21 because the test data installed before this test runs has a scheduled item! Assert.AreEqual(21, runSched.Count); - Assert.AreEqual(20, runSched.Count(x => x.Success), + Assert.AreEqual( + 20, + runSched.Count(x => x.Success), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - Assert.AreEqual(5, runSched.Count(x => x.Result == PublishResultType.SuccessPublish), + Assert.AreEqual( + 5, + runSched.Count(x => x.Result == PublishResultType.SuccessPublish), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - Assert.AreEqual(5, runSched.Count(x => x.Result == PublishResultType.SuccessUnpublish), + Assert.AreEqual( + 5, + runSched.Count(x => x.Result == PublishResultType.SuccessUnpublish), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - Assert.AreEqual(5, runSched.Count(x => x.Result == PublishResultType.SuccessPublishCulture), + Assert.AreEqual( + 5, + runSched.Count(x => x.Result == PublishResultType.SuccessPublishCulture), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - Assert.AreEqual(5, runSched.Count(x => x.Result == PublishResultType.SuccessUnpublishCulture), + Assert.AreEqual( + 5, + runSched.Count(x => x.Result == PublishResultType.SuccessUnpublishCulture), string.Join(Environment.NewLine, runSched.Select(x => $"{x.Entity.Name} - {x.Result}"))); - //re-run the scheduled publishing, there should be no results + // re-run the scheduled publishing, there should be no results runSched = ContentService.PerformScheduledPublish( now.AddMinutes(1)).ToList(); @@ -276,20 +293,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Arrange // Act - var content = ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); content.ContentSchedule.Add(null, DateTime.Now.AddHours(2)); ContentService.Save(content, Constants.Security.SuperUserId); Assert.AreEqual(1, content.ContentSchedule.FullSchedule.Count); content = ContentService.GetById(content.Id); - var sched = content.ContentSchedule.FullSchedule; + IReadOnlyList sched = content.ContentSchedule.FullSchedule; Assert.AreEqual(1, sched.Count); Assert.AreEqual(1, sched.Count(x => x.Culture == string.Empty)); content.ContentSchedule.Clear(ContentScheduleAction.Expire); ContentService.Save(content, Constants.Security.SuperUserId); - // Assert content = ContentService.GetById(content.Id); sched = content.ContentSchedule.FullSchedule; @@ -302,18 +318,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); - for (var i = 0; i < 20; i++) + IContent content = ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + for (int i = 0; i < 20; i++) { content.SetValue("bodyText", "hello world " + Guid.NewGuid()); ContentService.SaveAndPublish(content); } // Assert - var allVersions = ContentService.GetVersionIds(content.Id, int.MaxValue); + IEnumerable allVersions = ContentService.GetVersionIds(content.Id, int.MaxValue); Assert.AreEqual(21, allVersions.Count()); - var topVersions = ContentService.GetVersionIds(content.Id, 4); + IEnumerable topVersions = ContentService.GetVersionIds(content.Id, 4); Assert.AreEqual(4, topVersions.Count()); } @@ -323,12 +339,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Arrange // Act var results = new List(); - for (var i = 0; i < 20; i++) + for (int i = 0; i < 20; i++) { results.Add(ContentService.CreateAndSave("Test", Constants.System.Root, "umbTextpage", 0)); } - var sortedGet = ContentService.GetByIds(new[] {results[10].Id, results[5].Id, results[12].Id}).ToArray(); + IContent[] sortedGet = ContentService.GetByIds(new[] { results[10].Id, results[5].Id, results[12].Id }).ToArray(); // Assert Assert.AreEqual(sortedGet[0].Id, results[10].Id); @@ -354,14 +370,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Count_By_Content_Type() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); // Act - for (var i = 0; i < 20; i++) + for (int i = 0; i < 20; i++) { ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); } @@ -374,12 +390,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Count_Children() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var parent = ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); + IContent parent = ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); // Act for (int i = 0; i < 20; i++) @@ -395,12 +411,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Count_Descendants() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbBlah", "test Doc Type", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var parent = ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); + IContent parent = ContentService.CreateAndSave("Test", Constants.System.Root, "umbBlah", Constants.Security.SuperUserId); // Act IContent current = parent; @@ -419,7 +435,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Arrange // Act var current = new Mock(); - var res = ContentService.GetAncestors(current.Object); + IEnumerable res = ContentService.GetAncestors(current.Object); // Assert Assert.IsEmpty(res); @@ -430,7 +446,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.Create("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); // Assert Assert.That(content, Is.Not.Null); @@ -442,30 +458,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.Create("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Test", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); // Assert Assert.That(content, Is.Not.Null); Assert.That(content.HasIdentity, Is.False); } - [Test] public void Can_Create_Content_Without_Explicitly_Set_User() { // Arrange // Act - var content = ContentService.Create("Test", Constants.System.Root, "umbTextpage"); + IContent content = ContentService.Create("Test", Constants.System.Root, "umbTextpage"); // Assert Assert.That(content, Is.Not.Null); Assert.That(content.HasIdentity, Is.False); - Assert.That(content.CreatorId, Is.EqualTo(Constants.Security.SuperUserId)); //Default to -1 aka SuperUser (unknown) since we didn't explicitly set this in the Create call + Assert.That(content.CreatorId, Is.EqualTo(Constants.Security.SuperUserId)); // Default to -1 aka SuperUser (unknown) since we didn't explicitly set this in the Create call } [Test] public void Can_Save_New_Content_With_Explicit_User() { - var user = new UserBuilder().Build(); + User user = new UserBuilder().Build(); UserService.Save(user); var content = new Content("Test", Constants.System.Root, ContentTypeService.Get("umbTextpage")); @@ -478,12 +493,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } [Test] - public void Cannot_Create_Content_With_Non_Existing_ContentType_Alias() - { - // Arrange - // Act & Assert + public void Cannot_Create_Content_With_Non_Existing_ContentType_Alias() => Assert.Throws(() => ContentService.Create("Test", Constants.System.Root, "umbAliasDoesntExist")); - } [Test] public void Cannot_Save_Content_With_Empty_Name() @@ -500,7 +511,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Assert Assert.That(content, Is.Not.Null); @@ -512,7 +523,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var content = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); + IContent content = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); // Assert Assert.That(content, Is.Not.Null); @@ -535,33 +546,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_All_Versions_Of_Content() { - var parent = ContentService.GetById(Textpage.Id); + IContent parent = ContentService.GetById(Textpage.Id); Assert.IsFalse(parent.Published); ContentService.SaveAndPublish(parent); // publishing parent, so Text Page 2 can be updated. - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); Assert.IsFalse(content.Published); var versions = ContentService.GetVersions(Subpage.Id).ToList(); Assert.AreEqual(1, versions.Count); - var version1 = content.VersionId; + int version1 = content.VersionId; Console.WriteLine($"1 e={content.VersionId} p={content.PublishedVersionId}"); content.Name = "Text Page 2 Updated"; content.SetValue("author", "Jane Doe"); ContentService.SaveAndPublish(content); // publishes the current version, creates a version - var version2 = content.VersionId; + int version2 = content.VersionId; Console.WriteLine($"2 e={content.VersionId} p={content.PublishedVersionId}"); content.Name = "Text Page 2 ReUpdated"; content.SetValue("author", "Bob Hope"); ContentService.SaveAndPublish(content); // publishes again, creates a version - var version3 = content.VersionId; + int version3 = content.VersionId; Console.WriteLine($"3 e={content.VersionId} p={content.PublishedVersionId}"); - var content1 = ContentService.GetById(content.Id); + IContent content1 = ContentService.GetById(content.Id); Assert.AreEqual("Bob Hope", content1.GetValue("author")); Assert.AreEqual("Bob Hope", content1.GetValue("author", published: true)); @@ -584,8 +595,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // p is always the same, published version // e is changing, actual version we're loading Console.WriteLine(); - foreach (var version in ((IEnumerable) versions).Reverse()) - Console.WriteLine($"+ e={((Content) version).VersionId} p={((Content) version).PublishedVersionId}"); + foreach (IContent version in ((IEnumerable)versions).Reverse()) + { + Console.WriteLine($"+ e={((Content)version).VersionId} p={((Content)version).PublishedVersionId}"); + } // and proper values // first, the current (edited) version, with edited and published versions @@ -618,9 +631,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_Content_For_Expiration() { // Arrange - var root = ContentService.GetById(Textpage.Id); + IContent root = ContentService.GetById(Textpage.Id); ContentService.SaveAndPublish(root); - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); content.ContentSchedule.Add(null, DateTime.Now.AddSeconds(1)); ContentService.SaveAndPublish(content); @@ -653,7 +666,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange // Act - var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out var _).ToList(); + var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out long _).ToList(); // Assert Assert.That(contents, Is.Not.Null); @@ -665,11 +678,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Unpublish_Content() { // Arrange - var content = ContentService.GetById(Textpage.Id); - var published = ContentService.SaveAndPublish(content, userId: 0); + IContent content = ContentService.GetById(Textpage.Id); + PublishResult published = ContentService.SaveAndPublish(content, userId: 0); // Act - var unpublished = ContentService.Unpublish(content, userId: 0); + PublishResult unpublished = ContentService.Unpublish(content, userId: 0); // Assert Assert.That(published.Success, Is.True); @@ -681,49 +694,47 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Unpublish_Content_Variation() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); content.PublishCulture(CultureImpact.Explicit(langFr.IsoCode, langFr.IsDefault)); content.PublishCulture(CultureImpact.Explicit(langUk.IsoCode, langUk.IsDefault)); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - var published = ContentService.SaveAndPublish(content, new[]{ langFr.IsoCode , langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.IsTrue(published.Success); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - var unpublished = ContentService.Unpublish(content, langFr.IsoCode); + PublishResult unpublished = ContentService.Unpublish(content, langFr.IsoCode); Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - - } [Test] public void Can_Publish_Culture_After_Last_Culture_Unpublished() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); - var unpublished = ContentService.Unpublish(content, langUk.IsoCode); //first culture + PublishResult unpublished = ContentService.Unpublish(content, langUk.IsoCode); // first culture Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); @@ -731,7 +742,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content = ContentService.GetById(content.Id); - unpublished = ContentService.Unpublish(content, langFr.IsoCode); //last culture + unpublished = ContentService.Unpublish(content, langFr.IsoCode); // last culture Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishLastCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); @@ -744,54 +755,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); - content = ContentService.GetById(content.Id); //reget + content = ContentService.GetById(content.Id); // reget Assert.AreEqual(PublishedState.Published, content.PublishedState); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); - } - - [Test] public void Unpublish_All_Cultures_Has_Unpublished_State() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsTrue(published.Success); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.AreEqual(PublishedState.Published, content.PublishedState); - var unpublished = ContentService.Unpublish(content, langFr.IsoCode); //first culture + PublishResult unpublished = ContentService.Unpublish(content, langFr.IsoCode); // first culture Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - Assert.AreEqual(PublishedState.Published, content.PublishedState); //still published + Assert.AreEqual(PublishedState.Published, content.PublishedState); // still published - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); - unpublished = ContentService.Unpublish(content, langUk.IsoCode); //last culture + unpublished = ContentService.Unpublish(content, langUk.IsoCode); // last culture Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishLastCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); - Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); //the last culture was unpublished so the document should also reflect this + Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); // the last culture was unpublished so the document should also reflect this - //re-get + // re-get content = ContentService.GetById(content.Id); - Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); //just double checking + Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); // just double checking Assert.IsFalse(content.IsCulturePublished(langFr.IsoCode)); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); } @@ -799,19 +807,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Unpublishing_Mandatory_Language_Unpublishes_Document() { - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .WithIsMandatory(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langUk); - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); @@ -819,104 +827,108 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("content-fr", langFr.IsoCode); content.SetCultureName("content-en", langUk.IsoCode); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsTrue(published.Success); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); - var unpublished = ContentService.Unpublish(content, langUk.IsoCode); //unpublish mandatory lang + PublishResult unpublished = ContentService.Unpublish(content, langUk.IsoCode); // unpublish mandatory lang Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishMandatoryCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); - Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); //remains published + Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); // remains published Assert.AreEqual(PublishedState.Unpublished, content.PublishedState); } [Test] public void Unpublishing_Already_Unpublished_Culture() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsTrue(published.Success); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); - var unpublished = ContentService.Unpublish(content, langUk.IsoCode); + PublishResult unpublished = ContentService.Unpublish(content, langUk.IsoCode); Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishCulture, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); content = ContentService.GetById(content.Id); - //Change some data since Unpublish should always Save + // Change some data since Unpublish should always Save content.SetCultureName("content-en-updated", langUk.IsoCode); - unpublished = ContentService.Unpublish(content, langUk.IsoCode); //unpublish again + unpublished = ContentService.Unpublish(content, langUk.IsoCode); // unpublish again Assert.IsTrue(unpublished.Success); Assert.AreEqual(PublishResultType.SuccessUnpublishAlready, unpublished.Result); Assert.IsFalse(content.IsCulturePublished(langUk.IsoCode)); content = ContentService.GetById(content.Id); - //ensure that even though the culture was already unpublished that the data was still persisted + + // ensure that even though the culture was already unpublished that the data was still persisted Assert.AreEqual("content-en-updated", content.GetCultureName(langUk.IsoCode)); } [Test] public void Publishing_No_Cultures_Still_Saves() { - var content = CreateEnglishAndFrenchDocument(out var langUk, out var langFr, out var contentType); + IContent content = CreateEnglishAndFrenchDocument(out Language langUk, out Language langFr, out ContentType contentType); - var published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); Assert.IsTrue(content.IsCulturePublished(langUk.IsoCode)); Assert.IsTrue(published.Success); Assert.AreEqual(PublishedState.Published, content.PublishedState); - //re-get + // re-get content = ContentService.GetById(content.Id); - //Change some data since SaveAndPublish should always Save + // Change some data since SaveAndPublish should always Save content.SetCultureName("content-en-updated", langUk.IsoCode); - var saved = ContentService.SaveAndPublish(content, new string [] { }); //save without cultures + PublishResult saved = ContentService.SaveAndPublish(content, new string[] { }); // save without cultures Assert.AreEqual(PublishResultType.FailedPublishNothingToPublish, saved.Result); - //re-get + // re-get content = ContentService.GetById(content.Id); - //ensure that even though nothing was published that the data was still persisted + + // ensure that even though nothing was published that the data was still persisted Assert.AreEqual("content-en-updated", content.GetCultureName(langUk.IsoCode)); } - [Test] public void Pending_Invariant_Property_Changes_Affect_Default_Language_Edited_State() { // Arrange - var langGb = new LanguageBuilder() + ILanguage langGb = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langGb); - var contentType = ContentTypeBuilder.CreateMetaContentType(); + ContentType contentType = ContentTypeBuilder.CreateMetaContentType(); contentType.Variations = ContentVariation.Culture; - foreach(var prop in contentType.PropertyTypes) + foreach (IPropertyType prop in contentType.PropertyTypes) + { prop.Variations = ContentVariation.Culture; - var keywordsProp = contentType.PropertyTypes.Single(x => x.Alias == "metakeywords"); + } + + IPropertyType keywordsProp = contentType.PropertyTypes.Single(x => x.Alias == "metakeywords"); keywordsProp.Variations = ContentVariation.Nothing; // this one is invariant ContentTypeService.Save(contentType); @@ -925,9 +937,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("content-en", langGb.IsoCode); content.SetCultureName("content-fr", langFr.IsoCode); - Assert.IsTrue(ContentService.SaveAndPublish(content, new []{ langGb.IsoCode , langFr.IsoCode }).Success); + Assert.IsTrue(ContentService.SaveAndPublish(content, new[] { langGb.IsoCode, langFr.IsoCode }).Success); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.AreEqual(PublishedState.Published, content.PublishedState); Assert.IsTrue(content.IsCulturePublished(langGb.IsoCode)); @@ -935,11 +947,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsFalse(content.IsCultureEdited(langGb.IsoCode)); Assert.IsFalse(content.IsCultureEdited(langFr.IsoCode)); - //update the invariant property and save a pending version + // update the invariant property and save a pending version content.SetValue("metakeywords", "hello"); ContentService.Save(content); - //re-get + // re-get content = ContentService.GetById(content.Id); Assert.AreEqual(PublishedState.Published, content.PublishedState); Assert.IsTrue(content.IsCulturePublished(langGb.IsoCode)); @@ -951,20 +963,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Content_Variation_And_Detect_Changed_Cultures() { - CreateEnglishAndFrenchDocumentType(out var langUk, out var langFr, out var contentType); + CreateEnglishAndFrenchDocumentType(out Language langUk, out Language langFr, out ContentType contentType); IContent content = new Content("content", Constants.System.Root, contentType); content.SetCultureName("content-fr", langFr.IsoCode); - var published = ContentService.SaveAndPublish(content, langFr.IsoCode); - //audit log will only show that french was published - var lastLog = AuditService.GetLogs(content.Id).Last(); + PublishResult published = ContentService.SaveAndPublish(content, langFr.IsoCode); + + // audit log will only show that french was published + IAuditItem lastLog = AuditService.GetLogs(content.Id).Last(); Assert.AreEqual($"Published languages: French (France)", lastLog.Comment); - //re-get + // re-get content = ContentService.GetById(content.Id); content.SetCultureName("content-en", langUk.IsoCode); published = ContentService.SaveAndPublish(content, langUk.IsoCode); - //audit log will only show that english was published + + // audit log will only show that english was published lastLog = AuditService.GetLogs(content.Id).Last(); Assert.AreEqual($"Published languages: English (United Kingdom)", lastLog.Comment); } @@ -973,53 +987,55 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Unpublish_Content_Variation_And_Detect_Changed_Cultures() { // Arrange - var langGb = new LanguageBuilder() + ILanguage langGb = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .WithIsMandatory(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langGb); - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); IContent content = new Content("content", Constants.System.Root, contentType); content.SetCultureName("content-fr", langFr.IsoCode); content.SetCultureName("content-gb", langGb.IsoCode); - var published = ContentService.SaveAndPublish(content, new[] {langGb.IsoCode, langFr.IsoCode}); + PublishResult published = ContentService.SaveAndPublish(content, new[] { langGb.IsoCode, langFr.IsoCode }); Assert.IsTrue(published.Success); - //re-get + // re-get content = ContentService.GetById(content.Id); - var unpublished = ContentService.Unpublish(content, langFr.IsoCode); - //audit log will only show that french was unpublished - var lastLog = AuditService.GetLogs(content.Id).Last(); + PublishResult unpublished = ContentService.Unpublish(content, langFr.IsoCode); + + // audit log will only show that french was unpublished + IAuditItem lastLog = AuditService.GetLogs(content.Id).Last(); Assert.AreEqual($"Unpublished languages: French (France)", lastLog.Comment); - //re-get + // re-get content = ContentService.GetById(content.Id); content.SetCultureName("content-en", langGb.IsoCode); unpublished = ContentService.Unpublish(content, langGb.IsoCode); - //audit log will only show that english was published + + // audit log will only show that english was published var logs = AuditService.GetLogs(content.Id).ToList(); - Assert.AreEqual($"Unpublished languages: English (United Kingdom)", logs[logs.Count - 2].Comment); - Assert.AreEqual($"Unpublished (mandatory language unpublished)", logs[logs.Count - 1].Comment); + Assert.AreEqual($"Unpublished languages: English (United Kingdom)", logs[^2].Comment); + Assert.AreEqual($"Unpublished (mandatory language unpublished)", logs[^1].Comment); } [Test] public void Can_Publish_Content_1() { // Arrange - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(published.Success, Is.True); @@ -1030,10 +1046,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Publish_Content_2() { // Arrange - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Act - var published = ContentService.SaveAndPublish(content, userId: 0); + PublishResult published = ContentService.SaveAndPublish(content, userId: 0); // Assert Assert.That(published.Success, Is.True); @@ -1044,10 +1060,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void IsPublishable() { // Arrange - var parent = ContentService.Create("parent", Constants.System.Root, "umbTextpage"); + IContent parent = ContentService.Create("parent", Constants.System.Root, "umbTextpage"); ContentService.SaveAndPublish(parent); - var content = ContentService.Create("child", parent, "umbTextpage"); + IContent content = ContentService.Create("child", parent, "umbTextpage"); ContentService.Save(content); Assert.IsTrue(ContentService.IsPathPublishable(content)); @@ -1063,19 +1079,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // tests that during 'publishing' event, what we get from the repo is the 'old' content, // because 'publishing' fires before the 'saved' event ie before the content is actually // saved - try { - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); Assert.AreEqual("Home", content.Name); content.Name = "foo"; - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); Assert.That(published.Success, Is.True); Assert.That(content.Published, Is.True); - var e = ContentService.GetById(content.Id); + IContent e = ContentService.GetById(content.Id); Assert.AreEqual("foo", e.Name); } finally @@ -1087,23 +1102,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void ContentServiceOnPublishing(IContentService sender, PublishEventArgs args) { Assert.AreEqual(1, args.PublishedEntities.Count()); - var entity = args.PublishedEntities.First(); + IContent entity = args.PublishedEntities.First(); Assert.AreEqual("foo", entity.Name); - var e = ContentService.GetById(entity.Id); + IContent e = ContentService.GetById(entity.Id); Assert.AreEqual("Home", e.Name); } [Test] public void Can_Not_Publish_Invalid_Cultures() { - var content = new ContentBuilder() + Content content = new ContentBuilder() .AddContentType() .WithContentVariation(ContentVariation.Culture) .Done() .Build(); - Assert.Throws(() => ContentService.SaveAndPublish(content, new[] {"*"})); + Assert.Throws(() => ContentService.SaveAndPublish(content, new[] { "*" })); Assert.Throws(() => ContentService.SaveAndPublish(content, new string[] { null })); Assert.Throws(() => ContentService.SaveAndPublish(content, new[] { "*", null })); Assert.Throws(() => ContentService.SaveAndPublish(content, new[] { "en-US", "*", "es-ES" })); @@ -1112,60 +1127,59 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Only_Valid_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", mandatoryProperties: true, defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var parentId = Textpage.Id; + int parentId = Textpage.Id; - var parent = ContentService.GetById(parentId); + IContent parent = ContentService.GetById(parentId); - var parentPublished = ContentService.SaveAndPublish(parent); + PublishResult parentPublished = ContentService.SaveAndPublish(parent); // parent can publish values // and therefore can be published Assert.IsTrue(parentPublished.Success); Assert.IsTrue(parent.Published); - var content = ContentBuilder.CreateSimpleContent(contentType, "Invalid Content", parentId); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Invalid Content", parentId); content.SetValue("author", string.Empty); Assert.IsFalse(content.HasIdentity); // content cannot publish values because they are invalid var propertyValidationService = new PropertyValidationService(PropertyEditorCollection, DataTypeService, TextService); - var isValid = propertyValidationService.IsPropertyDataValid(content, out var invalidProperties, CultureImpact.Invariant); + bool isValid = propertyValidationService.IsPropertyDataValid(content, out IProperty[] invalidProperties, CultureImpact.Invariant); Assert.IsFalse(isValid); Assert.IsNotEmpty(invalidProperties); // and therefore cannot be published, // because it did not have a published version at all - var contentPublished = ContentService.SaveAndPublish(content); + PublishResult contentPublished = ContentService.SaveAndPublish(content); Assert.IsFalse(contentPublished.Success); Assert.AreEqual(PublishResultType.FailedPublishContentInvalid, contentPublished.Result); Assert.IsFalse(content.Published); - //Ensure it saved though + // Ensure it saved though Assert.Greater(content.Id, 0); Assert.IsTrue(content.HasIdentity); } - [Test] public void Can_Publish_And_Unpublish_Cultures_In_Single_Operation() { - //TODO: This is using an internal API - we aren't exposing this publicly (at least for now) but we'll keep the test around - var langFr = new LanguageBuilder() + // TODO: This is using an internal API - we aren't exposing this publicly (at least for now) but we'll keep the test around + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr") .Build(); - var langDa = new LanguageBuilder() + ILanguage langDa = new LanguageBuilder() .WithCultureInfo("da") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langDa); - var ct = ContentTypeBuilder.CreateBasicContentType(); + ContentType ct = ContentTypeBuilder.CreateBasicContentType(); ct.Variations = ContentVariation.Culture; ContentTypeService.Save(ct); @@ -1174,7 +1188,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("name-da", langDa.IsoCode); content.PublishCulture(CultureImpact.Explicit(langFr.IsoCode, langFr.IsDefault)); - var result = ((ContentService)ContentService).CommitDocumentChanges(content); + PublishResult result = ((ContentService)ContentService).CommitDocumentChanges(content); Assert.IsTrue(result.Success); content = ContentService.GetById(content.Id); Assert.IsTrue(content.IsCulturePublished(langFr.IsoCode)); @@ -1197,18 +1211,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private IEnumerable MapPublishValues(IEnumerable documents, Func map) { var exclude = new HashSet(); - foreach (var document in documents) + foreach (IContent document in documents) { if (exclude.Contains(document.ParentId)) { exclude.Add(document.Id); continue; } + if (!map(document)) { exclude.Add(document.Id); continue; } + yield return document; } } @@ -1216,19 +1232,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Publish_Content_Children() { - var parentId = Textpage.Id; + int parentId = Textpage.Id; - var parent = ContentService.GetById(parentId); + IContent parent = ContentService.GetById(parentId); Console.WriteLine(" " + parent.Id); const int pageSize = 500; - var page = 0; - var total = long.MaxValue; - while(page * pageSize < total) + int page = 0; + long total = long.MaxValue; + while (page * pageSize < total) { - var descendants = ContentService.GetPagedDescendants(parent.Id, page++, pageSize, out total); - foreach (var x in descendants) + IEnumerable descendants = ContentService.GetPagedDescendants(parent.Id, page++, pageSize, out total); + foreach (IContent x in descendants) + { Console.WriteLine(" ".Substring(0, x.Level) + x.Id); + } } Console.WriteLine(); @@ -1236,16 +1254,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // publish parent & its branch // only those that are not already published // only invariant/neutral values - var parentPublished = ContentService.SaveAndPublishBranch(parent, true); + IEnumerable parentPublished = ContentService.SaveAndPublishBranch(parent, true); - foreach (var result in parentPublished) + foreach (PublishResult result in parentPublished) + { Console.WriteLine(" ".Substring(0, result.Content.Level) + $"{result.Content.Id}: {result.Result}"); + } // everything should be successful Assert.IsTrue(parentPublished.All(x => x.Success)); Assert.IsTrue(parent.Published); - var children = ContentService.GetPagedChildren(parentId, 0, 500, out var totalChildren); //we only want the first so page size, etc.. is abitrary + IEnumerable children = ContentService.GetPagedChildren(parentId, 0, 500, out long totalChildren); // we only want the first so page size, etc.. is abitrary // children are published including ... that was released 5 mins ago Assert.IsTrue(children.First(x => x.Id == Subpage.Id).Published); @@ -1255,15 +1275,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Publish_Expired_Content() { // Arrange - var content = ContentService.GetById(Subpage.Id); //This Content expired 5min ago + IContent content = ContentService.GetById(Subpage.Id); // This Content expired 5min ago content.ContentSchedule.Add(null, DateTime.Now.AddMinutes(-5)); ContentService.Save(content); - var parent = ContentService.GetById(Textpage.Id); - var parentPublished = ContentService.SaveAndPublish(parent, userId: Constants.Security.SuperUserId);//Publish root Home node to enable publishing of 'Subpage.Id' + IContent parent = ContentService.GetById(Textpage.Id); + PublishResult parentPublished = ContentService.SaveAndPublish(parent, userId: Constants.Security.SuperUserId); // Publish root Home node to enable publishing of 'Subpage.Id' // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(parentPublished.Success, Is.True); @@ -1275,16 +1295,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Cannot_Publish_Expired_Culture() { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateBasicContent(contentType); + Content content = ContentBuilder.CreateBasicContent(contentType); content.SetCultureName("Hello", "en-US"); content.ContentSchedule.Add("en-US", null, DateTime.Now.AddMinutes(-5)); ContentService.Save(content); - var published = ContentService.SaveAndPublish(content, "en-US", Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, "en-US", Constants.Security.SuperUserId); Assert.IsFalse(published.Success); Assert.AreEqual(PublishResultType.FailedPublishCultureHasExpired, published.Result); @@ -1295,15 +1315,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Publish_Content_Awaiting_Release() { // Arrange - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); content.ContentSchedule.Add(DateTime.Now.AddHours(2), null); ContentService.Save(content, Constants.Security.SuperUserId); - var parent = ContentService.GetById(Textpage.Id); - var parentPublished = ContentService.SaveAndPublish(parent, userId: Constants.Security.SuperUserId);//Publish root Home node to enable publishing of 'Subpage.Id' + IContent parent = ContentService.GetById(Textpage.Id); + PublishResult parentPublished = ContentService.SaveAndPublish(parent, userId: Constants.Security.SuperUserId); // Publish root Home node to enable publishing of 'Subpage.Id' // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(parentPublished.Success, Is.True); @@ -1315,16 +1335,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Cannot_Publish_Culture_Awaiting_Release() { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateBasicContent(contentType); + Content content = ContentBuilder.CreateBasicContent(contentType); content.SetCultureName("Hello", "en-US"); content.ContentSchedule.Add("en-US", DateTime.Now.AddHours(2), null); ContentService.Save(content); - var published = ContentService.SaveAndPublish(content, "en-US", Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, "en-US", Constants.Security.SuperUserId); Assert.IsFalse(published.Success); Assert.AreEqual(PublishResultType.FailedPublishCultureAwaitingRelease, published.Result); @@ -1335,11 +1355,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Publish_Content_Where_Parent_Is_Unpublished() { // Arrange - var content = ContentService.Create("Subpage with Unpublished Parent", Textpage.Id, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Subpage with Unpublished Parent", Textpage.Id, "umbTextpage", Constants.Security.SuperUserId); ContentService.Save(content, Constants.Security.SuperUserId); // Act - var published = ContentService.SaveAndPublishBranch(content, true); + IEnumerable published = ContentService.SaveAndPublishBranch(content, true); // Assert Assert.That(published.All(x => x.Success), Is.False); @@ -1350,10 +1370,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Publish_Trashed_Content() { // Arrange - var content = ContentService.GetById(Trashed.Id); + IContent content = ContentService.GetById(Trashed.Id); // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(published.Success, Is.False); @@ -1365,11 +1385,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Save_And_Publish_Content() { // Arrange - var content = ContentService.Create("Home US", - 1, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Home US", -1, "umbTextpage", Constants.Security.SuperUserId); content.SetValue("author", "Barack Obama"); // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); // Assert Assert.That(content.HasIdentity, Is.True); @@ -1388,17 +1408,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Save_And_Publish_Content_And_Child_Without_Identity() { // Arrange - var content = ContentService.Create("Home US", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Home US", Constants.System.Root, "umbTextpage", Constants.Security.SuperUserId); content.SetValue("author", "Barack Obama"); // Act - var published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); - var childContent = ContentService.Create("Child", content.Id, "umbTextpage", Constants.Security.SuperUserId); + PublishResult published = ContentService.SaveAndPublish(content, userId: Constants.Security.SuperUserId); + IContent childContent = ContentService.Create("Child", content.Id, "umbTextpage", Constants.Security.SuperUserId); + // Reset all identity properties childContent.Id = 0; childContent.Path = null; ((Content)childContent).ResetIdentity(); - var childPublished = ContentService.SaveAndPublish(childContent, userId: Constants.Security.SuperUserId); + PublishResult childPublished = ContentService.SaveAndPublish(childContent, userId: Constants.Security.SuperUserId); // Assert Assert.That(content.HasIdentity, Is.True); @@ -1413,13 +1434,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_Published_Descendant_Versions() { // Arrange - var root = ContentService.GetById(Textpage.Id); - var rootPublished = ContentService.SaveAndPublish(root); + IContent root = ContentService.GetById(Textpage.Id); + PublishResult rootPublished = ContentService.SaveAndPublish(root); - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); content.Properties["title"].SetValue(content.Properties["title"].GetValue() + " Published"); - var contentPublished = ContentService.SaveAndPublish(content); - var publishedVersion = content.VersionId; + PublishResult contentPublished = ContentService.SaveAndPublish(content); + int publishedVersion = content.VersionId; content.Properties["title"].SetValue(content.Properties["title"].GetValue() + " Saved"); ContentService.Save(content); @@ -1433,20 +1454,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(rootPublished.Success); Assert.IsTrue(contentPublished.Success); - //Console.WriteLine(publishedVersion); - //foreach (var d in publishedDescendants) Console.WriteLine(d.Version); + // Console.WriteLine(publishedVersion); + // foreach (var d in publishedDescendants) Console.WriteLine(d.Version); Assert.IsTrue(publishedDescendants.Any(x => x.VersionId == publishedVersion)); - //Ensure that the published content version has the correct property value and is marked as published - var publishedContentVersion = publishedDescendants.First(x => x.VersionId == publishedVersion); + // Ensure that the published content version has the correct property value and is marked as published + IContent publishedContentVersion = publishedDescendants.First(x => x.VersionId == publishedVersion); Assert.That(publishedContentVersion.Published, Is.True); Assert.That(publishedContentVersion.Properties["title"].GetValue(published: true), Contains.Substring("Published")); // and has the correct draft properties Assert.That(publishedContentVersion.Properties["title"].GetValue(), Contains.Substring("Saved")); - //Ensure that the latest version of the content is ok - var currentContent = ContentService.GetById(Subpage.Id); + // Ensure that the latest version of the content is ok + IContent currentContent = ContentService.GetById(Subpage.Id); Assert.That(currentContent.Published, Is.True); Assert.That(currentContent.Properties["title"].GetValue(published: true), Contains.Substring("Published")); Assert.That(currentContent.Properties["title"].GetValue(), Contains.Substring("Saved")); @@ -1457,7 +1478,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Save_Content() { // Arrange - var content = ContentService.Create("Home US", - 1, "umbTextpage", Constants.Security.SuperUserId); + IContent content = ContentService.Create("Home US", -1, "umbTextpage", Constants.Security.SuperUserId); content.SetValue("author", "Barack Obama"); // Act @@ -1470,7 +1491,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Update_Content_Property_Values() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); @@ -1511,7 +1532,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("new author text", content.GetValue("author")); // make sure that the published version remained the same - var publishedContent = ContentService.GetVersion(content.PublishedVersionId); + IContent publishedContent = ContentService.GetVersion(content.PublishedVersionId); Assert.AreEqual("another title of mine", publishedContent.GetValue("title")); Assert.IsNull(publishedContent.GetValue("bodyText")); Assert.AreEqual("new author", publishedContent.GetValue("author")); @@ -1521,10 +1542,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Bulk_Save_Content() { // Arrange - var contentType = ContentTypeService.Get("umbTextpage"); - var subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Subpage 1", Textpage.Id); - var subpage2 = ContentBuilder.CreateSimpleContent(contentType, "Text Subpage 2", Textpage.Id); - var list = new List {subpage, subpage2}; + IContentType contentType = ContentTypeService.Get("umbTextpage"); + Content subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Subpage 1", Textpage.Id); + Content subpage2 = ContentBuilder.CreateSimpleContent(contentType, "Text Subpage 2", Textpage.Id); + var list = new List { subpage, subpage2 }; // Act ContentService.Save(list, Constants.Security.SuperUserId); @@ -1544,21 +1565,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(hierarchy.Any(), Is.True); Assert.That(hierarchy.Any(x => x.HasIdentity == false), Is.False); - //all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown - Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); + // all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown + Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); } [Test] public void Can_Delete_Content_Of_Specific_ContentType() { // Arrange - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); // Act ContentService.DeleteOfType(contentType.Id); - var rootContent = ContentService.GetRootContent(); - var contents = ContentService.GetPagedOfType(contentType.Id, 0, int.MaxValue, out var _, null); + IEnumerable rootContent = ContentService.GetRootContent(); + IEnumerable contents = ContentService.GetPagedOfType(contentType.Id, 0, int.MaxValue, out long _, null); // Assert Assert.That(rootContent.Any(), Is.False); @@ -1569,11 +1590,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Delete_Content() { // Arrange - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Act ContentService.Delete(content, Constants.Security.SuperUserId); - var deleted = ContentService.GetById(Textpage.Id); + IContent deleted = ContentService.GetById(Textpage.Id); // Assert Assert.That(deleted, Is.Null); @@ -1583,7 +1604,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Content_To_RecycleBin() { // Arrange - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); // Act ContentService.MoveToRecycleBin(content, Constants.Security.SuperUserId); @@ -1596,18 +1617,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Move_Content_Structure_To_RecycleBin_And_Empty_RecycleBin() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var subsubpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 3", Subpage.Id); + Content subsubpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 3", Subpage.Id); ContentService.Save(subsubpage, Constants.Security.SuperUserId); - var content = ContentService.GetById(Textpage.Id); + IContent content = ContentService.GetById(Textpage.Id); const int pageSize = 500; - var page = 0; - var total = long.MaxValue; + int page = 0; + long total = long.MaxValue; var descendants = new List(); - while(page * pageSize < total) + while (page * pageSize < total) + { descendants.AddRange(ContentService.GetPagedDescendants(content.Id, page++, pageSize, out total)); + } Assert.AreNotEqual(-20, content.ParentId); Assert.IsFalse(content.Trashed); @@ -1620,7 +1643,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services descendants.Clear(); page = 0; while (page * pageSize < total) + { descendants.AddRange(ContentService.GetPagedDescendants(content.Id, page++, pageSize, out total)); + } Assert.AreEqual(-20, content.ParentId); Assert.IsTrue(content.Trashed); @@ -1629,7 +1654,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.True(descendants.All(x => x.Trashed)); ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var trashed = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out var _).ToList(); + var trashed = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out long _).ToList(); Assert.IsEmpty(trashed); } @@ -1639,7 +1664,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Arrange // Act ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out var _).ToList(); + var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out long _).ToList(); // Assert Assert.That(contents.Any(), Is.False); @@ -1649,36 +1674,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Ensures_Permissions_Are_Retained_For_Copied_Descendants_With_Explicit_Permissions() { // Arrange - var userGroup = UserGroupBuilder.CreateUserGroup("1"); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup("1"); UserService.Save(userGroup); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentType.AllowedContentTypes = new List { new ContentTypeSort(new Lazy(() => contentType.Id), 0, contentType.Alias) }; ContentTypeService.Save(contentType); - var parentPage = ContentBuilder.CreateSimpleContent(contentType); + Content parentPage = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parentPage); - var childPage = ContentBuilder.CreateSimpleContent(contentType, "child", parentPage); + Content childPage = ContentBuilder.CreateSimpleContent(contentType, "child", parentPage); ContentService.Save(childPage); - //assign explicit permissions to the child + + // assign explicit permissions to the child ContentService.SetPermission(childPage, 'A', new[] { userGroup.Id }); - //Ok, now copy, what should happen is the childPage will retain it's own permissions - var parentPage2 = ContentBuilder.CreateSimpleContent(contentType); + // Ok, now copy, what should happen is the childPage will retain it's own permissions + Content parentPage2 = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parentPage2); - var copy = ContentService.Copy(childPage, parentPage2.Id, false, true); + IContent copy = ContentService.Copy(childPage, parentPage2.Id, false, true); - //get the permissions and verify - var permissions = UserService.GetPermissionsForPath(userGroup, copy.Path, fallbackToDefaultPermissions: true); - var allPermissions = permissions.GetAllPermissions().ToArray(); + // get the permissions and verify + EntityPermissionSet permissions = UserService.GetPermissionsForPath(userGroup, copy.Path, fallbackToDefaultPermissions: true); + string[] allPermissions = permissions.GetAllPermissions().ToArray(); Assert.AreEqual(1, allPermissions.Length); Assert.AreEqual("A", allPermissions[0]); } @@ -1687,65 +1713,71 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Ensures_Permissions_Are_Inherited_For_Copied_Descendants() { // Arrange - var userGroup = UserGroupBuilder.CreateUserGroup("1"); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup("1"); UserService.Save(userGroup); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage1", "Textpage", defaultTemplateId: template.Id); contentType.AllowedContentTypes = new List { new ContentTypeSort(new Lazy(() => contentType.Id), 0, contentType.Alias) }; ContentTypeService.Save(contentType); - var parentPage = ContentBuilder.CreateSimpleContent(contentType); + Content parentPage = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parentPage); ContentService.SetPermission(parentPage, 'A', new[] { userGroup.Id }); - var childPage1 = ContentBuilder.CreateSimpleContent(contentType, "child1", parentPage); + Content childPage1 = ContentBuilder.CreateSimpleContent(contentType, "child1", parentPage); ContentService.Save(childPage1); - var childPage2 = ContentBuilder.CreateSimpleContent(contentType, "child2", childPage1); + Content childPage2 = ContentBuilder.CreateSimpleContent(contentType, "child2", childPage1); ContentService.Save(childPage2); - var childPage3 = ContentBuilder.CreateSimpleContent(contentType, "child3", childPage2); + Content childPage3 = ContentBuilder.CreateSimpleContent(contentType, "child3", childPage2); ContentService.Save(childPage3); - //Verify that the children have the inherited permissions + // Verify that the children have the inherited permissions var descendants = new List(); const int pageSize = 500; - var page = 0; - var total = long.MaxValue; - while(page * pageSize < total) + int page = 0; + long total = long.MaxValue; + while (page * pageSize < total) + { descendants.AddRange(ContentService.GetPagedDescendants(parentPage.Id, page++, pageSize, out total)); + } + Assert.AreEqual(3, descendants.Count); - foreach (var descendant in descendants) + foreach (IContent descendant in descendants) { - var permissions = UserService.GetPermissionsForPath(userGroup, descendant.Path, fallbackToDefaultPermissions: true); - var allPermissions = permissions.GetAllPermissions().ToArray(); + EntityPermissionSet permissions = UserService.GetPermissionsForPath(userGroup, descendant.Path, fallbackToDefaultPermissions: true); + string[] allPermissions = permissions.GetAllPermissions().ToArray(); Assert.AreEqual(1, allPermissions.Length); Assert.AreEqual("A", allPermissions[0]); } - //create a new parent with a new permission structure - var parentPage2 = ContentBuilder.CreateSimpleContent(contentType); + // create a new parent with a new permission structure + Content parentPage2 = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parentPage2); ContentService.SetPermission(parentPage2, 'B', new[] { userGroup.Id }); - //Now copy, what should happen is the child pages will now have permissions inherited from the new parent - var copy = ContentService.Copy(childPage1, parentPage2.Id, false, true); + // Now copy, what should happen is the child pages will now have permissions inherited from the new parent + IContent copy = ContentService.Copy(childPage1, parentPage2.Id, false, true); descendants.Clear(); page = 0; while (page * pageSize < total) + { descendants.AddRange(ContentService.GetPagedDescendants(parentPage2.Id, page++, pageSize, out total)); + } + Assert.AreEqual(3, descendants.Count); - foreach (var descendant in descendants) + foreach (IContent descendant in descendants) { - var permissions = UserService.GetPermissionsForPath(userGroup, descendant.Path, fallbackToDefaultPermissions: true); - var allPermissions = permissions.GetAllPermissions().ToArray(); + EntityPermissionSet permissions = UserService.GetPermissionsForPath(userGroup, descendant.Path, fallbackToDefaultPermissions: true); + string[] allPermissions = permissions.GetAllPermissions().ToArray(); Assert.AreEqual(1, allPermissions.Length); Assert.AreEqual("B", allPermissions[0]); } @@ -1755,7 +1787,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Empty_RecycleBin_With_Content_That_Has_All_Related_Data() { // Arrange - //need to: + // need to: // * add relations // * add permissions // * add notifications @@ -1764,8 +1796,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // * domain // * published & preview data // * multiple versions - - var contentType = ContentTypeBuilder.CreateAllTypesContentType("test", "test"); + ContentType contentType = ContentTypeBuilder.CreateAllTypesContentType("test", "test"); ContentTypeService.Save(contentType, Constants.Security.SuperUserId); object obj = @@ -1773,23 +1804,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { tags = "[\"Hello\",\"World\"]" }; - var content1 = ContentBuilder.CreateBasicContent(contentType); + Content content1 = ContentBuilder.CreateBasicContent(contentType); content1.PropertyValues(obj); content1.ResetDirtyProperties(false); ContentService.Save(content1, Constants.Security.SuperUserId); Assert.IsTrue(ContentService.SaveAndPublish(content1, userId: 0).Success); - var content2 = ContentBuilder.CreateBasicContent(contentType); + Content content2 = ContentBuilder.CreateBasicContent(contentType); content2.PropertyValues(obj); content2.ResetDirtyProperties(false); ContentService.Save(content2, Constants.Security.SuperUserId); Assert.IsTrue(ContentService.SaveAndPublish(content2, userId: 0).Success); - var editorGroup = UserService.GetUserGroupByAlias(Constants.Security.EditorGroupAlias); + IUserGroup editorGroup = UserService.GetUserGroupByAlias(Constants.Security.EditorGroupAlias); editorGroup.StartContentId = content1.Id; UserService.Save(editorGroup); - var admin = UserService.GetUserById(Constants.Security.SuperUserId); - admin.StartContentIds = new[] {content1.Id}; + IUser admin = UserService.GetUserById(Constants.Security.SuperUserId); + admin.StartContentIds = new[] { content1.Id }; UserService.Save(admin); RelationService.Save(new RelationType("test", "test", false, Constants.ObjectTypes.Document, Constants.ObjectTypes.Document)); @@ -1805,8 +1836,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services })); Assert.IsTrue(PublicAccessService.AddRule(content1, "test2", "test2").Success); - var user = UserService.GetUserById(Constants.Security.SuperUserId); - var userGroup = UserService.GetUserGroupByAlias(user.Groups.First().Alias); + IUser user = UserService.GetUserById(Constants.Security.SuperUserId); + IUserGroup userGroup = UserService.GetUserGroupByAlias(user.Groups.First().Alias); Assert.IsNotNull(NotificationService.CreateNotification(user, content1, "X")); ContentService.SetPermission(content1, 'A', new[] { userGroup.Id }); @@ -1819,7 +1850,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Act ContentService.MoveToRecycleBin(content1, Constants.Security.SuperUserId); ContentService.EmptyRecycleBin(Constants.Security.SuperUserId); - var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out var _).ToList(); + var contents = ContentService.GetPagedContentInRecycleBin(0, int.MaxValue, out long _).ToList(); // Assert Assert.That(contents.Any(), Is.False); @@ -1829,7 +1860,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Content() { // Arrange - var content = ContentService.GetById(Trashed.Id); + IContent content = ContentService.GetById(Trashed.Id); // Act - moving out of recycle bin ContentService.Move(content, Textpage.Id); @@ -1844,64 +1875,64 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_Content() { // Arrange - var temp = ContentService.GetById(Subpage.Id); + IContent temp = ContentService.GetById(Subpage.Id); // Act - var copy = ContentService.Copy(temp, temp.ParentId, false, Constants.Security.SuperUserId); - var content = ContentService.GetById(Subpage.Id); + IContent copy = ContentService.Copy(temp, temp.ParentId, false, Constants.Security.SuperUserId); + IContent content = ContentService.GetById(Subpage.Id); // Assert Assert.That(copy, Is.Not.Null); Assert.That(copy.Id, Is.Not.EqualTo(content.Id)); Assert.AreNotSame(content, copy); - foreach (var property in copy.Properties) + foreach (IProperty property in copy.Properties) { Assert.AreEqual(property.GetValue(), content.Properties[property.Alias].GetValue()); } - //Assert.AreNotEqual(content.Name, copy.Name); + + // Assert.AreNotEqual(content.Name, copy.Name); } [Test] public void Can_Copy_And_Modify_Content_With_Events() { // see https://github.com/umbraco/Umbraco-CMS/issues/5513 - - TypedEventHandler> copying = (sender, args) => + static void Copying(IContentService sender, CopyEventArgs args) { args.Copy.SetValue("title", "1"); args.Original.SetValue("title", "2"); - }; + } - TypedEventHandler> copied = (sender, args) => + static void Copied(IContentService sender, CopyEventArgs args) { - var copyVal = args.Copy.GetValue("title"); - var origVal = args.Original.GetValue("title"); + string copyVal = args.Copy.GetValue("title"); + string origVal = args.Original.GetValue("title"); Assert.AreEqual("1", copyVal); Assert.AreEqual("2", origVal); - }; + } try { - ContentService.Copying += copying; - ContentService.Copied += copied; + ContentService.Copying += Copying; + ContentService.Copied += Copied; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType); + Content content = ContentBuilder.CreateSimpleContent(contentType); content.SetValue("title", "New Value"); ContentService.Save(content); - var copy = ContentService.Copy(content, content.ParentId, false, Constants.Security.SuperUserId); + IContent copy = ContentService.Copy(content, content.ParentId, false, Constants.Security.SuperUserId); Assert.AreEqual("1", copy.GetValue("title")); } finally { - ContentService.Copying -= copying; - ContentService.Copied -= copied; + ContentService.Copying -= Copying; + ContentService.Copied -= Copied; } } @@ -1909,13 +1940,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_Recursive() { // Arrange - var temp = ContentService.GetById(Textpage.Id); + IContent temp = ContentService.GetById(Textpage.Id); Assert.AreEqual("Home", temp.Name); Assert.AreEqual(2, ContentService.CountChildren(temp.Id)); // Act - var copy = ContentService.Copy(temp, temp.ParentId, false, true, Constants.Security.SuperUserId); - var content = ContentService.GetById(Textpage.Id); + IContent copy = ContentService.Copy(temp, temp.ParentId, false, true, Constants.Security.SuperUserId); + IContent content = ContentService.GetById(Textpage.Id); // Assert Assert.That(copy, Is.Not.Null); @@ -1923,8 +1954,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreNotSame(content, copy); Assert.AreEqual(2, ContentService.CountChildren(copy.Id)); - var child = ContentService.GetById(Subpage.Id); - var childCopy = ContentService.GetPagedChildren(copy.Id, 0, 500, out var total).First(); + IContent child = ContentService.GetById(Subpage.Id); + IContent childCopy = ContentService.GetPagedChildren(copy.Id, 0, 500, out long total).First(); Assert.AreEqual(childCopy.Name, child.Name); Assert.AreNotEqual(childCopy.Id, child.Id); Assert.AreNotEqual(childCopy.Key, child.Key); @@ -1934,13 +1965,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_NonRecursive() { // Arrange - var temp = ContentService.GetById(Textpage.Id); + IContent temp = ContentService.GetById(Textpage.Id); Assert.AreEqual("Home", temp.Name); Assert.AreEqual(2, ContentService.CountChildren(temp.Id)); // Act - var copy = ContentService.Copy(temp, temp.ParentId, false, false, Constants.Security.SuperUserId); - var content = ContentService.GetById(Textpage.Id); + IContent copy = ContentService.Copy(temp, temp.ParentId, false, false, Constants.Security.SuperUserId); + IContent content = ContentService.GetById(Textpage.Id); // Assert Assert.That(copy, Is.Not.Null); @@ -1956,23 +1987,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // create a content type that has a 'tags' property // the property needs to support tags, else nothing works of course! - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleTagsContentType("umbTagsPage", "TagsPage", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleTagsContentType("umbTagsPage", "TagsPage", defaultTemplateId: template.Id); contentType.Key = new Guid("78D96D30-1354-4A1E-8450-377764200C58"); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateSimpleContent(contentType, "Simple Tags Page", Constants.System.Root); - content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, propAlias, new[] {"hello", "world"}); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Simple Tags Page", Constants.System.Root); + content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, propAlias, new[] { "hello", "world" }); ContentService.Save(content); // value has been set but no tags have been created (not published) Assert.AreEqual("[\"hello\",\"world\"]", content.GetValue(propAlias)); - var contentTags = TagService.GetTagsForEntity(content.Id).ToArray(); + ITag[] contentTags = TagService.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(0, contentTags.Length); // reloading the content yields the same result - content = (Content) ContentService.GetById(content.Id); + content = (Content)ContentService.GetById(content.Id); Assert.AreEqual("[\"hello\",\"world\"]", content.GetValue(propAlias)); contentTags = TagService.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(0, contentTags.Length); @@ -1986,11 +2017,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(2, contentTags.Length); // copy - var copy = ContentService.Copy(content, content.ParentId, false); + IContent copy = ContentService.Copy(content, content.ParentId, false); // copy is not published, so property has value, but no tags have been created Assert.AreEqual("[\"hello\",\"world\"]", copy.GetValue(propAlias)); - var copiedTags = TagService.GetTagsForEntity(copy.Id).ToArray(); + ITag[] copiedTags = TagService.GetTagsForEntity(copy.Id).ToArray(); Assert.AreEqual(0, copiedTags.Length); // publish @@ -2008,17 +2039,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Rollback_Version_On_Content() { // Arrange - var parent = ContentService.GetById(Textpage.Id); + IContent parent = ContentService.GetById(Textpage.Id); Assert.IsFalse(parent.Published); ContentService.SaveAndPublish(parent); // publishing parent, so Text Page 2 can be updated. - var content = ContentService.GetById(Subpage.Id); + IContent content = ContentService.GetById(Subpage.Id); Assert.IsFalse(content.Published); var versions = ContentService.GetVersions(Subpage.Id).ToList(); Assert.AreEqual(1, versions.Count); - var version1 = content.VersionId; + int version1 = content.VersionId; content.Name = "Text Page 2 Updated"; content.SetValue("author", "Francis Doe"); @@ -2027,7 +2058,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(content.Edited); ContentService.SaveAndPublish(content); // new version - var version2 = content.VersionId; + int version2 = content.VersionId; Assert.AreNotEqual(version1, version2); Assert.IsTrue(content.Published); @@ -2051,7 +2082,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.Name = "Text Page 2 ReReUpdated"; ContentService.SaveAndPublish(content); // new version - var version3 = content.VersionId; + int version3 = content.VersionId; Assert.AreNotEqual(version2, version3); Assert.IsTrue(content.Published); @@ -2067,8 +2098,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // version3, third and current published version // rollback all values to version1 - var rollback = ContentService.GetById(Subpage.Id); - var rollto = ContentService.GetVersion(version1); + IContent rollback = ContentService.GetById(Subpage.Id); + IContent rollto = ContentService.GetVersion(version1); rollback.CopyFrom(rollto); rollback.Name = rollto.Name; // must do it explicitly ContentService.Save(rollback); @@ -2089,8 +2120,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // rollback all values to current version // special because... current has edits... this really is equivalent to rolling back to version2 - var rollback2 = ContentService.GetById(Subpage.Id); - var rollto2 = ContentService.GetVersion(version3); + IContent rollback2 = ContentService.GetById(Subpage.Id); + IContent rollto2 = ContentService.GetVersion(version3); rollback2.CopyFrom(rollto2); rollback2.Name = rollto2.PublishName; // must do it explicitely AND must pick the publish one! ContentService.Save(rollback2); @@ -2123,22 +2154,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Rollback_Version_On_Multilingual() { - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr") .Build(); - var langDa = new LanguageBuilder() + ILanguage langDa = new LanguageBuilder() .WithCultureInfo("da") .Build(); LocalizationService.Save(langFr); LocalizationService.Save(langDa); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("multi", "Multi", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("multi", "Multi", defaultTemplateId: template.Id); contentType.Key = new Guid("45FF9A70-9C5F-448D-A476-DCD23566BBF8"); contentType.Variations = ContentVariation.Culture; - var p1 = contentType.PropertyTypes.First(); + IPropertyType p1 = contentType.PropertyTypes.First(); p1.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); @@ -2155,13 +2186,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services page.SetCultureName("da1", langDa.IsoCode); Thread.Sleep(1); ContentService.Save(page); - var versionId0 = page.VersionId; + int versionId0 = page.VersionId; page.SetValue(p1.Alias, "v1fr", langFr.IsoCode); page.SetValue(p1.Alias, "v1da", langDa.IsoCode); Thread.Sleep(1); ContentService.SaveAndPublish(page); - var versionId1 = page.VersionId; + int versionId1 = page.VersionId; Thread.Sleep(10); @@ -2169,7 +2200,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services page.SetValue(p1.Alias, "v2fr", langFr.IsoCode); Thread.Sleep(1); ContentService.SaveAndPublish(page, langFr.IsoCode); - var versionId2 = page.VersionId; + int versionId2 = page.VersionId; Thread.Sleep(10); @@ -2177,7 +2208,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services page.SetValue(p1.Alias, "v2da", langDa.IsoCode); Thread.Sleep(1); ContentService.SaveAndPublish(page, langDa.IsoCode); - var versionId3 = page.VersionId; + int versionId3 = page.VersionId; Thread.Sleep(10); @@ -2187,26 +2218,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services page.SetValue(p1.Alias, "v3da", langDa.IsoCode); Thread.Sleep(1); ContentService.SaveAndPublish(page); - var versionId4 = page.VersionId; + int versionId4 = page.VersionId; // now get all versions - - var versions = ContentService.GetVersions(page.Id).ToArray(); + IContent[] versions = ContentService.GetVersions(page.Id).ToArray(); Assert.AreEqual(5, versions.Length); // current version Assert.AreEqual(versionId4, versions[0].VersionId); Assert.AreEqual(versionId3, versions[0].PublishedVersionId); + // published version Assert.AreEqual(versionId3, versions[1].VersionId); Assert.AreEqual(versionId3, versions[1].PublishedVersionId); + // previous version Assert.AreEqual(versionId2, versions[2].VersionId); Assert.AreEqual(versionId3, versions[2].PublishedVersionId); + // previous version Assert.AreEqual(versionId1, versions[3].VersionId); Assert.AreEqual(versionId3, versions[3].PublishedVersionId); + // previous version Assert.AreEqual(versionId0, versions[4].VersionId); Assert.AreEqual(versionId3, versions[4].PublishedVersionId); @@ -2236,24 +2270,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("da3", versions[0].GetCultureName(langDa.IsoCode)); // all versions have the same publish infos - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { Assert.AreEqual(versions[0].PublishDate, versions[i].PublishDate); Assert.AreEqual(versions[0].GetPublishDate(langFr.IsoCode), versions[i].GetPublishDate(langFr.IsoCode)); Assert.AreEqual(versions[0].GetPublishDate(langDa.IsoCode), versions[i].GetPublishDate(langDa.IsoCode)); } - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { Console.Write("[{0}] ", i); - Console.WriteLine(versions[i].UpdateDate.ToString("O").Substring(11)); - Console.WriteLine(" fr: {0}", versions[i].GetUpdateDate(langFr.IsoCode)?.ToString("O").Substring(11)); - Console.WriteLine(" da: {0}", versions[i].GetUpdateDate(langDa.IsoCode)?.ToString("O").Substring(11)); + Console.WriteLine(versions[i].UpdateDate.ToString("O")[11..]); + Console.WriteLine(" fr: {0}", versions[i].GetUpdateDate(langFr.IsoCode)?.ToString("O")[11..]); + Console.WriteLine(" da: {0}", versions[i].GetUpdateDate(langDa.IsoCode)?.ToString("O")[11..]); } + Console.WriteLine("-"); // for all previous versions, UpdateDate is the published date - Assert.AreEqual(versions[4].UpdateDate, versions[4].GetUpdateDate(langFr.IsoCode)); Assert.AreEqual(versions[4].UpdateDate, versions[4].GetUpdateDate(langDa.IsoCode)); @@ -2264,28 +2298,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(versions[2].UpdateDate, versions[2].GetUpdateDate(langDa.IsoCode)); // for the published version, UpdateDate is the published date - Assert.AreEqual(versions[1].UpdateDate, versions[1].GetUpdateDate(langFr.IsoCode)); Assert.AreEqual(versions[1].UpdateDate, versions[1].GetUpdateDate(langDa.IsoCode)); Assert.AreEqual(versions[1].PublishDate, versions[1].UpdateDate); // for the current version, things are different // UpdateDate is the date it was last saved - Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langFr.IsoCode)); Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langDa.IsoCode)); // so if we save again... page.SetCultureName("fr4", langFr.IsoCode); - //page.SetCultureName("da4", langDa.IsoCode); + + // page.SetCultureName("da4", langDa.IsoCode); page.SetValue(p1.Alias, "v4fr", langFr.IsoCode); page.SetValue(p1.Alias, "v4da", langDa.IsoCode); + // This sleep ensures the save is called on later ticks then the SetValue and SetCultureName. Therefore // we showcase the currect lack of handling dirty on variants on save. When this is implemented the sleep // helps showcase the functionality is actually working Thread.Sleep(1); ContentService.Save(page); - var versionId5 = page.VersionId; + int versionId5 = page.VersionId; versions = ContentService.GetVersions(page.Id).ToArray(); @@ -2293,29 +2327,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, versions.Length); Assert.AreEqual(versionId4, versionId5); - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { Console.Write("[{0}] ", i); - Console.WriteLine(versions[i].UpdateDate.ToString("O").Substring(11)); - Console.WriteLine(" fr: {0}", versions[i].GetUpdateDate(langFr.IsoCode)?.ToString("O").Substring(11)); - Console.WriteLine(" da: {0}", versions[i].GetUpdateDate(langDa.IsoCode)?.ToString("O").Substring(11)); + Console.WriteLine(versions[i].UpdateDate.ToString("O")[11..]); + Console.WriteLine(" fr: {0}", versions[i].GetUpdateDate(langFr.IsoCode)?.ToString("O")[11..]); + Console.WriteLine(" da: {0}", versions[i].GetUpdateDate(langDa.IsoCode)?.ToString("O")[11..]); } + Console.WriteLine("-"); - var versionsSlim = ContentService.GetVersionsSlim(page.Id, 0, 50).ToArray(); + IContent[] versionsSlim = ContentService.GetVersionsSlim(page.Id, 0, 50).ToArray(); Assert.AreEqual(5, versionsSlim.Length); - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { Console.Write("[{0}] ", i); Console.WriteLine(versionsSlim[i].UpdateDate.Ticks); Console.WriteLine(" fr: {0}", versionsSlim[i].GetUpdateDate(langFr.IsoCode)?.Ticks); Console.WriteLine(" da: {0}", versionsSlim[i].GetUpdateDate(langDa.IsoCode)?.Ticks); } + Console.WriteLine("-"); // what we do in the controller to get rollback versions - var versionsSlimFr = versionsSlim.Where(x => x.UpdateDate == x.GetUpdateDate(langFr.IsoCode)).ToArray(); + IContent[] versionsSlimFr = versionsSlim.Where(x => x.UpdateDate == x.GetUpdateDate(langFr.IsoCode)).ToArray(); // TODO this should expect 4, but as the comment below tells we are "*not* properly track 'dirty' for culture" // This should be changed to 4 as soon a this functionality works. Currently it is always 3 due to the sleep @@ -2325,8 +2361,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // alas, at the moment we do *not* properly track 'dirty' for cultures, meaning // that we cannot synchronize dates the way we do with publish dates - and so this // would fail - the version UpdateDate is greater than the cultures'. - //Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langFr.IsoCode)); - //Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langDa.IsoCode)); + // Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langFr.IsoCode)); + // Assert.AreEqual(versions[0].UpdateDate, versions[0].GetUpdateDate(langDa.IsoCode)); // now roll french back to its very first version page.CopyFrom(versions[4], langFr.IsoCode); // only the pure FR values @@ -2345,18 +2381,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Save_Lazy_Content() { - var contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentService.GetById(Textpage.Id); + IContentType contentType = ContentTypeService.Get("umbTextpage"); + IContent root = ContentService.GetById(Textpage.Id); var c = new Lazy(() => ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Page", root.Id)); var c2 = new Lazy(() => ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Subpage", c.Value.Id)); - var list = new List> {c, c2}; + var list = new List> { c, c2 }; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var repository = DocumentRepository; + IDocumentRepository repository = DocumentRepository; - foreach (var content in list) + foreach (Lazy content in list) { repository.Save(content.Value); } @@ -2370,22 +2406,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(c.Value.ParentId > 0, Is.True); Assert.That(c2.Value.ParentId > 0, Is.True); } - } [Test] public void Can_Verify_Property_Types_On_Content() { // Arrange - var contentTypeService = ContentTypeService; - var contentType = ContentTypeBuilder.CreateAllTypesContentType("allDataTypes", "All DataTypes"); + IContentTypeService contentTypeService = ContentTypeService; + ContentType contentType = ContentTypeBuilder.CreateAllTypesContentType("allDataTypes", "All DataTypes"); ContentTypeService.Save(contentType); - var content = ContentBuilder.CreateAllTypesContent(contentType, "Random Content", Constants.System.Root); + Content content = ContentBuilder.CreateAllTypesContent(contentType, "Random Content", Constants.System.Root); ContentService.Save(content); - var id = content.Id; + int id = content.Id; // Act - var sut = ContentService.GetById(id); + IContent sut = ContentService.GetById(id); // Arrange Assert.That(sut.GetValue("isTrue"), Is.True); @@ -2395,8 +2430,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(sut.GetValue("multilineText"), Is.EqualTo("Multiple lines \n in one box")); Assert.That(sut.GetValue("upload"), Is.EqualTo("/media/1234/koala.jpg")); Assert.That(sut.GetValue("label"), Is.EqualTo("Non-editable label")); - //SD: This is failing because the 'content' call to GetValue always has empty milliseconds - //MCH: I'm guessing this is an issue because of the format the date is actually stored as, right? Cause we don't do any formatting when saving or loading + + // SD: This is failing because the 'content' call to GetValue always has empty milliseconds + // MCH: I'm guessing this is an issue because of the format the date is actually stored as, right? Cause we don't do any formatting when saving or loading Assert.That(sut.GetValue("dateTime").ToString("G"), Is.EqualTo(content.GetValue("dateTime").ToString("G"))); Assert.That(sut.GetValue("colorPicker"), Is.EqualTo("black")); Assert.That(sut.GetValue("ddlMultiple"), Is.EqualTo("1234,1235")); @@ -2415,12 +2451,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Delete_Previous_Versions_Not_Latest() { // Arrange - var content = ContentService.GetById(Trashed.Id); - var version = content.VersionId; + IContent content = ContentService.GetById(Trashed.Id); + int version = content.VersionId; // Act ContentService.DeleteVersion(Trashed.Id, version, true, Constants.Security.SuperUserId); - var sut = ContentService.GetById(Trashed.Id); + IContent sut = ContentService.GetById(Trashed.Id); // Assert Assert.That(sut.VersionId, Is.EqualTo(version)); @@ -2430,21 +2466,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_Paged_Children() { // Start by cleaning the "db" - var umbTextPage = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); + IContent umbTextPage = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); ContentService.Delete(umbTextPage, Constants.Security.SuperUserId); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType); + Content c1 = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(c1); } - var entities = ContentService.GetPagedChildren(Constants.System.Root, 0, 6, out var total).ToArray(); + IContent[] entities = ContentService.GetPagedChildren(Constants.System.Root, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = ContentService.GetPagedChildren(Constants.System.Root, 1, 6, out total).ToArray(); @@ -2456,31 +2492,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_Paged_Children_Dont_Get_Descendants() { // Start by cleaning the "db" - var umbTextPage = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); + IContent umbTextPage = ContentService.GetById(new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0")); ContentService.Delete(umbTextPage, Constants.Security.SuperUserId); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - // only add 9 as we also add a content with children - for (var i = 0; i < 9; i++) + + // Only add 9 as we also add a content with children + for (int i = 0; i < 9; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType); + Content c1 = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(c1); } - var willHaveChildren = ContentBuilder.CreateSimpleContent(contentType); + Content willHaveChildren = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(willHaveChildren); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, "Content" + i, willHaveChildren.Id); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, "Content" + i, willHaveChildren.Id); ContentService.Save(c1); } // children in root including the folder - not the descendants in the folder - var entities = ContentService.GetPagedChildren(Constants.System.Root, 0, 6, out var total).ToArray(); + IContent[] entities = ContentService.GetPagedChildren(Constants.System.Root, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = ContentService.GetPagedChildren(Constants.System.Root, 1, 6, out total).ToArray(); @@ -2516,7 +2553,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! ContentTypeService.Save(contentType); - var content = ContentService.Create("foo", Constants.System.Root, "foo"); + IContent content = ContentService.Create("foo", Constants.System.Root, "foo"); ContentService.Save(content); Assert.IsFalse(content.Published); @@ -2538,7 +2575,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsFalse(content.Published); Assert.IsTrue(content.Edited); - var versions = ContentService.GetVersions(content.Id); + IEnumerable versions = ContentService.GetVersions(content.Id); Assert.AreEqual(1, versions.Count()); // publish content @@ -2570,8 +2607,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("foo", content.GetValue("title", published: true)); Assert.AreEqual("foo", content.GetValue("title")); - var vpk = ((Content) content).VersionId; - var ppk = ((Content) content).PublishedVersionId; + int vpk = ((Content)content).VersionId; + int ppk = ((Content)content).PublishedVersionId; content = ContentService.GetById(content.Id); Assert.IsFalse(content.Published); @@ -2580,13 +2617,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // FIXME: depending on 1 line in ContentBaseFactory.BuildEntity // the published infos can be gone or not // if gone, it's not consistent with above - Assert.AreEqual(vpk, ((Content) content).VersionId); - Assert.AreEqual(ppk, ((Content) content).PublishedVersionId); // still there + Assert.AreEqual(vpk, ((Content)content).VersionId); + Assert.AreEqual(ppk, ((Content)content).PublishedVersionId); // still there // FIXME: depending on 1 line in ContentRepository.MapDtoToContent // the published values can be null or not // if null, it's not consistent with above - //Assert.IsNull(content.GetValue("title", published: true)); + // Assert.IsNull(content.GetValue("title", published: true)); Assert.AreEqual("foo", content.GetValue("title", published: true)); // still there Assert.AreEqual("foo", content.GetValue("title")); @@ -2597,7 +2634,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // and therefore we cannot "just" republish the content - we need to publish some values // so... that's not really an option // - //ContentService.SaveAndPublish(content); + // ContentService.SaveAndPublish(content); // FIXME: what shall we do of all this? /* @@ -2628,22 +2665,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Ensure_Invariant_Name() { - var languageService = LocalizationService; + ILocalizationService languageService = LocalizationService; - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); languageService.Save(langFr); languageService.Save(langUk); - var contentTypeService = ContentTypeService; + IContentTypeService contentTypeService = ContentTypeService; - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); contentType.Variations = ContentVariation.Culture; contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Nvarchar, "prop") { Variations = ContentVariation.Culture }); ContentTypeService.Save(contentType); @@ -2654,35 +2691,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("name-fr", langFr.IsoCode); ContentService.Save(content); - //the name will be set to the default culture variant name + // the name will be set to the default culture variant name Assert.AreEqual("name-us", content.Name); // FIXME: should we always sync the invariant name even on update? see EnsureInvariantNameValues ////updating the default culture variant name should also update the invariant name so they stay in sync - //content.SetName("name-us-2", langUk.IsoCode); - //ContentService.Save(content); - //Assert.AreEqual("name-us-2", content.Name); + // content.SetName("name-us-2", langUk.IsoCode); + // ContentService.Save(content); + // Assert.AreEqual("name-us-2", content.Name); } [Test] public void Ensure_Unique_Culture_Names() { - var languageService = LocalizationService; + ILocalizationService languageService = LocalizationService; - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); languageService.Save(langFr); languageService.Save(langUk); - var contentTypeService = ContentTypeService; + IContentTypeService contentTypeService = ContentTypeService; - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); @@ -2690,34 +2727,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services content.SetCultureName("root", langUk.IsoCode); ContentService.Save(content); - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { var child = new Content(null, content, contentType); child.SetCultureName("child", langUk.IsoCode); ContentService.Save(child); - Assert.AreEqual("child" + (i == 0 ? "" : " (" + i + ")"), child.GetCultureName(langUk.IsoCode)); + Assert.AreEqual("child" + (i == 0 ? string.Empty : " (" + i + ")"), child.GetCultureName(langUk.IsoCode)); - //Save it again to ensure that the unique check is not performed again against it's own name + // Save it again to ensure that the unique check is not performed again against it's own name ContentService.Save(child); - Assert.AreEqual("child" + (i == 0 ? "" : " (" + i + ")"), child.GetCultureName(langUk.IsoCode)); + Assert.AreEqual("child" + (i == 0 ? string.Empty : " (" + i + ")"), child.GetCultureName(langUk.IsoCode)); } } [Test] public void Can_Get_Paged_Children_WithFilterAndOrder() { - var languageService = LocalizationService; + ILocalizationService languageService = LocalizationService; - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .WithIsDefault(true) .WithIsMandatory(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); - var langDa = new LanguageBuilder() + ILanguage langDa = new LanguageBuilder() .WithCultureInfo("da-DK") .Build(); @@ -2725,14 +2762,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services languageService.Save(langUk); languageService.Save(langDa); - var contentTypeService = ContentTypeService; + IContentTypeService contentTypeService = ContentTypeService; - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var o = new[] { 2, 1, 3, 0, 4 }; // randomly different - for (var i = 0; i < 5; i++) + int[] o = new[] { 2, 1, 3, 0, 4 }; // randomly different + for (int i = 0; i < 5; i++) { var contentA = new Content(null, Constants.System.Root, contentType); contentA.SetCultureName("contentA" + i + "uk", langUk.IsoCode); @@ -2748,7 +2785,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } // get all - var list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out var total).ToList(); + var list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out long total).ToList(); Console.WriteLine("ALL"); WriteList(list); @@ -2757,10 +2794,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(11, total); Assert.AreEqual(11, list.Count); - var sqlContext = GetRequiredService(); + ISqlContext sqlContext = GetRequiredService(); // filter - list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out total, + list = ContentService.GetPagedChildren( + Constants.System.Root, + 0, + 100, + out total, sqlContext.Query().Where(x => x.Name.Contains("contentX")), Ordering.By("name", culture: langFr.IsoCode)).ToList(); @@ -2768,7 +2809,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(0, list.Count); // filter - list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out total, + list = ContentService.GetPagedChildren( + Constants.System.Root, + 0, + 100, + out total, sqlContext.Query().Where(x => x.Name.Contains("contentX")), Ordering.By("name", culture: langDa.IsoCode)).ToList(); @@ -2779,7 +2824,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(10, list.Count); // filter - list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out total, + list = ContentService.GetPagedChildren( + Constants.System.Root, + 0, + 100, + out total, sqlContext.Query().Where(x => x.Name.Contains("contentA")), Ordering.By("name", culture: langFr.IsoCode)).ToList(); @@ -2789,10 +2838,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, total); Assert.AreEqual(5, list.Count); - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) + { Assert.AreEqual("contentA" + i + "fr", list[i].GetCultureName(langFr.IsoCode)); + } - list = ContentService.GetPagedChildren(Constants.System.Root, 0, 100, out total, + list = ContentService.GetPagedChildren( + Constants.System.Root, + 0, + 100, + out total, sqlContext.Query().Where(x => x.Name.Contains("contentA")), Ordering.By("name", direction: Direction.Descending, culture: langFr.IsoCode)).ToList(); @@ -2802,32 +2857,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(5, total); Assert.AreEqual(5, list.Count); - for (var i = 0; i < 5; i++) - Assert.AreEqual("contentA" + (4-i) + "fr", list[i].GetCultureName(langFr.IsoCode)); + for (int i = 0; i < 5; i++) + { + Assert.AreEqual("contentA" + (4 - i) + "fr", list[i].GetCultureName(langFr.IsoCode)); + } } private void WriteList(List list) { - foreach (var content in list) + foreach (IContent content in list) + { Console.WriteLine("[{0}] {1} {2} {3} {4}", content.Id, content.Name, content.GetCultureName("en-GB"), content.GetCultureName("fr-FR"), content.GetCultureName("da-DK")); + } + Console.WriteLine("-"); } [Test] public void Can_SaveRead_Variations() { - var languageService = LocalizationService; - var langPt = new LanguageBuilder() + ILocalizationService languageService = LocalizationService; + ILanguage langPt = new LanguageBuilder() .WithCultureInfo("pt-PT") .WithIsDefault(true) .Build(); - var langFr = new LanguageBuilder() + ILanguage langFr = new LanguageBuilder() .WithCultureInfo("fr-FR") .Build(); - var langUk = new LanguageBuilder() + ILanguage langUk = new LanguageBuilder() .WithCultureInfo("en-GB") .Build(); - var langDe = new LanguageBuilder() + ILanguage langDe = new LanguageBuilder() .WithCultureInfo("de-DE") .Build(); @@ -2835,25 +2895,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services languageService.Save(langUk); languageService.Save(langDe); - var contentTypeService = ContentTypeService; + IContentTypeService contentTypeService = ContentTypeService; - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); contentType.Variations = ContentVariation.Culture; contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Nvarchar, "prop") { Variations = ContentVariation.Culture }); + // FIXME: add test w/ an invariant prop ContentTypeService.Save(contentType); - var content = ContentService.Create("Home US", Constants.System.Root, "umbTextpage"); + IContent content = ContentService.Create("Home US", Constants.System.Root, "umbTextpage"); // creating content with a name but no culture - will set the invariant name // but, because that content is variant, as soon as we save, we'll need to // replace the invariant name with whatever we have in cultures - always // // in fact, that would throw, because there is no name - //ContentService.Save(content); - - // act + // ContentService.Save(content); + // Act content.SetValue("author", "Barack Obama"); content.SetValue("prop", "value-fr1", langFr.IsoCode); content.SetValue("prop", "value-uk1", langUk.IsoCode); @@ -2863,8 +2923,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // content has been saved, // it has names, but no publishNames, and no published cultures - - var content2 = ContentService.GetById(content.Id); + IContent content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr", content2.Name); // got the default culture name when saved Assert.AreEqual("name-fr", content2.GetCultureName(langFr.IsoCode)); @@ -2891,14 +2950,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.IsCultureEdited(c), (langFr, true), (langUk, true), (langDe, false)); AssertPerCulture(content2, (x, c) => x.IsCultureEdited(c), (langFr, true), (langUk, true), (langDe, false)); - // act - - ContentService.SaveAndPublish(content, new[]{ langFr.IsoCode, langUk.IsoCode }); + // Act + ContentService.SaveAndPublish(content, new[] { langFr.IsoCode, langUk.IsoCode }); // both FR and UK have been published, // and content has been published, // it has names, publishNames, and published cultures - content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr", content2.Name); // got the default culture name when saved @@ -2935,20 +2992,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // note that content and content2 culture published dates might be slightly different due to roundtrip to database - - // act - + // Act ContentService.SaveAndPublish(content); // now it has publish name for invariant neutral - content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr", content2.PublishName); - - // act - content.SetCultureName("Home US2", null); content.SetCultureName("name-fr2", langFr.IsoCode); content.SetCultureName("name-uk2", langUk.IsoCode); @@ -2959,7 +3010,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // content has been saved, // it has updated names, unchanged publishNames, and published cultures - content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr2", content2.Name); // got the default culture name when saved @@ -2993,16 +3043,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langFr, false), (langUk, false)); // DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langFr, false), (langUk, false)); // DE would throw - - // act + // Act // cannot just 'save' since we are changing what's published! - ContentService.Unpublish(content, langFr.IsoCode); // content has been published, // the french culture is gone // (only if french is not mandatory, else everything would be gone!) - content2 = ContentService.GetById(content.Id); Assert.AreEqual("name-fr2", content2.Name); // got the default culture name when saved @@ -3036,9 +3083,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw - - // act - + // Act ContentService.Unpublish(content); // content has been unpublished, @@ -3050,7 +3095,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // its exact previous state, properties and names etc. retain their published // values even though the content is not published - hence many things being // non-null or true below - always check against content.Published to be sure - content2 = ContentService.GetById(content.Id); Assert.IsFalse(content2.Published); @@ -3083,18 +3127,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw - - // act + // Act // that HAS to be SavePublishing, because SaveAndPublish would just republish everything! - //TODO: This is using an internal API - the test can't pass without this but we want to keep the test here + // TODO: This is using an internal API - the test can't pass without this but we want to keep the test here // will need stephane to have a look at this test at some stage since there is a lot of logic here that we // want to keep on testing but don't need the public API to do these more complicated things. ContentService.CommitDocumentChanges(content); // content has been re-published, // everything is back to what it was before being unpublished - content2 = ContentService.GetById(content.Id); Assert.IsTrue(content2.Published); @@ -3127,9 +3169,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw - - // act - + // Act ContentService.SaveAndPublish(content, langUk.IsoCode); content2 = ContentService.GetById(content.Id); @@ -3149,9 +3189,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services AssertPerCulture(content, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw AssertPerCulture(content2, (x, c) => x.GetPublishDate(c) == DateTime.MinValue, (langUk, false)); // FR, DE would throw - - // act - + // Act content.SetCultureName("name-uk3", langUk.IsoCode); ContentService.Save(content); @@ -3161,30 +3199,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // but they change, on what's being saved, and when getting it back // changing the name = edited! - Assert.IsTrue(content.IsCultureEdited(langUk.IsoCode)); Assert.IsTrue(content2.IsCultureEdited(langUk.IsoCode)); } private void AssertPerCulture(IContent item, Func getter, params (ILanguage Language, bool Result)[] testCases) { - foreach (var testCase in testCases) + foreach ((ILanguage Language, bool Result) testCase in testCases) { - var value = getter(item, testCase.Language.IsoCode); + T value = getter(item, testCase.Language.IsoCode); Assert.AreEqual(testCase.Result, value, $"Expected {testCase.Result} and got {value} for culture {testCase.Language.IsoCode}."); } } private IEnumerable CreateContentHierarchy() { - var contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentService.GetById(Textpage.Id); + IContentType contentType = ContentTypeService.Get("umbTextpage"); + IContent root = ContentService.GetById(Textpage.Id); var list = new List(); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var content = ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Page " + i, root); + Content content = ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Page " + i, root); list.Add(content); list.AddRange(CreateChildrenOf(contentType, content, 4)); @@ -3198,13 +3235,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private IEnumerable CreateChildrenOf(IContentType contentType, IContent content, int depth) { var list = new List(); - for (var i = 0; i < depth; i++) + for (int i = 0; i < depth; i++) { - var c = ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Subpage " + i, content); + Content c = ContentBuilder.CreateSimpleContent(contentType, "Hierarchy Simple Text Subpage " + i, content); list.Add(c); Debug.Print("Created: 'Hierarchy Simple Text Subpage {0}' - Depth: {1}", i, depth); } + return list; } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs index e5234205c4..469a806335 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceTests.cs @@ -1,7 +1,9 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Events; @@ -20,27 +22,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class ContentTypeServiceTests : UmbracoIntegrationTest { private IFileService FileService => GetRequiredService(); + private ContentService ContentService => (ContentService)GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private ContentTypeService ContentTypeService => (ContentTypeService)GetRequiredService(); [Test] public void CanSaveAndGetIsElement() { - //create content type with a property type that varies by culture + // create content type with a property type that varies by culture IContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = ContentVariation.Nothing; - var contentCollection = new PropertyTypeCollection(true); - contentCollection.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext) + var contentCollection = new PropertyTypeCollection(true) { - Alias = "title", - Name = "Title", - Description = "", - Mandatory = false, - SortOrder = 1, - DataTypeId = -88, - Variations = ContentVariation.Nothing - }); + new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext) + { + Alias = "title", + Name = "Title", + Description = string.Empty, + Mandatory = false, + SortOrder = 1, + DataTypeId = -88, + Variations = ContentVariation.Nothing + } + }; contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); ContentTypeService.Save(contentType); @@ -57,7 +64,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Deleting_Content_Type_With_Hierarchy_Of_Content_Items_Moves_Orphaned_Content_To_Recycle_Bin() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType1 = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); @@ -70,17 +77,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services FileService.SaveTemplate(contentType3.DefaultTemplate); ContentTypeService.Save(contentType3); - var contentTypes = new[] { contentType1, contentType2, contentType3 }; - var parentId = -1; + IContentType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; + int parentId = -1; var ids = new List(); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - for (var index = 0; index < contentTypes.Length; index++) + for (int index = 0; index < contentTypes.Length; index++) { - var contentType = contentTypes[index]; - var contentItem = ContentBuilder.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); + IContentType contentType = contentTypes[index]; + Content contentItem = ContentBuilder.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); ContentService.Save(contentItem); ContentService.SaveAndPublish(contentItem); parentId = contentItem.Id; @@ -89,13 +96,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } } - //delete the first content type, all other content of different content types should be in the recycle bin + // delete the first content type, all other content of different content types should be in the recycle bin ContentTypeService.Delete(contentTypes[0]); - var found = ContentService.GetByIds(ids); + IEnumerable found = ContentService.GetByIds(ids); Assert.AreEqual(4, found.Count()); - foreach (var content in found) + foreach (IContent content in found) { Assert.IsTrue(content.Trashed); } @@ -108,7 +115,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services try { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType1 = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); @@ -121,22 +128,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services FileService.SaveTemplate(contentType3.DefaultTemplate); ContentTypeService.Save(contentType3); - var contentTypes = new[] { contentType1, contentType2, contentType3 }; - var parentId = -1; + IContentType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; + int parentId = -1; - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - for (var index = 0; index < contentTypes.Length; index++) + for (int index = 0; index < contentTypes.Length; index++) { - var contentType = contentTypes[index]; - var contentItem = ContentBuilder.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); + IContentType contentType = contentTypes[index]; + Content contentItem = ContentBuilder.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); ContentService.Save(contentItem); ContentService.SaveAndPublish(contentItem); parentId = contentItem.Id; } } - foreach (var contentType in contentTypes.Reverse()) + foreach (IContentType contentType in contentTypes.Reverse()) { ContentTypeService.Delete(contentType); } @@ -154,7 +161,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services try { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType1 = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); @@ -167,17 +174,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services FileService.SaveTemplate(contentType3.DefaultTemplate); ContentTypeService.Save(contentType3); - var root = ContentBuilder.CreateSimpleContent(contentType1, "Root", -1); + Content root = ContentBuilder.CreateSimpleContent(contentType1, "Root", -1); ContentService.Save(root); ContentService.SaveAndPublish(root); - var level1 = ContentBuilder.CreateSimpleContent(contentType2, "L1", root.Id); + Content level1 = ContentBuilder.CreateSimpleContent(contentType2, "L1", root.Id); ContentService.Save(level1); ContentService.SaveAndPublish(level1); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - var level3 = ContentBuilder.CreateSimpleContent(contentType3, "L2" + i, level1.Id); + Content level3 = ContentBuilder.CreateSimpleContent(contentType3, "L2" + i, level1.Id); ContentService.Save(level3); ContentService.SaveAndPublish(level3); } @@ -192,19 +199,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void ContentServiceOnTrashed(IContentService sender, MoveEventArgs e) { - foreach (var item in e.MoveInfoCollection) + foreach (MoveEventInfo item in e.MoveInfoCollection) { - //if this item doesn't exist then Fail! - var exists = ContentService.GetById(item.Entity.Id); + // if this item doesn't exist then Fail! + IContent exists = ContentService.GetById(item.Entity.Id); if (exists == null) + { Assert.Fail("The item doesn't exist"); + } } } [Test] public void Deleting_PropertyType_Removes_The_Property_From_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); IContentType contentType1 = ContentTypeBuilder.CreateTextPageContentType("test1", "Test1", defaultTemplateId: template.Id); @@ -212,13 +221,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(contentType1); IContent contentItem = ContentBuilder.CreateTextpageContent(contentType1, "Testing", -1); ContentService.SaveAndPublish(contentItem); - var initProps = contentItem.Properties.Count; + int initProps = contentItem.Properties.Count; - //remove a property + // remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ContentTypeService.Save(contentType1); - //re-load it from the db + // re-load it from the db contentItem = ContentService.GetById(contentItem.Id); Assert.AreEqual(initProps - 1, contentItem.Properties.Count); @@ -228,15 +237,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_Descendants() { // Arrange - var contentTypeService = ContentTypeService; - var hierarchy = CreateContentTypeHierarchy(); - contentTypeService.Save(hierarchy, 0); //ensure they are saved! - var master = hierarchy.First(); + ContentTypeService contentTypeService = ContentTypeService; + IContentType[] hierarchy = CreateContentTypeHierarchy(); + contentTypeService.Save(hierarchy, 0); // ensure they are saved! + IContentType master = hierarchy.First(); - //Act - var descendants = contentTypeService.GetDescendants(master.Id, false); + // Act + IEnumerable descendants = contentTypeService.GetDescendants(master.Id, false); - //Assert + // Assert Assert.AreEqual(10, descendants.Count()); } @@ -244,15 +253,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_Descendants_And_Self() { // Arrange - var contentTypeService = ContentTypeService; - var hierarchy = CreateContentTypeHierarchy(); - contentTypeService.Save(hierarchy, 0); //ensure they are saved! - var master = hierarchy.First(); + ContentTypeService contentTypeService = ContentTypeService; + IContentType[] hierarchy = CreateContentTypeHierarchy(); + contentTypeService.Save(hierarchy, 0); // ensure they are saved! + IContentType master = hierarchy.First(); - //Act - var descendants = contentTypeService.GetDescendants(master.Id, true); + // Act + IEnumerable descendants = contentTypeService.GetDescendants(master.Id, true); - //Assert + // Assert Assert.AreEqual(11, descendants.Count()); } @@ -260,19 +269,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Bulk_Save_New_Hierarchy_Content_Types() { // Arrange - var contentTypeService = ContentTypeService; - var hierarchy = CreateContentTypeHierarchy(); + ContentTypeService contentTypeService = ContentTypeService; + IContentType[] hierarchy = CreateContentTypeHierarchy(); // Act contentTypeService.Save(hierarchy, 0); Assert.That(hierarchy.Any(), Is.True); Assert.That(hierarchy.Any(x => x.HasIdentity == false), Is.False); - //all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown + + // all parent ids should be ok, they are lazy and if they equal zero an exception will be thrown Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); - for (var i = 0; i < hierarchy.Count(); i++) + for (int i = 0; i < hierarchy.Count(); i++) { - if (i == 0) continue; + if (i == 0) + { + continue; + } + Assert.AreEqual(hierarchy.ElementAt(i).ParentId, hierarchy.ElementAt(i - 1).Id); } } @@ -281,16 +295,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Save_ContentType_Structure_And_Create_Content_Based_On_It() { // Arrange - var cs = ContentService; - var cts = ContentTypeService; - var dtdYesNo = DataTypeService.GetDataType(-49); + ContentService cs = ContentService; + ContentTypeService cts = ContentTypeService; + IDataType dtdYesNo = DataTypeService.GetDataType(-49); var ctBase = new ContentType(ShortStringHelper, -1) { Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png" }; ctBase.AddPropertyType(new PropertyType(ShortStringHelper, dtdYesNo, Constants.Conventions.Content.NaviHide) { Name = "Hide From Navigation", - } - /*,"Navigation"*/); - cts.Save(ctBase); + }); + /*,"Navigation"*/ cts.Save(ctBase); const string contentTypeAlias = "HomePage"; var ctHomePage = new ContentType(ShortStringHelper, ctBase, contentTypeAlias) @@ -301,12 +314,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Thumbnail = "folder.png", AllowedAsRoot = true }; - ctHomePage.AddPropertyType(new PropertyType(ShortStringHelper, dtdYesNo, "someProperty") { Name = "Some property" } - /*,"Navigation"*/); - cts.Save(ctHomePage); + ctHomePage.AddPropertyType(new PropertyType(ShortStringHelper, dtdYesNo, "someProperty") { Name = "Some property" }); + /*,"Navigation"*/ cts.Save(ctHomePage); // Act - var homeDoc = cs.Create("Home Page", -1, contentTypeAlias); + IContent homeDoc = cs.Create("Home Page", -1, contentTypeAlias); cs.SaveAndPublish(homeDoc); // Assert @@ -331,13 +343,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Trashed = false }; - contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, DataTypeId = -88 }); - contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TinyMce, ValueStorageType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, DataTypeId = -87 }); + contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { Name = "Title", Description = string.Empty, Mandatory = false, DataTypeId = -88 }); + contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TinyMce, ValueStorageType.Ntext, "bodyText") { Name = "Body Text", Description = string.Empty, Mandatory = false, DataTypeId = -87 }); contentType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { Name = "Author", Description = "Name of the author", Mandatory = false, DataTypeId = -88 }); ContentTypeService.Save(contentType); - var sortOrders = contentType.PropertyTypes.Select(x => x.SortOrder).ToArray(); + int[] sortOrders = contentType.PropertyTypes.Select(x => x.SortOrder).ToArray(); Assert.AreEqual(1, sortOrders.Count(x => x == 0)); Assert.AreEqual(1, sortOrders.Count(x => x == 1)); @@ -352,22 +364,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services * - Components * - Category */ - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var global = ContentTypeBuilder.CreateSimpleContentType("global", "Global", defaultTemplateId: template.Id); + ContentType global = ContentTypeBuilder.CreateSimpleContentType("global", "Global", defaultTemplateId: template.Id); ContentTypeService.Save(global); - var components = ContentTypeBuilder.CreateSimpleContentType("components", "Components", global, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType components = ContentTypeBuilder.CreateSimpleContentType("components", "Components", global, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(components); - var component = ContentTypeBuilder.CreateSimpleContentType("component", "Component", components, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType component = ContentTypeBuilder.CreateSimpleContentType("component", "Component", components, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(component); - var category = ContentTypeBuilder.CreateSimpleContentType("category", "Category", global, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType category = ContentTypeBuilder.CreateSimpleContentType("category", "Category", global, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(category); - var success = category.AddContentType(component); + bool success = category.AddContentType(component); Assert.That(success, Is.False); } @@ -375,15 +387,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Delete_Parent_ContentType_When_Child_Has_Content() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var childContentType = ContentTypeBuilder.CreateSimpleContentType("childPage", "Child Page", contentType, randomizeAliases: true, propertyGroupName: "Child Content", defaultTemplateId: template.Id); + ContentType childContentType = ContentTypeBuilder.CreateSimpleContentType("childPage", "Child Page", contentType, randomizeAliases: true, propertyGroupName: "Child Content", defaultTemplateId: template.Id); ContentTypeService.Save(childContentType); - var content = ContentService.Create("Page 1", -1, childContentType.Alias); + IContent content = ContentService.Create("Page 1", -1, childContentType.Alias); ContentService.Save(content); ContentTypeService.Delete(contentType); @@ -394,9 +406,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreNotEqual(0, childContentType.Id); Assert.IsNotNull(contentType.Id); Assert.AreNotEqual(0, contentType.Id); - var deletedContent = ContentService.GetById(content.Id); - var deletedChildContentType = ContentTypeService.Get(childContentType.Id); - var deletedContentType = ContentTypeService.Get(contentType.Id); + IContent deletedContent = ContentService.GetById(content.Id); + IContentType deletedChildContentType = ContentTypeService.Get(childContentType.Id); + IContentType deletedContentType = ContentTypeService.Get(contentType.Id); Assert.IsNull(deletedChildContentType); Assert.IsNull(deletedContent); @@ -407,15 +419,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Create_Container() { // Arrange - var cts = ContentTypeService; + ContentTypeService cts = ContentTypeService; // Act - var container = new EntityContainer(Constants.ObjectTypes.DocumentType); - container.Name = "container1"; + var container = new EntityContainer(Constants.ObjectTypes.DocumentType) + { + Name = "container1" + }; cts.SaveContainer(container); // Assert - var createdContainer = cts.GetContainer(container.Id); + EntityContainer createdContainer = cts.GetContainer(container.Id); Assert.IsNotNull(createdContainer); } @@ -423,37 +437,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_All_Containers() { // Arrange - var cts = ContentTypeService; + ContentTypeService cts = ContentTypeService; // Act - var container1 = new EntityContainer(Constants.ObjectTypes.DocumentType); - container1.Name = "container1"; + var container1 = new EntityContainer(Constants.ObjectTypes.DocumentType) + { + Name = "container1" + }; cts.SaveContainer(container1); - var container2 = new EntityContainer(Constants.ObjectTypes.DocumentType); - container2.Name = "container2"; + var container2 = new EntityContainer(Constants.ObjectTypes.DocumentType) + { + Name = "container2" + }; cts.SaveContainer(container2); // Assert - var containers = cts.GetContainers(new int[0]); + IEnumerable containers = cts.GetContainers(new int[0]); Assert.AreEqual(2, containers.Count()); } [Test] public void Deleting_ContentType_Sends_Correct_Number_Of_DeletedEntities_In_Events() { - var deletedEntities = 0; + int deletedEntities = 0; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - ContentTypeService.Deleted += (sender, args) => - { - deletedEntities += args.DeletedEntities.Count(); - }; + ContentTypeService.Deleted += (sender, args) => deletedEntities += args.DeletedEntities.Count(); ContentTypeService.Delete(contentType); @@ -463,20 +478,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Deleting_Multiple_ContentTypes_Sends_Correct_Number_Of_DeletedEntities_In_Events() { - var deletedEntities = 0; + int deletedEntities = 0; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var contentType2 = ContentTypeBuilder.CreateSimpleContentType("otherPage", "Other page", defaultTemplateId: template.Id); + ContentType contentType2 = ContentTypeBuilder.CreateSimpleContentType("otherPage", "Other page", defaultTemplateId: template.Id); ContentTypeService.Save(contentType2); - ContentTypeService.Deleted += (sender, args) => - { - deletedEntities += args.DeletedEntities.Count(); - }; + ContentTypeService.Deleted += (sender, args) => deletedEntities += args.DeletedEntities.Count(); ContentTypeService.Delete(contentType); ContentTypeService.Delete(contentType2); @@ -487,21 +499,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Deleting_ContentType_With_Child_Sends_Correct_Number_Of_DeletedEntities_In_Events() { - var deletedEntities = 0; + int deletedEntities = 0; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("page", "Page", defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var contentType2 = ContentTypeBuilder.CreateSimpleContentType("subPage", "Sub page", defaultTemplateId: template.Id); + ContentType contentType2 = ContentTypeBuilder.CreateSimpleContentType("subPage", "Sub page", defaultTemplateId: template.Id); contentType2.ParentId = contentType.Id; ContentTypeService.Save(contentType2); - ContentTypeService.Deleted += (sender, args) => - { - deletedEntities += args.DeletedEntities.Count(); - }; + ContentTypeService.Deleted += (sender, args) => deletedEntities += args.DeletedEntities.Count(); ContentTypeService.Delete(contentType); @@ -511,37 +520,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Remove_ContentType_Composition_From_ContentType() { - //Test for U4-2234 - var cts = ContentTypeService; - //Arrange - var component = CreateComponent(); + // Test for U4-2234 + ContentTypeService cts = ContentTypeService; + + // Arrange + ContentType component = CreateComponent(); cts.Save(component); - var banner = CreateBannerComponent(component); + ContentType banner = CreateBannerComponent(component); cts.Save(banner); - var site = CreateSite(); + ContentType site = CreateSite(); cts.Save(site); - var homepage = CreateHomepage(site); + ContentType homepage = CreateHomepage(site); cts.Save(homepage); - //Add banner to homepage - var added = homepage.AddContentType(banner); + // Add banner to homepage + bool added = homepage.AddContentType(banner); cts.Save(homepage); - //Assert composition - var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); - var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); + // Assert composition + bool bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); + bool bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(added, Is.True); Assert.That(bannerExists, Is.True); Assert.That(bannerPropertyExists, Is.True); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); - //Remove banner from homepage - var removed = homepage.RemoveContentType(banner.Alias); + // Remove banner from homepage + bool removed = homepage.RemoveContentType(banner.Alias); cts.Save(homepage); - //Assert composition - var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); - var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); + // Assert composition + bool bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); + bool bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(removed, Is.True); Assert.That(bannerStillExists, Is.False); Assert.That(bannerPropertyStillExists, Is.False); @@ -552,25 +562,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_ContentType_By_Performing_Clone() { // Arrange - var metaContentType = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaContentType = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaContentType); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); var simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType, defaultTemplateId: template.Id) as IContentType; ContentTypeService.Save(simpleContentType); - var categoryId = simpleContentType.Id; + int categoryId = simpleContentType.Id; // Act - var sut = simpleContentType.DeepCloneWithResetIdentities("newcategory"); + IContentType sut = simpleContentType.DeepCloneWithResetIdentities("newcategory"); Assert.IsNotNull(sut); ContentTypeService.Save(sut); // Assert Assert.That(sut.HasIdentity, Is.True); - var contentType = ContentTypeService.Get(sut.Id); - var category = ContentTypeService.Get(categoryId); + IContentType contentType = ContentTypeService.Get(sut.Id); + IContentType category = ContentTypeService.Get(categoryId); Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); Assert.AreEqual(contentType.ParentId, category.ParentId); @@ -588,19 +598,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_ContentType_To_New_Parent_By_Performing_Clone() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var parentContentType1 = ContentTypeBuilder.CreateSimpleContentType("parent1", "Parent1", defaultTemplateId: template.Id); + ContentType parentContentType1 = ContentTypeBuilder.CreateSimpleContentType("parent1", "Parent1", defaultTemplateId: template.Id); ContentTypeService.Save(parentContentType1); - var parentContentType2 = ContentTypeBuilder.CreateSimpleContentType("parent2", "Parent2", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType parentContentType2 = ContentTypeBuilder.CreateSimpleContentType("parent2", "Parent2", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(parentContentType2); var simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", parentContentType1, randomizeAliases: true, defaultTemplateId: template.Id) as IContentType; ContentTypeService.Save(simpleContentType); // Act - var clone = simpleContentType.DeepCloneWithResetIdentities("newcategory"); + IContentType clone = simpleContentType.DeepCloneWithResetIdentities("newcategory"); Assert.IsNotNull(clone); clone.RemoveContentType("parent1"); clone.AddContentType(parentContentType2); @@ -610,8 +620,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.That(clone.HasIdentity, Is.True); - var clonedContentType = ContentTypeService.Get(clone.Id); - var originalContentType = ContentTypeService.Get(simpleContentType.Id); + IContentType clonedContentType = ContentTypeService.Get(clone.Id); + IContentType originalContentType = ContentTypeService.Get(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); @@ -634,26 +644,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_ContentType_With_Service_To_Root() { // Arrange - var metaContentType = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaContentType = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaContentType); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType, defaultTemplateId: template.Id); + ContentType simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType, defaultTemplateId: template.Id); ContentTypeService.Save(simpleContentType); - var categoryId = simpleContentType.Id; + int categoryId = simpleContentType.Id; // Act - var clone = ContentTypeService.Copy(simpleContentType, "newcategory", "new category"); + IContentType clone = ContentTypeService.Copy(simpleContentType, "newcategory", "new category"); // Assert Assert.That(clone.HasIdentity, Is.True); - var cloned = ContentTypeService.Get(clone.Id); - var original = ContentTypeService.Get(categoryId); + IContentType cloned = ContentTypeService.Get(clone.Id); + IContentType original = ContentTypeService.Get(categoryId); - Assert.That(cloned.CompositionAliases().Any(x => x.Equals("meta")), Is.False); //it's been copied to root + Assert.That(cloned.CompositionAliases().Any(x => x.Equals("meta")), Is.False); // it's been copied to root Assert.AreEqual(cloned.ParentId, -1); Assert.AreEqual(cloned.Level, 1); Assert.AreEqual(cloned.PropertyTypes.Count(), original.PropertyTypes.Count()); @@ -662,13 +672,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int i = 0; i < cloned.PropertyGroups.Count; i++) { Assert.AreEqual(cloned.PropertyGroups[i].PropertyTypes.Count, original.PropertyGroups[i].PropertyTypes.Count); - foreach (var propertyType in cloned.PropertyGroups[i].PropertyTypes) + foreach (IPropertyType propertyType in cloned.PropertyGroups[i].PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } } - foreach (var propertyType in cloned.PropertyTypes) + foreach (IPropertyType propertyType in cloned.PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } @@ -685,25 +695,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_ContentType_To_New_Parent_With_Service() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var parentContentType1 = ContentTypeBuilder.CreateSimpleContentType("parent1", "Parent1", defaultTemplateId: template.Id); + ContentType parentContentType1 = ContentTypeBuilder.CreateSimpleContentType("parent1", "Parent1", defaultTemplateId: template.Id); ContentTypeService.Save(parentContentType1); - var parentContentType2 = ContentTypeBuilder.CreateSimpleContentType("parent2", "Parent2", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType parentContentType2 = ContentTypeBuilder.CreateSimpleContentType("parent2", "Parent2", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(parentContentType2); - var simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", parentContentType1, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType simpleContentType = ContentTypeBuilder.CreateSimpleContentType("category", "Category", parentContentType1, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(simpleContentType); // Act - var clone = ContentTypeService.Copy(simpleContentType, "newAlias", "new alias", parentContentType2); + IContentType clone = ContentTypeService.Copy(simpleContentType, "newAlias", "new alias", parentContentType2); // Assert Assert.That(clone.HasIdentity, Is.True); - var clonedContentType = ContentTypeService.Get(clone.Id); - var originalContentType = ContentTypeService.Get(simpleContentType.Id); + IContentType clonedContentType = ContentTypeService.Get(clone.Id); + IContentType originalContentType = ContentTypeService.Get(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); @@ -725,29 +735,29 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Cannot_Add_Duplicate_PropertyType_Alias_To_Referenced_Composition() { - //Related the second issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 + // Related the second issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var parent = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType parent = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(parent); - var child = ContentTypeBuilder.CreateSimpleContentType("simpleChildPage", "Simple Child Page", parent, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType child = ContentTypeBuilder.CreateSimpleContentType("simpleChildPage", "Simple Child Page", parent, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(child); - var composition = ContentTypeBuilder.CreateMetaContentType(); + ContentType composition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(composition); - //Adding Meta-composition to child doc type + // Adding Meta-composition to child doc type child.AddContentType(composition); ContentTypeService.Save(child); // Act var duplicatePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var added = composition.AddPropertyType(duplicatePropertyType, "Meta"); + bool added = composition.AddPropertyType(duplicatePropertyType, "Meta"); // Assert Assert.That(added, Is.True); @@ -759,35 +769,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Add_Duplicate_PropertyType_Alias_In_Composition_Graph() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var basePage = ContentTypeBuilder.CreateSimpleContentType("basePage", "Base Page", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType basePage = ContentTypeBuilder.CreateSimpleContentType("basePage", "Base Page", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", basePage, defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", basePage, defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(advancedPage); - var metaComposition = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaComposition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaComposition); - var seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); + ContentType seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); ContentTypeService.Save(seoComposition); - var metaAdded = contentPage.AddContentType(metaComposition); + bool metaAdded = contentPage.AddContentType(metaComposition); ContentTypeService.Save(contentPage); - var seoAdded = advancedPage.AddContentType(seoComposition); + bool seoAdded = advancedPage.AddContentType(seoComposition); ContentTypeService.Save(advancedPage); // Act var duplicatePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var addedToBasePage = basePage.AddPropertyType(duplicatePropertyType, "Content"); - var addedToAdvancedPage = advancedPage.AddPropertyType(duplicatePropertyType, "Content"); - var addedToMeta = metaComposition.AddPropertyType(duplicatePropertyType, "Meta"); - var addedToSeo = seoComposition.AddPropertyType(duplicatePropertyType, "Seo"); + bool addedToBasePage = basePage.AddPropertyType(duplicatePropertyType, "Content"); + bool addedToAdvancedPage = advancedPage.AddPropertyType(duplicatePropertyType, "Content"); + bool addedToMeta = metaComposition.AddPropertyType(duplicatePropertyType, "Meta"); + bool addedToSeo = seoComposition.AddPropertyType(duplicatePropertyType, "Seo"); // Assert Assert.That(metaAdded, Is.True); @@ -822,40 +832,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services */ // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); - var compositionAdded = advancedPage.AddContentType(contentMetaComposition); + bool compositionAdded = advancedPage.AddContentType(contentMetaComposition); ContentTypeService.Save(advancedPage); - //NOTE: It should not be possible to Save 'BasePage' with the Title PropertyType added + // NOTE: It should not be possible to Save 'BasePage' with the Title PropertyType added var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); + bool titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); // Assert Assert.That(bodyTextAdded, Is.True); @@ -873,7 +883,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_ContentType_With_Empty_Name() { // Arrange - var contentType = ContentTypeBuilder.CreateSimpleContentType("contentType", string.Empty); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("contentType", string.Empty); // Act & Assert Assert.Throws(() => ContentTypeService.Save(contentType)); @@ -892,55 +902,55 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services */ // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var moreAdvancedPage = ContentTypeBuilder.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); + ContentType moreAdvancedPage = ContentTypeBuilder.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); ContentTypeService.Save(moreAdvancedPage); - var seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); + ContentType seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); ContentTypeService.Save(seoComposition); - var metaComposition = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaComposition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); + bool subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); ContentTypeService.Save(advancedPage); var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); + bool titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); ContentTypeService.Save(seoComposition); - var seoCompositionAdded = advancedPage.AddContentType(seoComposition); - var metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); + bool seoCompositionAdded = advancedPage.AddContentType(seoComposition); + bool metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); ContentTypeService.Save(advancedPage); ContentTypeService.Save(moreAdvancedPage); - var keywordsPropertyType = metaComposition.PropertyTypes.First(x => x.Alias.Equals("metakeywords")); + IPropertyType keywordsPropertyType = metaComposition.PropertyTypes.First(x => x.Alias.Equals("metakeywords")); keywordsPropertyType.Alias = "title"; // Assert @@ -971,51 +981,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services */ // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var moreAdvancedPage = ContentTypeBuilder.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); + ContentType moreAdvancedPage = ContentTypeBuilder.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); ContentTypeService.Save(moreAdvancedPage); - var seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); + ContentType seoComposition = ContentTypeBuilder.CreateMetaContentType("seo", "SEO"); ContentTypeService.Save(seoComposition); - var metaComposition = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaComposition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); + bool subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); ContentTypeService.Save(advancedPage); var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); + bool titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); ContentTypeService.Save(seoComposition); - var seoCompositionAdded = advancedPage.AddContentType(seoComposition); - var metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); + bool seoCompositionAdded = advancedPage.AddContentType(seoComposition); + bool metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); ContentTypeService.Save(advancedPage); ContentTypeService.Save(moreAdvancedPage); @@ -1029,9 +1039,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var testPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "test") { - Name = "Test", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Test", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var testAdded = seoComposition.AddPropertyType(testPropertyType, "Content"); + bool testAdded = seoComposition.AddPropertyType(testPropertyType, "Content"); ContentTypeService.Save(seoComposition); Assert.That(testAdded, Is.True); @@ -1045,37 +1055,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Rename_PropertyGroup_On_Child_Avoiding_Conflict_With_Parent_PropertyGroup() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(page); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, propertyGroupName: "Details", defaultTemplateId: template.Id); + ContentType advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, propertyGroupName: "Details", defaultTemplateId: template.Id); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); - //Change the name of the tab on the "root" content type 'page'. - var propertyGroup = contentPage.PropertyGroups["Content_"]; + // Change the name of the tab on the "root" content type 'page'. + PropertyGroup propertyGroup = contentPage.PropertyGroups["Content_"]; Assert.Throws(() => contentPage.PropertyGroups.Add(new PropertyGroup(true) { Id = propertyGroup.Id, @@ -1096,40 +1106,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Rename_PropertyType_Alias_Causing_Conflicts_With_Parents() { // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); // Act var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); + bool titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content"); var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); + bool subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(basePage); ContentTypeService.Save(contentPage); ContentTypeService.Save(advancedPage); - //Rename the PropertyType to something that already exists in the Composition - NOTE this should not be allowed and Saving should throw an exception - var authorPropertyTypeToRename = advancedPage.PropertyTypes.First(x => x.Alias.Equals("author")); + // Rename the PropertyType to something that already exists in the Composition - NOTE this should not be allowed and Saving should throw an exception + IPropertyType authorPropertyTypeToRename = advancedPage.PropertyTypes.First(x => x.Alias.Equals("author")); authorPropertyTypeToRename.Alias = "title"; // Assert @@ -1155,33 +1165,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services * ---- Advanced Page */ // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var basePage = ContentTypeBuilder.CreateSimpleContentType("basePage", "Base Page", randomizeAliases: true, defaultTemplateId: template.Id); + ContentType basePage = ContentTypeBuilder.CreateSimpleContentType("basePage", "Base Page", randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", basePage, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", basePage, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, defaultTemplateId: template.Id); ContentTypeService.Save(advancedPage); - var metaComposition = ContentTypeBuilder.CreateMetaContentType(); + ContentType metaComposition = ContentTypeBuilder.CreateMetaContentType(); ContentTypeService.Save(metaComposition); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); - var metaAdded = contentPage.AddContentType(metaComposition); + bool metaAdded = contentPage.AddContentType(metaComposition); ContentTypeService.Save(contentPage); - var metaAddedToComposition = contentMetaComposition.AddContentType(metaComposition); + bool metaAddedToComposition = contentMetaComposition.AddContentType(metaComposition); ContentTypeService.Save(contentMetaComposition); // Act var propertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { - Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Title", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var addedToContentPage = contentPage.AddPropertyType(propertyType, "Content"); + bool addedToContentPage = contentPage.AddPropertyType(propertyType, "Content"); // Assert Assert.That(metaAdded, Is.True); @@ -1194,13 +1204,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Rename_PropertyGroup_With_Inherited_PropertyGroups() { - //Related the first issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 + // Related the first issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 // Arrange // create 'page' content type with a 'Content_' group - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", propertyGroupName: "Content_", defaultTemplateId: template.Id); + ContentType page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", propertyGroupName: "Content_", defaultTemplateId: template.Id); Assert.AreEqual(1, page.PropertyGroups.Count); Assert.AreEqual("Content_", page.PropertyGroups.First().Name); Assert.AreEqual(3, page.PropertyTypes.Count()); @@ -1210,7 +1220,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(page); // create 'contentPage' content type as a child of 'page' - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, defaultTemplateId: template.Id); Assert.AreEqual(1, page.PropertyGroups.Count); Assert.AreEqual("Content_", page.PropertyGroups.First().Name); Assert.AreEqual(3, contentPage.PropertyTypes.Count()); @@ -1220,7 +1230,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(contentPage); // add 'Content' group to 'meta' content type - var meta = ContentTypeBuilder.CreateMetaContentType(); + ContentType meta = ContentTypeBuilder.CreateMetaContentType(); Assert.AreEqual(1, meta.PropertyGroups.Count); Assert.AreEqual("Meta", meta.PropertyGroups.First().Name); Assert.AreEqual(2, meta.PropertyTypes.Count()); @@ -1237,41 +1247,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // add property 'prop1' to 'contentPage' group 'Content_' var prop1 = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "testTextbox") { - Name = "Test Textbox", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Test Textbox", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var prop1Added = contentPage.AddPropertyType(prop1, "Content_"); + bool prop1Added = contentPage.AddPropertyType(prop1, "Content_"); Assert.IsTrue(prop1Added); // add property 'prop2' to 'contentPage' group 'Content' var prop2 = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "anotherTextbox") { - Name = "Another Test Textbox", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Another Test Textbox", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var prop2Added = contentPage.AddPropertyType(prop2, "Content"); + bool prop2Added = contentPage.AddPropertyType(prop2, "Content"); Assert.IsTrue(prop2Added); // save 'contentPage' content type ContentTypeService.Save(contentPage); - var group = page.PropertyGroups["Content_"]; + PropertyGroup group = page.PropertyGroups["Content_"]; group.Name = "ContentTab"; // rename the group ContentTypeService.Save(page); Assert.AreEqual(3, page.PropertyTypes.Count()); // get 'contentPage' content type again - var contentPageAgain = ContentTypeService.Get("contentPage"); + IContentType contentPageAgain = ContentTypeService.Get("contentPage"); Assert.IsNotNull(contentPageAgain); // assert that 'Content_' group is still there because we don't propagate renames - var findGroup = contentPageAgain.CompositionPropertyGroups.FirstOrDefault(x => x.Name == "Content_"); + PropertyGroup findGroup = contentPageAgain.CompositionPropertyGroups.FirstOrDefault(x => x.Name == "Content_"); Assert.IsNotNull(findGroup); // count all property types (local and composed) - var propertyTypeCount = contentPageAgain.PropertyTypes.Count(); + int propertyTypeCount = contentPageAgain.PropertyTypes.Count(); Assert.That(propertyTypeCount, Is.EqualTo(5)); // count composed property types - var compPropertyTypeCount = contentPageAgain.CompositionPropertyTypes.Count(); + int compPropertyTypeCount = contentPageAgain.CompositionPropertyTypes.Count(); Assert.That(compPropertyTypeCount, Is.EqualTo(10)); } @@ -1279,52 +1289,52 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Rename_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); + ContentType page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); ContentTypeService.Save(page); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Contentx", defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Contentx", defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, propertyGroupName: "Contenty", defaultTemplateId: template.Id); + ContentType advancedPage = ContentTypeBuilder.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, randomizeAliases: true, propertyGroupName: "Contenty", defaultTemplateId: template.Id); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content_");//Will be added to the parent tab - var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content");//Will be added to the "Content Meta" composition + bool bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content_"); // Will be added to the parent tab + bool subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); // Will be added to the "Content Meta" composition ContentTypeService.Save(contentPage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var descriptionPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "description") { - Name = "Description", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Description", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var keywordsPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "keywords") { - Name = "Keywords", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Keywords", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content_");//Will be added to an ancestor tab - var descriptionAdded = advancedPage.AddPropertyType(descriptionPropertyType, "Contentx");//Will be added to a parent tab - var keywordsAdded = advancedPage.AddPropertyType(keywordsPropertyType, "Content");//Will be added to the "Content Meta" composition + bool authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content_"); // Will be added to an ancestor tab + bool descriptionAdded = advancedPage.AddPropertyType(descriptionPropertyType, "Contentx"); // Will be added to a parent tab + bool keywordsAdded = advancedPage.AddPropertyType(keywordsPropertyType, "Content"); // Will be added to the "Content Meta" composition ContentTypeService.Save(advancedPage); - //Change the name of the tab on the "root" content type 'page'. - var propertyGroup = page.PropertyGroups["Content_"]; + // Change the name of the tab on the "root" content type 'page'. + PropertyGroup propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup(true) { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 }); ContentTypeService.Save(page); @@ -1339,13 +1349,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.DoesNotThrow(() => ContentTypeService.Get("contentPage")); Assert.DoesNotThrow(() => ContentTypeService.Get("advancedPage")); - var advancedPageReloaded = ContentTypeService.Get("advancedPage"); - var contentUnderscoreTabExists = advancedPageReloaded.CompositionPropertyGroups.Any(x => x.Name.Equals("Content_")); + IContentType advancedPageReloaded = ContentTypeService.Get("advancedPage"); + bool contentUnderscoreTabExists = advancedPageReloaded.CompositionPropertyGroups.Any(x => x.Name.Equals("Content_")); // now is true, because we don't propagate renames anymore Assert.That(contentUnderscoreTabExists, Is.True); - var numberOfContentTabs = advancedPageReloaded.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); + int numberOfContentTabs = advancedPageReloaded.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); Assert.That(numberOfContentTabs, Is.EqualTo(4)); } @@ -1353,40 +1363,40 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Rename_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups_v2() { // Arrange - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); + ContentType page = ContentTypeBuilder.CreateSimpleContentType("page", "Page", randomizeAliases: true, propertyGroupName: "Content_", defaultTemplateId: template.Id); ContentTypeService.Save(page); - var contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Content", defaultTemplateId: template.Id); + ContentType contentPage = ContentTypeBuilder.CreateSimpleContentType("contentPage", "Content Page", page, randomizeAliases: true, propertyGroupName: "Content", defaultTemplateId: template.Id); ContentTypeService.Save(contentPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var subtitlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "subtitle") { - Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Subtitle", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = page.AddPropertyType(bodyTextPropertyType, "Content_"); - var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content_"); + bool bodyTextAdded = page.AddPropertyType(bodyTextPropertyType, "Content_"); + bool subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content_"); ContentTypeService.Save(page); ContentTypeService.Save(contentPage); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); - //Change the name of the tab on the "root" content type 'page'. - var propertyGroup = page.PropertyGroups["Content_"]; + // Change the name of the tab on the "root" content type 'page'. + PropertyGroup propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup(true) { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 }); ContentTypeService.Save(page); @@ -1403,34 +1413,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Remove_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups() { // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); basePage.RemovePropertyGroup("Content"); @@ -1444,14 +1454,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.DoesNotThrow(() => ContentTypeService.Get("contentPage")); Assert.DoesNotThrow(() => ContentTypeService.Get("advancedPage")); - var contentType = ContentTypeService.Get("contentPage"); - var propertyGroup = contentType.PropertyGroups["Content"]; + IContentType contentType = ContentTypeService.Get("contentPage"); + PropertyGroup propertyGroup = contentType.PropertyGroups["Content"]; } [Test] public void Can_Remove_PropertyGroup_Without_Removing_Property_Types() { - var basePage = (IContentType) ContentTypeBuilder.CreateBasicContentType(); + var basePage = (IContentType)ContentTypeBuilder.CreateBasicContentType(); basePage.AddPropertyGroup("Content"); basePage.AddPropertyGroup("Meta"); ContentTypeService.Save(basePage); @@ -1459,7 +1469,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { Name = "Author", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 @@ -1469,7 +1479,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var titlePropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "title") { Name = "Title", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 @@ -1479,7 +1489,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(basePage); basePage = ContentTypeService.Get(basePage.Id); - var count = basePage.PropertyTypes.Count(); + int count = basePage.PropertyTypes.Count(); Assert.AreEqual(2, count); basePage.RemovePropertyGroup("Content"); @@ -1501,34 +1511,34 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services */ // Arrange - var basePage = ContentTypeBuilder.CreateBasicContentType(); + ContentType basePage = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(basePage); - var contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); + ContentType contentPage = ContentTypeBuilder.CreateBasicContentType("contentPage", "Content Page", basePage); ContentTypeService.Save(contentPage); - var advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); + ContentType advancedPage = ContentTypeBuilder.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); ContentTypeService.Save(advancedPage); - var contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); + ContentType contentMetaComposition = ContentTypeBuilder.CreateContentMetaContentType(); ContentTypeService.Save(contentMetaComposition); // Act var authorPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "author") { - Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Author", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); + bool authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); ContentTypeService.Save(contentPage); var bodyTextPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext, "bodyText") { - Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 + Name = "Body Text", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); + bool bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); ContentTypeService.Save(basePage); - var compositionAdded = contentPage.AddContentType(contentMetaComposition); + bool compositionAdded = contentPage.AddContentType(contentMetaComposition); ContentTypeService.Save(contentPage); // Assert @@ -1539,39 +1549,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.DoesNotThrow(() => ContentTypeService.Get("contentPage")); Assert.DoesNotThrow(() => ContentTypeService.Get("advancedPage")); - var contentType = ContentTypeService.Get("contentPage"); - var propertyGroup = contentType.PropertyGroups["Content"]; + IContentType contentType = ContentTypeService.Get("contentPage"); + PropertyGroup propertyGroup = contentType.PropertyGroups["Content"]; - var numberOfContentTabs = contentType.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); + int numberOfContentTabs = contentType.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); Assert.That(numberOfContentTabs, Is.EqualTo(3)); - //Ensure that adding a new PropertyType to the "Content"-tab also adds it to the right group - + // Ensure that adding a new PropertyType to the "Content"-tab also adds it to the right group var descriptionPropertyType = new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { - Alias = "description", Name = "Description", Description = "", Mandatory = false, SortOrder = 1,DataTypeId = -88 + Alias = "description", Name = "Description", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 }; - var descriptionAdded = contentType.AddPropertyType(descriptionPropertyType, "Content"); + bool descriptionAdded = contentType.AddPropertyType(descriptionPropertyType, "Content"); ContentTypeService.Save(contentType); Assert.That(descriptionAdded, Is.True); - var contentPageReloaded = ContentTypeService.Get("contentPage"); - var propertyGroupReloaded = contentPageReloaded.PropertyGroups["Content"]; - var hasDescriptionPropertyType = propertyGroupReloaded.PropertyTypes.Contains("description"); + IContentType contentPageReloaded = ContentTypeService.Get("contentPage"); + PropertyGroup propertyGroupReloaded = contentPageReloaded.PropertyGroups["Content"]; + bool hasDescriptionPropertyType = propertyGroupReloaded.PropertyTypes.Contains("description"); Assert.That(hasDescriptionPropertyType, Is.True); - var descriptionPropertyTypeReloaded = propertyGroupReloaded.PropertyTypes["description"]; + IPropertyType descriptionPropertyTypeReloaded = propertyGroupReloaded.PropertyTypes["description"]; Assert.That(descriptionPropertyTypeReloaded.PropertyGroupId.IsValueCreated, Is.False); } [Test] public void Empty_Description_Is_Always_Null_After_Saving_Content_Type() { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Description = null; ContentTypeService.Save(contentType); - var contentType2 = ContentTypeBuilder.CreateBasicContentType("basePage2", "Base Page 2"); + ContentType contentType2 = ContentTypeBuilder.CreateBasicContentType("basePage2", "Base Page 2"); contentType2.Description = string.Empty; ContentTypeService.Save(contentType2); @@ -1582,23 +1591,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Variations_In_Compositions() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var typeA = ContentTypeBuilder.CreateSimpleContentType("a", "A", defaultTemplateId: template.Id); + ContentType typeA = ContentTypeBuilder.CreateSimpleContentType("a", "A", defaultTemplateId: template.Id); typeA.Variations = ContentVariation.Culture; // make it variant typeA.PropertyTypes.First(x => x.Alias.InvariantEquals("title")).Variations = ContentVariation.Culture; // with a variant property ContentTypeService.Save(typeA); - var typeB = ContentTypeBuilder.CreateSimpleContentType("b", "B", typeA, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType typeB = ContentTypeBuilder.CreateSimpleContentType("b", "B", typeA, randomizeAliases: true, defaultTemplateId: template.Id); typeB.Variations = ContentVariation.Nothing; // make it invariant ContentTypeService.Save(typeB); - var typeC = ContentTypeBuilder.CreateSimpleContentType("c", "C", typeA, randomizeAliases: true, defaultTemplateId: template.Id); + ContentType typeC = ContentTypeBuilder.CreateSimpleContentType("c", "C", typeA, randomizeAliases: true, defaultTemplateId: template.Id); typeC.Variations = ContentVariation.Culture; // make it variant ContentTypeService.Save(typeC); // property is variant on A - var test = ContentTypeService.Get(typeA.Id); + IContentType test = ContentTypeService.Get(typeA.Id); Assert.AreEqual(ContentVariation.Culture, test.CompositionPropertyTypes.First(x => x.Alias.InvariantEquals("title")).Variations); Assert.AreEqual(ContentVariation.Culture, test.CompositionPropertyGroups.First().PropertyTypes.First(x => x.Alias.InvariantEquals("title")).Variations); @@ -1627,8 +1636,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Trashed = false }; - var contentCollection = new PropertyTypeCollection(true); - contentCollection.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "componentGroup") { Name = "Component Group", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + var contentCollection = new PropertyTypeCollection(true) + { + new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "componentGroup") { Name = "Component Group", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 } + }; component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); return component; @@ -1652,7 +1663,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var propertyType = new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "bannerName") { Name = "Banner Name", - Description = "", + Description = string.Empty, Mandatory = false, SortOrder = 2, DataTypeId = -88 @@ -1675,8 +1686,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Trashed = false }; - var contentCollection = new PropertyTypeCollection(true); - contentCollection.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "hostname") { Name = "Hostname", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); + var contentCollection = new PropertyTypeCollection(true) + { + new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "hostname") { Name = "Hostname", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = -88 } + }; site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); return site; @@ -1684,28 +1697,31 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private ContentType CreateHomepage(ContentType parent) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); return ContentTypeBuilder.CreateSimpleContentType("homepage", "Homepage", parent, defaultTemplateId: template.Id); } private IContentType[] CreateContentTypeHierarchy() { - //create the master type - var template = TemplateBuilder.CreateTextPageTemplate(); + // create the master type + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var masterContentType = ContentTypeBuilder.CreateSimpleContentType("masterContentType", "MasterContentType", defaultTemplateId: template.Id); + ContentType masterContentType = ContentTypeBuilder.CreateSimpleContentType("masterContentType", "MasterContentType", defaultTemplateId: template.Id); masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); ContentTypeService.Save(masterContentType); - //add the one we just created + // add the one we just created var list = new List { masterContentType }; - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var contentType = ContentTypeBuilder.CreateSimpleContentType("childType" + i, "ChildType" + i, - //make the last entry in the list, this one's parent - list.Last(), randomizeAliases: true, defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType( + "childType" + i, + "ChildType" + i, + list.Last(), // make the last entry in the list, this one's parent + randomizeAliases: true, + defaultTemplateId: template.Id); list.Add(contentType); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs index 010f680ad1..15b4affa3a 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentTypeServiceVariantsTests.cs @@ -1,24 +1,24 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; -using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using NPoco; using NUnit.Framework; -using Umbraco.Core.Cache; using Umbraco.Core.Configuration.Models; using Umbraco.Core.DependencyInjection; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; -using Umbraco.Core.Sync; using Umbraco.Infrastructure.PublishedCache.DependencyInjection; -using Umbraco.Net; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; -using Umbraco.Web.PublishedCache; using Umbraco.Web.PublishedCache.NuCache; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services @@ -51,20 +51,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void AssertJsonStartsWith(int id, string expected) { - var json = GetJson(id).Replace('"', '\''); - var pos = json.IndexOf("'cd':", StringComparison.InvariantCultureIgnoreCase); + string json = GetJson(id).Replace('"', '\''); + int pos = json.IndexOf("'cd':", StringComparison.InvariantCultureIgnoreCase); json = json.Substring(0, pos + "'cd':".Length); Assert.AreEqual(expected, json); } private string GetJson(int id) { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) + using (IScope scope = ScopeProvider.CreateScope(autoComplete: true)) { - var selectJson = SqlContext.Sql().Select().From().Where(x => x.NodeId == id && !x.Published); - var dto = scope.Database.Fetch(selectJson).FirstOrDefault(); + Sql selectJson = SqlContext.Sql().Select().From().Where(x => x.NodeId == id && !x.Published); + ContentNuDto dto = scope.Database.Fetch(selectJson).FirstOrDefault(); Assert.IsNotNull(dto); - var json = dto.Data; + string json = dto.Data; return json; } } @@ -87,16 +87,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.CultureAndSegment, false)] public void Change_Content_Type_Variation_Clears_Redirects(ContentVariation startingContentTypeVariation, ContentVariation changedContentTypeVariation, bool shouldUrlRedirectsBeCleared) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = startingContentTypeVariation; ContentTypeService.Save(contentType); - var contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); + ContentType contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); ContentTypeService.Save(contentType2); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.Name = "Hello1"; - if(startingContentTypeVariation.HasFlag(ContentVariation.Culture)) + if (startingContentTypeVariation.HasFlag(ContentVariation.Culture)) { doc.SetCultureName(doc.Name, "en-US"); } @@ -113,10 +113,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(1, RedirectUrlService.GetContentRedirectUrls(doc.Key).Count()); Assert.AreEqual(1, RedirectUrlService.GetContentRedirectUrls(doc2.Key).Count()); - //change variation + // change variation contentType.Variations = changedContentTypeVariation; ContentTypeService.Save(contentType); - var expectedRedirectUrlCount = shouldUrlRedirectsBeCleared ? 0 : 1; + int expectedRedirectUrlCount = shouldUrlRedirectsBeCleared ? 0 : 1; Assert.AreEqual(expectedRedirectUrlCount, RedirectUrlService.GetContentRedirectUrls(doc.Key).Count()); Assert.AreEqual(1, RedirectUrlService.GetContentRedirectUrls(doc2.Key).Count()); } @@ -127,43 +127,43 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.Segment, ContentVariation.CultureAndSegment)] public void Change_Content_Type_From_No_Culture_To_Culture(ContentVariation from, ContentVariation to) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = from; - var properties = CreatePropertyCollection(("title", from)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", from)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.Name = "Hello1"; doc.SetValue("title", "hello world"); ContentService.Save(doc); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello1", doc.Name); Assert.AreEqual("hello world", doc.GetValue("title")); Assert.IsTrue(doc.Edited); Assert.IsFalse(doc.IsCultureEdited("en-US")); - //change the content type to be variant, we will also update the name here to detect the copy changes + // change the content type to be variant, we will also update the name here to detect the copy changes doc.Name = "Hello2"; ContentService.Save(doc); contentType.Variations = to; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello2", doc.GetCultureName("en-US")); - Assert.AreEqual("hello world", doc.GetValue("title")); //We are not checking against en-US here because properties will remain invariant + Assert.AreEqual("hello world", doc.GetValue("title")); // We are not checking against en-US here because properties will remain invariant Assert.IsTrue(doc.Edited); Assert.IsTrue(doc.IsCultureEdited("en-US")); - //change back property type to be invariant, we will also update the name here to detect the copy changes + // change back property type to be invariant, we will also update the name here to detect the copy changes doc.SetCultureName("Hello3", "en-US"); ContentService.Save(doc); contentType.Variations = from; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello3", doc.Name); Assert.AreEqual("hello world", doc.GetValue("title")); @@ -177,55 +177,55 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.Segment)] public void Change_Content_Type_From_Culture_To_No_Culture(ContentVariation startingContentTypeVariation, ContentVariation changeContentTypeVariationTo) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = startingContentTypeVariation; - var properties = CreatePropertyCollection(("title", startingContentTypeVariation)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", startingContentTypeVariation)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Hello1", "en-US"); doc.SetValue("title", "hello world", "en-US"); ContentService.Save(doc); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello1", doc.GetCultureName("en-US")); Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); Assert.IsTrue(doc.Edited); Assert.IsTrue(doc.IsCultureEdited("en-US")); - //change the content type to be invariant, we will also update the name here to detect the copy changes + // change the content type to be invariant, we will also update the name here to detect the copy changes doc.SetCultureName("Hello2", "en-US"); ContentService.Save(doc); contentType.Variations = changeContentTypeVariationTo; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello2", doc.Name); Assert.AreEqual("hello world", doc.GetValue("title")); Assert.IsTrue(doc.Edited); Assert.IsFalse(doc.IsCultureEdited("en-US")); - //change back property type to be variant, we will also update the name here to detect the copy changes + // change back property type to be variant, we will also update the name here to detect the copy changes doc.Name = "Hello3"; ContentService.Save(doc); contentType.Variations = startingContentTypeVariation; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get - //at this stage all property types were switched to invariant so even though the variant value - //exists it will not be returned because the property type is invariant, - //so this check proves that null will be returned + // at this stage all property types were switched to invariant so even though the variant value + // exists it will not be returned because the property type is invariant, + // so this check proves that null will be returned Assert.AreEqual("Hello3", doc.Name); Assert.IsNull(doc.GetValue("title", "en-US")); Assert.IsTrue(doc.Edited); Assert.IsTrue(doc.IsCultureEdited("en-US")); // this is true because the name change is copied to the default language - //we can now switch the property type to be variant and the value can be returned again + // we can now switch the property type to be variant and the value can be returned again contentType.PropertyTypes.First().Variations = startingContentTypeVariation; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("Hello3", doc.GetCultureName("en-US")); Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); @@ -251,23 +251,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.CultureAndSegment)] public void Preserve_Content_Name_After_Content_Type_Variation_Change(ContentVariation contentTypeVariationFrom, ContentVariation contentTypeVariationTo) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = contentTypeVariationFrom; ContentTypeService.Save(contentType); - var invariantContentName = "Content Invariant"; + string invariantContentName = "Content Invariant"; - var defaultCultureContentName = "Content en-US"; - var defaultCulture = "en-US"; + string defaultCultureContentName = "Content en-US"; + string defaultCulture = "en-US"; - var nlContentName = "Content nl-NL"; - var nlCulture = "nl-NL"; + string nlContentName = "Content nl-NL"; + string nlCulture = "nl-NL"; var globalSettings = new GlobalSettings(); LocalizationService.Save(new Language(globalSettings, nlCulture)); - var includeCultureNames = contentType.Variations.HasFlag(ContentVariation.Culture); + bool includeCultureNames = contentType.Variations.HasFlag(ContentVariation.Culture); // Create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); @@ -277,7 +277,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { Assert.DoesNotThrow(() => doc.SetCultureName(defaultCultureContentName, defaultCulture)); Assert.DoesNotThrow(() => doc.SetCultureName(nlContentName, nlCulture)); - } else + } + else { Assert.Throws(() => doc.SetCultureName(defaultCultureContentName, defaultCulture)); Assert.Throws(() => doc.SetCultureName(nlContentName, nlCulture)); @@ -331,14 +332,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.CultureAndSegment)] public void Verify_If_Property_Type_Variation_Is_Correctly_Corrected_When_Content_Type_Is_Updated(ContentVariation contentTypeVariation, ContentVariation propertyTypeVariation) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); // We test an updated content type so it has to be saved first. ContentTypeService.Save(contentType); // Update it contentType.Variations = contentTypeVariation; - var properties = CreatePropertyCollection(("title", propertyTypeVariation)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", propertyTypeVariation)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); @@ -352,40 +353,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.Segment, ContentVariation.CultureAndSegment)] public void Change_Property_Type_From_Invariant_Variant(ContentVariation invariant, ContentVariation variant) { - var contentType = ContentTypeBuilder.CreateBasicContentType(); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); + // content type supports all variations contentType.Variations = ContentVariation.Culture | ContentVariation.Segment; - var properties = CreatePropertyCollection(("title", invariant)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", invariant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Home", "en-US"); doc.SetValue("title", "hello world"); ContentService.Save(doc); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); - Assert.IsTrue(doc.IsCultureEdited("en-US")); //invariant prop changes show up on default lang + Assert.IsTrue(doc.IsCultureEdited("en-US")); // invariant prop changes show up on default lang Assert.IsTrue(doc.Edited); - //change the property type to be variant + // change the property type to be variant contentType.PropertyTypes.First().Variations = variant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); Assert.IsTrue(doc.IsCultureEdited("en-US")); Assert.IsTrue(doc.Edited); - //change back property type to be invariant + // change back property type to be invariant contentType.PropertyTypes.First().Variations = invariant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); - Assert.IsTrue(doc.IsCultureEdited("en-US")); //invariant prop changes show up on default lang + Assert.IsTrue(doc.IsCultureEdited("en-US")); // invariant prop changes show up on default lang Assert.IsTrue(doc.Edited); } @@ -395,15 +397,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.Segment)] public void Change_Property_Type_From_Variant_Invariant(ContentVariation variant, ContentVariation invariant) { - //create content type with a property type that varies by culture - var contentType = ContentTypeBuilder.CreateBasicContentType(); + // create content type with a property type that varies by culture + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); + // content type supports all variations contentType.Variations = ContentVariation.Culture | ContentVariation.Segment; - var properties = CreatePropertyCollection(("title", variant)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", variant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Home", "en-US"); doc.SetValue("title", "hello world", "en-US"); @@ -411,17 +414,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); - //change the property type to be invariant + // change the property type to be invariant contentType.PropertyTypes.First().Variations = invariant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); - //change back property type to be variant + // change back property type to be variant contentType.PropertyTypes.First().Variations = variant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); } @@ -432,21 +435,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.Segment)] public void Change_Property_Type_From_Variant_Invariant_On_A_Composition(ContentVariation variant, ContentVariation invariant) { - //create content type with a property type that varies by culture - var contentType = ContentTypeBuilder.CreateBasicContentType(); + // create content type with a property type that varies by culture + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); + // content type supports all variations contentType.Variations = ContentVariation.Culture | ContentVariation.Segment; - var properties = CreatePropertyCollection(("title", variant)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", variant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //compose this from the other one - var contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); + // compose this from the other one + ContentType contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); contentType2.Variations = contentType.Variations; contentType2.AddContentType(contentType); ContentTypeService.Save(contentType2); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Home", "en-US"); doc.SetValue("title", "hello world", "en-US"); @@ -457,20 +461,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services doc2.SetValue("title", "hello world", "en-US"); ContentService.Save(doc2); - //change the property type to be invariant + // change the property type to be invariant contentType.PropertyTypes.First().Variations = invariant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get - doc2 = ContentService.GetById(doc2.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get + doc2 = ContentService.GetById(doc2.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); Assert.AreEqual("hello world", doc2.GetValue("title")); - //change back property type to be variant + // change back property type to be variant contentType.PropertyTypes.First().Variations = variant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get - doc2 = ContentService.GetById(doc2.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get + doc2 = ContentService.GetById(doc2.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title", "en-US")); Assert.AreEqual("hello world", doc2.GetValue("title", "en-US")); @@ -482,20 +486,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [TestCase(ContentVariation.CultureAndSegment, ContentVariation.Segment)] public void Change_Content_Type_From_Variant_Invariant_On_A_Composition(ContentVariation variant, ContentVariation invariant) { - //create content type with a property type that varies by culture - var contentType = ContentTypeBuilder.CreateBasicContentType(); + // create content type with a property type that varies by culture + ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); contentType.Variations = variant; - var properties = CreatePropertyCollection(("title", ContentVariation.Culture)); + PropertyTypeCollection properties = CreatePropertyCollection(("title", ContentVariation.Culture)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - //compose this from the other one - var contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); + // compose this from the other one + ContentType contentType2 = ContentTypeBuilder.CreateBasicContentType("test"); contentType2.Variations = contentType.Variations; contentType2.AddContentType(contentType); ContentTypeService.Save(contentType2); - //create some content of this content type + // create some content of this content type IContent doc = ContentBuilder.CreateBasicContent(contentType); doc.SetCultureName("Home", "en-US"); doc.SetValue("title", "hello world", "en-US"); @@ -506,22 +510,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services doc2.SetValue("title", "hello world", "en-US"); ContentService.Save(doc2); - //change the content type to be invariant + // change the content type to be invariant contentType.Variations = invariant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get - doc2 = ContentService.GetById(doc2.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get + doc2 = ContentService.GetById(doc2.Id); // re-get Assert.AreEqual("hello world", doc.GetValue("title")); Assert.AreEqual("hello world", doc2.GetValue("title")); - //change back content type to be variant + // change back content type to be variant contentType.Variations = variant; ContentTypeService.Save(contentType); - doc = ContentService.GetById(doc.Id); //re-get - doc2 = ContentService.GetById(doc2.Id); //re-get + doc = ContentService.GetById(doc.Id); // re-get + doc2 = ContentService.GetById(doc2.Id); // re-get - //this will be null because the doc type was changed back to variant but it's property types don't get changed back + // this will be null because the doc type was changed back to variant but it's property types don't get changed back Assert.IsNull(doc.GetValue("title", "en-US")); Assert.IsNull(doc2.GetValue("title", "en-US")); } @@ -533,9 +537,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change it to invariant and back CreateFrenchAndEnglishLangs(); - var contentType = CreateContentType(ContentVariation.Culture); + IContentType contentType = CreateContentType(ContentVariation.Culture); - var properties = CreatePropertyCollection( + PropertyTypeCollection properties = CreatePropertyCollection( ("value1", ContentVariation.Culture), ("value2", ContentVariation.Nothing)); @@ -559,7 +563,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'en','v':'v1en'},{'c':'fr','v':'v1fr'}],'value2':[{'v':'v2'}]},'cd':"); // switch content type to Nothing @@ -576,7 +581,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); // switch content back to Culture @@ -593,7 +599,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); // switch property back to Culture @@ -609,7 +616,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'fr','v':'v1fr'},{'c':'en','v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); } @@ -626,16 +634,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var languageFr = new Language(globalSettings, "fr"); LocalizationService.Save(languageFr); - var contentType = CreateContentType(ContentVariation.Nothing); + IContentType contentType = CreateContentType(ContentVariation.Nothing); - var properties = CreatePropertyCollection( + PropertyTypeCollection properties = CreatePropertyCollection( ("value1", ContentVariation.Nothing), ("value2", ContentVariation.Nothing)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); - var document = (IContent) new Content("document", -1, contentType); + var document = (IContent)new Content("document", -1, contentType); document.Name = "doc1"; document.SetValue("value1", "v1"); document.SetValue("value2", "v2"); @@ -651,7 +659,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1'}],'value2':[{'v':'v2'}]},'cd':"); // switch content type to Culture @@ -667,7 +676,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1'}],'value2':[{'v':'v2'}]},'cd':"); // switch property to Culture @@ -682,7 +692,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'en','v':'v1'}],'value2':[{'v':'v2'}]},'cd':"); // switch content back to Nothing @@ -699,7 +710,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1'}],'value2':[{'v':'v2'}]},'cd':"); } @@ -710,9 +722,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change an invariant property to variant and back CreateFrenchAndEnglishLangs(); - var contentType = CreateContentType(ContentVariation.Culture); + IContentType contentType = CreateContentType(ContentVariation.Culture); - var properties = CreatePropertyCollection( + PropertyTypeCollection properties = CreatePropertyCollection( ("value1", ContentVariation.Culture), ("value2", ContentVariation.Nothing)); @@ -736,7 +748,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'en','v':'v1en'},{'c':'fr','v':'v1fr'}],'value2':[{'v':'v2'}]},'cd':"); // switch property type to Nothing @@ -753,7 +766,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); // switch property back to Culture @@ -769,7 +783,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v2", document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'fr','v':'v1fr'},{'c':'en','v':'v1en'}],'value2':[{'v':'v2'}]},'cd':"); // switch other property to Culture @@ -787,7 +802,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsNull(document.GetValue("value2")); Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value1':[{'c':'fr','v':'v1fr'},{'c':'en','v':'v1en'}],'value2':[{'c':'en','v':'v2'}]},'cd':"); } @@ -799,12 +815,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // one simple content type, variant, with both variant and invariant properties // can change an invariant property to variant and back - CreateFrenchAndEnglishLangs(); - var contentType = CreateContentType(ContentVariation.Culture | ContentVariation.Segment); + IContentType contentType = CreateContentType(ContentVariation.Culture | ContentVariation.Segment); - var properties = CreatePropertyCollection(("value1", variant)); + PropertyTypeCollection properties = CreatePropertyCollection(("value1", variant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); @@ -814,15 +829,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services document.SetCultureName("doc1fr", "fr"); document.SetValue("value1", "v1en-init", "en"); document.SetValue("value1", "v1fr-init", "fr"); - ContentService.SaveAndPublish(document); //all values are published which means the document is not 'edited' + ContentService.SaveAndPublish(document); // all values are published which means the document is not 'edited' document = ContentService.GetById(document.Id); Assert.IsFalse(document.IsCultureEdited("en")); Assert.IsFalse(document.IsCultureEdited("fr")); Assert.IsFalse(document.Edited); - document.SetValue("value1", "v1en", "en"); //change the property culture value, so now this culture will be edited - document.SetValue("value1", "v1fr", "fr"); //change the property culture value, so now this culture will be edited + document.SetValue("value1", "v1en", "en"); // change the property culture value, so now this culture will be edited + document.SetValue("value1", "v1fr", "fr"); // change the property culture value, so now this culture will be edited ContentService.Save(document); document = ContentService.GetById(document.Id); @@ -833,20 +848,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("v1en-init", document.GetValue("value1", "en", published: true)); Assert.AreEqual("v1fr", document.GetValue("value1", "fr")); Assert.AreEqual("v1fr-init", document.GetValue("value1", "fr", published: true)); - Assert.IsTrue(document.IsCultureEdited("en")); //This will be true because the edited value isn't the same as the published value - Assert.IsTrue(document.IsCultureEdited("fr")); //This will be true because the edited value isn't the same as the published value + Assert.IsTrue(document.IsCultureEdited("en")); // This will be true because the edited value isn't the same as the published value + Assert.IsTrue(document.IsCultureEdited("fr")); // This will be true because the edited value isn't the same as the published value Assert.IsTrue(document.Edited); // switch property type to Invariant contentType.PropertyTypes.First(x => x.Alias == "value1").Variations = invariant; - ContentTypeService.Save(contentType); //This is going to have to re-normalize the "Edited" flag + ContentTypeService.Save(contentType); // This is going to have to re-normalize the "Edited" flag document = ContentService.GetById(document.Id); - Assert.IsTrue(document.IsCultureEdited("en")); //This will remain true because there is now a pending change for the invariant property data which is flagged under the default lang - Assert.IsFalse(document.IsCultureEdited("fr")); //This will be false because nothing has changed for this culture and the property no longer reflects variant changes + Assert.IsTrue(document.IsCultureEdited("en")); // This will remain true because there is now a pending change for the invariant property data which is flagged under the default lang + Assert.IsFalse(document.IsCultureEdited("fr")); // This will be false because nothing has changed for this culture and the property no longer reflects variant changes Assert.IsTrue(document.Edited); - //update the invariant value and publish + // update the invariant value and publish document.SetValue("value1", "v1inv"); ContentService.SaveAndPublish(document); @@ -854,14 +869,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("doc1en", document.Name); Assert.AreEqual("doc1en", document.GetCultureName("en")); Assert.AreEqual("doc1fr", document.GetCultureName("fr")); - Assert.IsNull(document.GetValue("value1", "en")); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", "fr")); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", "en", published: true)); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", "fr", published: true)); //The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "en")); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "fr")); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "en", published: true)); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "fr", published: true)); // The values are there but the business logic returns null Assert.AreEqual("v1inv", document.GetValue("value1")); Assert.AreEqual("v1inv", document.GetValue("value1", published: true)); - Assert.IsFalse(document.IsCultureEdited("en")); //This returns false, everything is published - Assert.IsFalse(document.IsCultureEdited("fr")); //This will be false because nothing has changed for this culture and the property no longer reflects variant changes + Assert.IsFalse(document.IsCultureEdited("en")); // This returns false, everything is published + Assert.IsFalse(document.IsCultureEdited("fr")); // This will be false because nothing has changed for this culture and the property no longer reflects variant changes Assert.IsFalse(document.Edited); // switch property back to Culture @@ -869,17 +884,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(contentType); document = ContentService.GetById(document.Id); - Assert.AreEqual("v1inv", document.GetValue("value1", "en")); //The invariant property value gets copied over to the default language + Assert.AreEqual("v1inv", document.GetValue("value1", "en")); // The invariant property value gets copied over to the default language Assert.AreEqual("v1inv", document.GetValue("value1", "en", published: true)); - Assert.AreEqual("v1fr", document.GetValue("value1", "fr")); //values are still retained - Assert.AreEqual("v1fr-init", document.GetValue("value1", "fr", published: true)); //values are still retained - Assert.IsFalse(document.IsCultureEdited("en")); //The invariant published AND edited values are copied over to the default language - Assert.IsTrue(document.IsCultureEdited("fr")); //The previously existing french values are there and there is no published value - Assert.IsTrue(document.Edited); //Will be flagged edited again because the french culture had pending changes + Assert.AreEqual("v1fr", document.GetValue("value1", "fr")); // values are still retained + Assert.AreEqual("v1fr-init", document.GetValue("value1", "fr", published: true)); // values are still retained + Assert.IsFalse(document.IsCultureEdited("en")); // The invariant published AND edited values are copied over to the default language + Assert.IsTrue(document.IsCultureEdited("fr")); // The previously existing french values are there and there is no published value + Assert.IsTrue(document.Edited); // Will be flagged edited again because the french culture had pending changes // publish again - document.SetValue("value1", "v1en2", "en"); //update the value now that it's variant again - document.SetValue("value1", "v1fr2", "fr"); //update the value now that it's variant again + document.SetValue("value1", "v1en2", "en"); // update the value now that it's variant again + document.SetValue("value1", "v1fr2", "fr"); // update the value now that it's variant again ContentService.SaveAndPublish(document); document = ContentService.GetById(document.Id); @@ -888,9 +903,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("doc1fr", document.GetCultureName("fr")); Assert.AreEqual("v1en2", document.GetValue("value1", "en")); Assert.AreEqual("v1fr2", document.GetValue("value1", "fr")); - Assert.IsNull(document.GetValue("value1")); //The value is there but the business logic returns null - Assert.IsFalse(document.IsCultureEdited("en")); //This returns false, the variant property value has been published - Assert.IsFalse(document.IsCultureEdited("fr")); //This returns false, the variant property value has been published + Assert.IsNull(document.GetValue("value1")); // The value is there but the business logic returns null + Assert.IsFalse(document.IsCultureEdited("en")); // This returns false, the variant property value has been published + Assert.IsFalse(document.IsCultureEdited("fr")); // This returns false, the variant property value has been published Assert.IsFalse(document.Edited); } @@ -904,9 +919,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change an invariant property to variant and back CreateFrenchAndEnglishLangs(); - var contentType = CreateContentType(ContentVariation.Culture | ContentVariation.Segment); + IContentType contentType = CreateContentType(ContentVariation.Culture | ContentVariation.Segment); - var properties = CreatePropertyCollection(("value1", invariant)); + PropertyTypeCollection properties = CreatePropertyCollection(("value1", invariant)); contentType.PropertyGroups.Add(new PropertyGroup(properties) { Name = "Content" }); ContentTypeService.Save(contentType); @@ -915,14 +930,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services document.SetCultureName("doc1en", "en"); document.SetCultureName("doc1fr", "fr"); document.SetValue("value1", "v1en-init"); - ContentService.SaveAndPublish(document); //all values are published which means the document is not 'edited' + ContentService.SaveAndPublish(document); // all values are published which means the document is not 'edited' document = ContentService.GetById(document.Id); Assert.IsFalse(document.IsCultureEdited("en")); Assert.IsFalse(document.IsCultureEdited("fr")); Assert.IsFalse(document.Edited); - document.SetValue("value1", "v1en"); //change the property value, so now the invariant (default) culture will be edited + document.SetValue("value1", "v1en"); // change the property value, so now the invariant (default) culture will be edited ContentService.Save(document); document = ContentService.GetById(document.Id); @@ -931,20 +946,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("doc1fr", document.GetCultureName("fr")); Assert.AreEqual("v1en", document.GetValue("value1")); Assert.AreEqual("v1en-init", document.GetValue("value1", published: true)); - Assert.IsTrue(document.IsCultureEdited("en")); //This is true because the invariant property reflects changes on the default lang + Assert.IsTrue(document.IsCultureEdited("en")); // This is true because the invariant property reflects changes on the default lang Assert.IsFalse(document.IsCultureEdited("fr")); Assert.IsTrue(document.Edited); // switch property type to Culture contentType.PropertyTypes.First(x => x.Alias == "value1").Variations = variant; - ContentTypeService.Save(contentType); //This is going to have to re-normalize the "Edited" flag + ContentTypeService.Save(contentType); // This is going to have to re-normalize the "Edited" flag document = ContentService.GetById(document.Id); - Assert.IsTrue(document.IsCultureEdited("en")); //Remains true - Assert.IsFalse(document.IsCultureEdited("fr")); //False because no french property has ever been edited + Assert.IsTrue(document.IsCultureEdited("en")); // Remains true + Assert.IsFalse(document.IsCultureEdited("fr")); // False because no french property has ever been edited Assert.IsTrue(document.Edited); - //update the culture value and publish + // update the culture value and publish document.SetValue("value1", "v1en2", "en"); ContentService.SaveAndPublish(document); @@ -952,12 +967,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("doc1en", document.Name); Assert.AreEqual("doc1en", document.GetCultureName("en")); Assert.AreEqual("doc1fr", document.GetCultureName("fr")); - Assert.IsNull(document.GetValue("value1")); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", published: true)); //The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1")); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", published: true)); // The values are there but the business logic returns null Assert.AreEqual("v1en2", document.GetValue("value1", "en")); Assert.AreEqual("v1en2", document.GetValue("value1", "en", published: true)); - Assert.IsFalse(document.IsCultureEdited("en")); //This returns false, everything is published - Assert.IsFalse(document.IsCultureEdited("fr")); //False because no french property has ever been edited + Assert.IsFalse(document.IsCultureEdited("en")); // This returns false, everything is published + Assert.IsFalse(document.IsCultureEdited("fr")); // False because no french property has ever been edited Assert.IsFalse(document.Edited); // switch property back to Invariant @@ -965,14 +980,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentTypeService.Save(contentType); document = ContentService.GetById(document.Id); - Assert.AreEqual("v1en2", document.GetValue("value1")); //The variant property value gets copied over to the invariant + Assert.AreEqual("v1en2", document.GetValue("value1")); // The variant property value gets copied over to the invariant Assert.AreEqual("v1en2", document.GetValue("value1", published: true)); - Assert.IsNull(document.GetValue("value1", "fr")); //The values are there but the business logic returns null - Assert.IsNull(document.GetValue("value1", "fr", published: true)); //The values are there but the business logic returns null - Assert.IsFalse(document.IsCultureEdited("en")); //The variant published AND edited values are copied over to the invariant + Assert.IsNull(document.GetValue("value1", "fr")); // The values are there but the business logic returns null + Assert.IsNull(document.GetValue("value1", "fr", published: true)); // The values are there but the business logic returns null + Assert.IsFalse(document.IsCultureEdited("en")); // The variant published AND edited values are copied over to the invariant Assert.IsFalse(document.IsCultureEdited("fr")); Assert.IsFalse(document.Edited); - } [Test] @@ -984,18 +998,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change the composed content type to invariant and back CreateFrenchAndEnglishLangs(); - var composing = CreateContentType(ContentVariation.Culture, "composing"); + IContentType composing = CreateContentType(ContentVariation.Culture, "composing"); - var properties1 = CreatePropertyCollection( + PropertyTypeCollection properties1 = CreatePropertyCollection( ("value11", ContentVariation.Culture), ("value12", ContentVariation.Nothing)); composing.PropertyGroups.Add(new PropertyGroup(properties1) { Name = "Content" }); ContentTypeService.Save(composing); - var composed = CreateContentType(ContentVariation.Culture, "composed"); + IContentType composed = CreateContentType(ContentVariation.Culture, "composed"); - var properties2 = CreatePropertyCollection( + PropertyTypeCollection properties2 = CreatePropertyCollection( ("value21", ContentVariation.Culture), ("value22", ContentVariation.Nothing)); @@ -1003,7 +1017,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services composed.AddContentType(composing); ContentTypeService.Save(composed); - var document = (IContent) new Content("document", -1, composed); + var document = (IContent)new Content("document", -1, composed); document.SetCultureName("doc1en", "en"); document.SetCultureName("doc1fr", "fr"); document.SetValue("value11", "v11en", "en"); @@ -1016,7 +1030,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // both value11 and value21 are variant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'c':'en','v':'v21en'},{'c':'fr','v':'v21fr'}],'value22':[{'v':'v22'}]},'cd':"); composed.Variations = ContentVariation.Nothing; @@ -1024,7 +1039,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // both value11 and value21 are invariant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composed.Variations = ContentVariation.Culture; @@ -1032,7 +1048,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is variant again, but value21 is still invariant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composed.PropertyTypes.First(x => x.Alias == "value21").Variations = ContentVariation.Culture; @@ -1040,7 +1057,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // we can make it variant again Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composing.Variations = ContentVariation.Nothing; @@ -1048,7 +1066,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is invariant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composing.Variations = ContentVariation.Culture; @@ -1056,7 +1075,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is still invariant Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); composing.PropertyTypes.First(x => x.Alias == "value11").Variations = ContentVariation.Culture; @@ -1064,7 +1084,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // we can make it variant again Console.WriteLine(GetJson(document.Id)); - AssertJsonStartsWith(document.Id, + AssertJsonStartsWith( + document.Id, "{'pd':{'value11':[{'c':'fr','v':'v11fr'},{'c':'en','v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); } @@ -1078,18 +1099,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // can change the variant composed content type to invariant and back CreateFrenchAndEnglishLangs(); - var composing = CreateContentType(ContentVariation.Culture, "composing"); + IContentType composing = CreateContentType(ContentVariation.Culture, "composing"); - var properties1 = CreatePropertyCollection( + PropertyTypeCollection properties1 = CreatePropertyCollection( ("value11", ContentVariation.Culture), ("value12", ContentVariation.Nothing)); composing.PropertyGroups.Add(new PropertyGroup(properties1) { Name = "Content" }); ContentTypeService.Save(composing); - var composed1 = CreateContentType(ContentVariation.Culture, "composed1"); + IContentType composed1 = CreateContentType(ContentVariation.Culture, "composed1"); - var properties2 = CreatePropertyCollection( + PropertyTypeCollection properties2 = CreatePropertyCollection( ("value21", ContentVariation.Culture), ("value22", ContentVariation.Nothing)); @@ -1097,9 +1118,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services composed1.AddContentType(composing); ContentTypeService.Save(composed1); - var composed2 = CreateContentType(ContentVariation.Nothing, "composed2"); + IContentType composed2 = CreateContentType(ContentVariation.Nothing, "composed2"); - var properties3 = CreatePropertyCollection( + PropertyTypeCollection properties3 = CreatePropertyCollection( ("value31", ContentVariation.Nothing), ("value32", ContentVariation.Nothing)); @@ -1107,7 +1128,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services composed2.AddContentType(composing); ContentTypeService.Save(composed2); - var document1 = (IContent) new Content ("document1", -1, composed1); + var document1 = (IContent)new Content("document1", -1, composed1); document1.SetCultureName("doc1en", "en"); document1.SetCultureName("doc1fr", "fr"); document1.SetValue("value11", "v11en", "en"); @@ -1128,11 +1149,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // both value11 and value21 are variant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'c':'en','v':'v21en'},{'c':'fr','v':'v21fr'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composed1.Variations = ContentVariation.Nothing; @@ -1140,11 +1163,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // both value11 and value21 are invariant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composed1.Variations = ContentVariation.Culture; @@ -1152,11 +1177,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is variant again, but value21 is still invariant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composed1.PropertyTypes.First(x => x.Alias == "value21").Variations = ContentVariation.Culture; @@ -1164,11 +1191,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // we can make it variant again Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'c':'en','v':'v11en'},{'c':'fr','v':'v11fr'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composing.Variations = ContentVariation.Nothing; @@ -1176,11 +1205,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is invariant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composing.Variations = ContentVariation.Culture; @@ -1188,11 +1219,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // value11 is still invariant Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); composing.PropertyTypes.First(x => x.Alias == "value11").Variations = ContentVariation.Culture; @@ -1200,11 +1233,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // we can make it variant again Console.WriteLine(GetJson(document1.Id)); - AssertJsonStartsWith(document1.Id, + AssertJsonStartsWith( + document1.Id, "{'pd':{'value11':[{'c':'fr','v':'v11fr'},{'c':'en','v':'v11en'}],'value12':[{'v':'v12'}],'value21':[{'c':'fr','v':'v21fr'},{'c':'en','v':'v21en'}],'value22':[{'v':'v22'}]},'cd':"); Console.WriteLine(GetJson(document2.Id)); - AssertJsonStartsWith(document2.Id, + AssertJsonStartsWith( + document2.Id, "{'pd':{'value11':[{'v':'v11'}],'value12':[{'v':'v12'}],'value31':[{'v':'v31'}],'value32':[{'v':'v32'}]},'cd':"); } @@ -1228,13 +1263,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { var propertyCollection = new PropertyTypeCollection(true); - foreach (var (alias, variance) in props) + foreach ((string alias, ContentVariation variance) in props) + { propertyCollection.Add(new PropertyType(ShortStringHelper, alias, ValueStorageType.Ntext) { Alias = alias, DataTypeId = -88, Variations = variance }); + } return propertyCollection; } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DataTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DataTypeServiceTests.cs index 2de7fb6b2a..9c284fb4b7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DataTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/DataTypeServiceTests.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.Threading; using NUnit.Framework; @@ -21,11 +25,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class DataTypeServiceTests : UmbracoIntegrationTest { private IDataTypeService DataTypeService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private ILocalizedTextService LocalizedTextService => GetRequiredService(); + private ILocalizationService LocalizationService => GetRequiredService(); + private IConfigurationEditorJsonSerializer ConfigurationEditorJsonSerializer => GetRequiredService(); + private IJsonSerializer JsonSerializer => GetRequiredService(); [Test] @@ -47,26 +57,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void DataTypeService_Can_Delete_Textfield_DataType_And_Clear_Usages() { // Arrange - var textfieldId = "Umbraco.Textbox"; - var dataTypeDefinitions = DataTypeService.GetByEditorAlias(textfieldId); - var template = TemplateBuilder.CreateTextPageTemplate(); + string textfieldId = "Umbraco.Textbox"; + IEnumerable dataTypeDefinitions = DataTypeService.GetByEditorAlias(textfieldId); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var doctype = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); + ContentType doctype = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); ContentTypeService.Save(doctype); - // Act - var definition = dataTypeDefinitions.First(); - var definitionId = definition.Id; + IDataType definition = dataTypeDefinitions.First(); + int definitionId = definition.Id; DataTypeService.Delete(definition); - var deletedDefinition = DataTypeService.GetDataType(definitionId); + IDataType deletedDefinition = DataTypeService.GetDataType(definitionId); // Assert Assert.That(deletedDefinition, Is.Null); - //Further assertions against the ContentType that contains PropertyTypes based on the TextField - var contentType = ContentTypeService.Get(doctype.Id); + // Further assertions against the ContentType that contains PropertyTypes based on the TextField + IContentType contentType = ContentTypeService.Get(doctype.Id); Assert.That(contentType.Alias, Is.EqualTo("umbTextpage")); Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(1)); } @@ -75,7 +84,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_DataType_With_Empty_Name() { // Act - var dataTypeDefinition = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService,LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { Name = string.Empty, DatabaseType = ValueStorageType.Ntext }; + var dataTypeDefinition = new DataType(new LabelPropertyEditor(LoggerFactory, IOHelper, DataTypeService, LocalizedTextService, LocalizationService, ShortStringHelper, JsonSerializer), ConfigurationEditorJsonSerializer) { Name = string.Empty, DatabaseType = ValueStorageType.Ntext }; // Act & Assert Assert.Throws(() => DataTypeService.Save(dataTypeDefinition)); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs index 6d5cf19b50..a221575f7c 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityServiceTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Linq; @@ -18,7 +21,6 @@ using Umbraco.Web.PublishedCache.NuCache; namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { - /// /// Tests covering the EntityService /// @@ -31,12 +33,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private Language _langEs; private ILocalizationService LocalizationService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IContentService ContentService => GetRequiredService(); + private IEntityService EntityService => GetRequiredService(); + private ISqlContext SqlContext => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); + private IMediaService MediaService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); [SetUp] @@ -57,24 +66,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Descendants_Ordering_Path() { + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var contentType = ContentTypeService.Get("umbTextpage"); - - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); - var rootId = root.Id; + int rootId = root.Id; var ids = new List(); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); ids.Add(c1.Id); root = c1; // make a hierarchy } - long total; - - var entities = EntityService.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 0, 6, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[0], entities[0].Id); @@ -84,15 +90,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[6], entities[0].Id); - //Test ordering direction - - entities = EntityService.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 0, 6, out total, + // Test ordering direction + entities = EntityService.GetPagedDescendants( + rootId, + UmbracoObjectTypes.Document, + 0, + 6, + out total, ordering: Ordering.By("Path", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); - Assert.AreEqual(ids[ids.Count - 1], entities[0].Id); + Assert.AreEqual(ids[^1], entities[0].Id); - entities = EntityService.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 1, 6, out total, + entities = EntityService.GetPagedDescendants( + rootId, + UmbracoObjectTypes.Document, + 1, + 6, + out total, ordering: Ordering.By("Path", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); @@ -102,22 +117,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Children() { + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var contentType = ContentTypeService.Get("umbTextpage"); - - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); var ids = new List(); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); ids.Add(c1.Id); } - long total; - - var entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 0, 6, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[0], entities[0].Id); @@ -127,15 +139,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[6], entities[0].Id); - //Test ordering direction - - entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 0, 6, out total, + // Test ordering direction + entities = EntityService.GetPagedChildren( + root.Id, + UmbracoObjectTypes.Document, + 0, + 6, + out total, ordering: Ordering.By("SortOrder", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); - Assert.AreEqual(ids[ids.Count - 1], entities[0].Id); + Assert.AreEqual(ids[^1], entities[0].Id); - entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 1, 6, out total, + entities = EntityService.GetPagedChildren( + root.Id, + UmbracoObjectTypes.Document, + 1, + 6, + out total, ordering: Ordering.By("SortOrder", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); @@ -145,27 +166,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Descendants() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); - var count = 0; + int count = 0; for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); count++; for (int j = 0; j < 5; j++) { - var c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); + Content c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); ContentService.Save(c2); count++; } } - long total; - var entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 31, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 31, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(31)); Assert.That(total, Is.EqualTo(60)); entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 1, 31, out total).ToArray(); @@ -176,14 +196,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Descendants_Including_Recycled() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); var toDelete = new List(); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); if (i % 2 == 0) @@ -193,23 +213,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int j = 0; j < 5; j++) { - var c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); + Content c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); ContentService.Save(c2); } } - foreach (var content in toDelete) + foreach (IContent content in toDelete) { ContentService.MoveToRecycleBin(content); } - long total; - //search at root to see if it returns recycled - var entities = EntityService.GetPagedDescendants(-1, UmbracoObjectTypes.Document, 0, 1000, out total) + // search at root to see if it returns recycled + int[] entities = EntityService.GetPagedDescendants(-1, UmbracoObjectTypes.Document, 0, 1000, out long total) .Select(x => x.Id) .ToArray(); - foreach (var c in toDelete) + foreach (IContent c in toDelete) { Assert.True(entities.Contains(c.Id)); } @@ -218,14 +237,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Descendants_Without_Recycled() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); var toDelete = new List(); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ContentService.Save(c1); if (i % 2 == 0) @@ -235,23 +254,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int j = 0; j < 5; j++) { - var c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); + Content c2 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); ContentService.Save(c2); } } - foreach (var content in toDelete) + foreach (IContent content in toDelete) { ContentService.MoveToRecycleBin(content); } - long total; - //search at root to see if it returns recycled - var entities = EntityService.GetPagedDescendants(UmbracoObjectTypes.Document, 0, 1000, out total, includeTrashed: false) + // search at root to see if it returns recycled + int[] entities = EntityService.GetPagedDescendants(UmbracoObjectTypes.Document, 0, 1000, out long total, includeTrashed: false) .Select(x => x.Id) .ToArray(); - foreach (var c in toDelete) + foreach (IContent c in toDelete) { Assert.IsFalse(entities.Contains(c.Id)); } @@ -260,29 +278,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Content_Descendants_With_Search() { - var contentType = ContentTypeService.Get("umbTextpage"); + IContentType contentType = ContentTypeService.Get("umbTextpage"); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(root); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, "ssss" + Guid.NewGuid(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, "ssss" + Guid.NewGuid(), root); ContentService.Save(c1); for (int j = 0; j < 5; j++) { - var c2 = ContentBuilder.CreateSimpleContent(contentType, "tttt" + Guid.NewGuid(), c1); + Content c2 = ContentBuilder.CreateSimpleContent(contentType, "tttt" + Guid.NewGuid(), c1); ContentService.Save(c2); } } - long total; - var entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 10, out total, + IEntitySlim[] entities = EntityService.GetPagedDescendants( + root.Id, + UmbracoObjectTypes.Document, + 0, + 10, + out long total, filter: SqlContext.Query().Where(x => x.Name.Contains("ssss"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(10)); Assert.That(total, Is.EqualTo(10)); - entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 50, out total, + entities = EntityService.GetPagedDescendants( + root.Id, + UmbracoObjectTypes.Document, + 0, + 50, + out total, filter: SqlContext.Query().Where(x => x.Name.Contains("tttt"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(50)); Assert.That(total, Is.EqualTo(50)); @@ -291,19 +318,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Children() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); MediaService.Save(c1); } - long total; - var entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Media, 0, 6, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Media, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = EntityService.GetPagedChildren(root.Id, UmbracoObjectTypes.Media, 1, 6, out total).ToArray(); @@ -314,28 +340,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Descendants() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); - var count = 0; + int count = 0; for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); MediaService.Save(c1); count++; for (int j = 0; j < 5; j++) { - var c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); + Media c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); MediaService.Save(c2); count++; } } - long total; - var entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 31, out total).ToArray(); + IEntitySlim[] entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 31, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(31)); Assert.That(total, Is.EqualTo(60)); entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 1, 31, out total).ToArray(); @@ -346,15 +371,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Descendants_Including_Recycled() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); var toDelete = new List(); for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); MediaService.Save(c1); if (i % 2 == 0) @@ -364,23 +389,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int j = 0; j < 5; j++) { - var c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); + Media c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); MediaService.Save(c2); } } - foreach (var content in toDelete) + foreach (IMedia content in toDelete) { MediaService.MoveToRecycleBin(content); } - long total; - //search at root to see if it returns recycled - var entities = EntityService.GetPagedDescendants(-1, UmbracoObjectTypes.Media, 0, 1000, out total) + // search at root to see if it returns recycled + int[] entities = EntityService.GetPagedDescendants(-1, UmbracoObjectTypes.Media, 0, 1000, out long total) .Select(x => x.Id) .ToArray(); - foreach (var media in toDelete) + foreach (IMedia media in toDelete) { Assert.IsTrue(entities.Contains(media.Id)); } @@ -389,15 +413,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Descendants_Without_Recycled() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); var toDelete = new List(); for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); MediaService.Save(c1); if (i % 2 == 0) @@ -407,23 +431,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services for (int j = 0; j < 5; j++) { - var c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); + Media c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); MediaService.Save(c2); } } - foreach (var content in toDelete) + foreach (IMedia content in toDelete) { MediaService.MoveToRecycleBin(content); } - long total; - //search at root to see if it returns recycled - var entities = EntityService.GetPagedDescendants(UmbracoObjectTypes.Media, 0, 1000, out total, includeTrashed: false) + // search at root to see if it returns recycled + int[] entities = EntityService.GetPagedDescendants(UmbracoObjectTypes.Media, 0, 1000, out long total, includeTrashed: false) .Select(x => x.Id) .ToArray(); - foreach (var media in toDelete) + foreach (IMedia media in toDelete) { Assert.IsFalse(entities.Contains(media.Id)); } @@ -432,32 +455,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Paged_Media_Descendants_With_Search() { - var folderType = MediaTypeService.Get(1031); - var imageMediaType = MediaTypeService.Get(1032); + IMediaType folderType = MediaTypeService.Get(1031); + IMediaType imageMediaType = MediaTypeService.Get(1032); - var root = MediaBuilder.CreateMediaFolder(folderType, -1); + Media root = MediaBuilder.CreateMediaFolder(folderType, -1); MediaService.Save(root); for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); + Media c1 = MediaBuilder.CreateMediaImage(imageMediaType, root.Id); c1.Name = "ssss" + Guid.NewGuid(); MediaService.Save(c1); for (int j = 0; j < 5; j++) { - var c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); + Media c2 = MediaBuilder.CreateMediaImage(imageMediaType, c1.Id); c2.Name = "tttt" + Guid.NewGuid(); MediaService.Save(c2); } } - long total; - var entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 10, out total, + IEntitySlim[] entities = EntityService.GetPagedDescendants( + root.Id, + UmbracoObjectTypes.Media, + 0, + 10, + out long total, filter: SqlContext.Query().Where(x => x.Name.Contains("ssss"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(10)); Assert.That(total, Is.EqualTo(10)); - entities = EntityService.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 50, out total, + entities = EntityService.GetPagedDescendants( + root.Id, + UmbracoObjectTypes.Media, + 0, + 50, + out total, filter: SqlContext.Query().Where(x => x.Name.Contains("tttt"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(50)); Assert.That(total, Is.EqualTo(50)); @@ -466,7 +498,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_Content_By_UmbracoObjectTypes() { - var entities = EntityService.GetAll(UmbracoObjectTypes.Document).ToArray(); + IEntitySlim[] entities = EntityService.GetAll(UmbracoObjectTypes.Document).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(4)); @@ -476,8 +508,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_Content_By_UmbracoObjectType_Id() { - var objectTypeId = Constants.ObjectTypes.Document; - var entities = EntityService.GetAll(objectTypeId).ToArray(); + Guid objectTypeId = Constants.ObjectTypes.Document; + IEntitySlim[] entities = EntityService.GetAll(objectTypeId).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(4)); @@ -487,7 +519,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_Content_By_Type() { - var entities = EntityService.GetAll().ToArray(); + IEntitySlim[] entities = EntityService.GetAll().ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(4)); @@ -497,7 +529,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Child_Content_By_ParentId_And_UmbracoObjectType() { - var entities = EntityService.GetChildren(-1, UmbracoObjectTypes.Document).ToArray(); + IEntitySlim[] entities = EntityService.GetChildren(-1, UmbracoObjectTypes.Document).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(1)); @@ -507,23 +539,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Content_By_UmbracoObjectType_With_Variant_Names() { - var alias = "test" + Guid.NewGuid(); - var template = TemplateBuilder.CreateTextPageTemplate(alias); + string alias = "test" + Guid.NewGuid(); + Template template = TemplateBuilder.CreateTextPageTemplate(alias); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test2", "Test2", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test2", "Test2", defaultTemplateId: template.Id); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var c1 = ContentBuilder.CreateSimpleContent(contentType, "Test", -1); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, "Test", -1); c1.SetCultureName("Test - FR", _langFr.IsoCode); c1.SetCultureName("Test - ES", _langEs.IsoCode); ContentService.Save(c1); - var result = EntityService.Get(c1.Id, UmbracoObjectTypes.Document); + IEntitySlim result = EntityService.Get(c1.Id, UmbracoObjectTypes.Document); Assert.AreEqual("Test - FR", result.Name); // got name from default culture Assert.IsNotNull(result as IDocumentEntitySlim); var doc = (IDocumentEntitySlim)result; - var cultureNames = doc.CultureNames; + IReadOnlyDictionary cultureNames = doc.CultureNames; Assert.AreEqual("Test - FR", cultureNames[_langFr.IsoCode]); Assert.AreEqual("Test - ES", cultureNames[_langEs.IsoCode]); } @@ -531,19 +563,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Child_Content_By_ParentId_And_UmbracoObjectType_With_Variant_Names() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("test1", "Test1", defaultTemplateId: template.Id); contentType.Variations = ContentVariation.Culture; ContentTypeService.Save(contentType); - var root = ContentBuilder.CreateSimpleContent(contentType); + Content root = ContentBuilder.CreateSimpleContent(contentType); root.SetCultureName("Root", _langFr.IsoCode); // else cannot save ContentService.Save(root); for (int i = 0; i < 10; i++) { - var c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); + Content c1 = ContentBuilder.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); if (i % 2 == 0) { c1.SetCultureName("Test " + i + " - FR", _langFr.IsoCode); @@ -553,10 +585,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { c1.SetCultureName("Test", _langFr.IsoCode); // else cannot save } + ContentService.Save(c1); } - var entities = EntityService.GetChildren(root.Id, UmbracoObjectTypes.Document).ToArray(); + IEntitySlim[] entities = EntityService.GetChildren(root.Id, UmbracoObjectTypes.Document).ToArray(); Assert.AreEqual(10, entities.Length); @@ -584,7 +617,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Children_By_ParentId() { - var entities = EntityService.GetChildren(folderId); + IEnumerable entities = EntityService.GetChildren(_folderId); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(3)); @@ -594,7 +627,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Descendants_By_ParentId() { - var entities = EntityService.GetDescendants(folderId); + IEnumerable entities = EntityService.GetDescendants(_folderId); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(4)); @@ -604,7 +637,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Throws_When_Getting_All_With_Invalid_Type() { - var objectTypeId = Constants.ObjectTypes.ContentItem; + Guid objectTypeId = Constants.ObjectTypes.ContentItem; Assert.Throws(() => EntityService.GetAll()); Assert.Throws(() => EntityService.GetAll(objectTypeId)); @@ -613,7 +646,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_ContentTypes_By_UmbracoObjectTypes() { - var entities = EntityService.GetAll(UmbracoObjectTypes.DocumentType).ToArray(); + IEntitySlim[] entities = EntityService.GetAll(UmbracoObjectTypes.DocumentType).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(1)); @@ -622,8 +655,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_ContentTypes_By_UmbracoObjectType_Id() { - var objectTypeId = Constants.ObjectTypes.DocumentType; - var entities = EntityService.GetAll(objectTypeId).ToArray(); + Guid objectTypeId = Constants.ObjectTypes.DocumentType; + IEntitySlim[] entities = EntityService.GetAll(objectTypeId).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(1)); @@ -632,7 +665,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_ContentTypes_By_Type() { - var entities = EntityService.GetAll().ToArray(); + IEntitySlim[] entities = EntityService.GetAll().ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(1)); @@ -641,12 +674,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Find_All_Media_By_UmbracoObjectTypes() { - var entities = EntityService.GetAll(UmbracoObjectTypes.Media).ToArray(); + IEntitySlim[] entities = EntityService.GetAll(UmbracoObjectTypes.Media).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(5)); - foreach (var entity in entities) + foreach (IEntitySlim entity in entities) { Assert.IsTrue(entity.GetType().Implements()); Console.WriteLine(((IMediaEntitySlim)entity).MediaPath); @@ -656,8 +689,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_ObjectType() - { ; - var mediaObjectType = EntityService.GetObjectType(1031); + { + UmbracoObjectTypes mediaObjectType = EntityService.GetObjectType(1031); Assert.NotNull(mediaObjectType); Assert.AreEqual(mediaObjectType, UmbracoObjectTypes.MediaType); @@ -666,7 +699,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Key_For_Id_With_Unknown_Type() { - var result = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.Unknown); + Attempt result = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.Unknown); Assert.IsTrue(result.Success); Assert.AreEqual(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), result.Result); @@ -675,7 +708,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Key_For_Id() { - var result = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.DocumentType); + Attempt result = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.DocumentType); Assert.IsTrue(result.Success); Assert.AreEqual(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), result.Result); @@ -684,8 +717,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Cannot_Get_Key_For_Id_With_Incorrect_Object_Type() { - var result1 = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.DocumentType); - var result2 = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.MediaType); + Attempt result1 = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.DocumentType); + Attempt result2 = EntityService.GetKey(_contentType.Id, UmbracoObjectTypes.MediaType); Assert.IsTrue(result1.Success); Assert.IsFalse(result2.Success); @@ -694,7 +727,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Id_For_Key_With_Unknown_Type() { - var result = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.Unknown); + Attempt result = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.Unknown); Assert.IsTrue(result.Success); Assert.AreEqual(_contentType.Id, result.Result); @@ -703,7 +736,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Can_Get_Id_For_Key() { - var result = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); + Attempt result = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); Assert.IsTrue(result.Success); Assert.AreEqual(_contentType.Id, result.Result); @@ -712,8 +745,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void EntityService_Cannot_Get_Id_For_Key_With_Incorrect_Object_Type() { - var result1 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); - var result2 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.MediaType); + Attempt result1 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); + Attempt result2 = EntityService.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.MediaType); Assert.IsTrue(result1.Success); Assert.IsFalse(result2.Success); @@ -725,11 +758,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var guid = Guid.NewGuid(); // can reserve - var reservedId = EntityService.ReserveId(guid); + int reservedId = EntityService.ReserveId(guid); Assert.IsTrue(reservedId > 0); // can get it back - var id = EntityService.GetId(guid, UmbracoObjectTypes.DocumentType); + Attempt id = EntityService.GetId(guid, UmbracoObjectTypes.DocumentType); Assert.IsTrue(id.Success); Assert.AreEqual(reservedId, id.Result); @@ -742,9 +775,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsFalse(EntityService.GetId(Guid.NewGuid(), UmbracoObjectTypes.DocumentType).Success); } - private static bool _isSetup = false; + private static bool s_isSetup = false; - private int folderId; + private int _folderId; private ContentType _contentType; private Content _textpage; private Content _subpage; @@ -759,56 +792,57 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void CreateTestData() { - if (_isSetup == false) + if (s_isSetup == false) { - _isSetup = true; + s_isSetup = true; - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // else, FK violation on contentType! - //Create and Save ContentType "umbTextpage" -> _contentType.Id + // Create and Save ContentType "umbTextpage" -> _contentType.Id _contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); _contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"); ContentTypeService.Save(_contentType); - //Create and Save Content "Homepage" based on "umbTextpage" -> 1053 + // Create and Save Content "Homepage" based on "umbTextpage" -> 1053 _textpage = ContentBuilder.CreateSimpleContent(_contentType); _textpage.Key = new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0"); ContentService.Save(_textpage, 0); - //Create and Save Content "Text Page 1" based on "umbTextpage" -> 1054 + // Create and Save Content "Text Page 1" based on "umbTextpage" -> 1054 _subpage = ContentBuilder.CreateSimpleContent(_contentType, "Text Page 1", _textpage.Id); _subpage.ContentSchedule.Add(DateTime.Now.AddMinutes(-5), null); ContentService.Save(_subpage, 0); - //Create and Save Content "Text Page 2" based on "umbTextpage" -> 1055 + // Create and Save Content "Text Page 2" based on "umbTextpage" -> 1055 _subpage2 = ContentBuilder.CreateSimpleContent(_contentType, "Text Page 2", _textpage.Id); ContentService.Save(_subpage2, 0); - //Create and Save Content "Text Page Deleted" based on "umbTextpage" -> 1056 + // Create and Save Content "Text Page Deleted" based on "umbTextpage" -> 1056 _trashed = ContentBuilder.CreateSimpleContent(_contentType, "Text Page Deleted", -20); _trashed.Trashed = true; ContentService.Save(_trashed, 0); - //Create and Save folder-Media -> 1057 + // Create and Save folder-Media -> 1057 _folderMediaType = MediaTypeService.Get(1031); _folder = MediaBuilder.CreateMediaFolder(_folderMediaType, -1); MediaService.Save(_folder, 0); - folderId = _folder.Id; + _folderId = _folder.Id; - //Create and Save image-Media -> 1058 + // Create and Save image-Media -> 1058 _imageMediaType = MediaTypeService.Get(1032); _image = MediaBuilder.CreateMediaImage(_imageMediaType, _folder.Id); MediaService.Save(_image, 0); - //Create and Save file-Media -> 1059 - var fileMediaType = MediaTypeService.Get(1033); - var file = MediaBuilder.CreateMediaFile(fileMediaType, _folder.Id); + // Create and Save file-Media -> 1059 + IMediaType fileMediaType = MediaTypeService.Get(1033); + Media file = MediaBuilder.CreateMediaFile(fileMediaType, _folder.Id); MediaService.Save(file, 0); // Create and save sub folder -> 1060 _subfolder = MediaBuilder.CreateMediaFolder(_folderMediaType, _folder.Id); MediaService.Save(_subfolder, 0); + // Create and save sub folder -> 1061 _subfolder2 = MediaBuilder.CreateMediaFolder(_folderMediaType, _subfolder.Id); MediaService.Save(_subfolder2, 0); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs index 8a04caeac7..d9c523bc58 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Xml.Linq; @@ -23,15 +26,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Export_Macro() { // Arrange - var macroService = GetRequiredService(); - var macro = new MacroBuilder() + IMacroService macroService = GetRequiredService(); + Macro macro = new MacroBuilder() .WithAlias("test1") .WithName("Test") .Build(); macroService.Save(macro); // Act - var element = Serializer.Serialize(macro); + XElement element = Serializer.Serialize(macro); // Assert Assert.That(element, Is.Not.Null); @@ -45,14 +48,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Arrange CreateDictionaryData(); - var localizationService = GetRequiredService(); - var dictionaryItem = localizationService.GetDictionaryItemByKey("Parent"); + ILocalizationService localizationService = GetRequiredService(); + IDictionaryItem dictionaryItem = localizationService.GetDictionaryItemByKey("Parent"); var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); + XElement dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First(); // Act - var xml = Serializer.Serialize(new[] { dictionaryItem }); + XElement xml = Serializer.Serialize(new[] { dictionaryItem }); // Assert Assert.That(xml.ToString(), Is.EqualTo(dictionaryItemsElement.ToString())); @@ -62,24 +65,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Export_Languages() { // Arrange - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - var languageNbNo = new LanguageBuilder() + ILanguage languageNbNo = new LanguageBuilder() .WithCultureInfo("nb-NO") .WithCultureName("Norwegian") .Build(); localizationService.Save(languageNbNo); - var languageEnGb = new LanguageBuilder() + ILanguage languageEnGb = new LanguageBuilder() .WithCultureInfo("en-GB") .Build(); localizationService.Save(languageEnGb); var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); - var languageItemsElement = newPackageXml.Elements("Languages").First(); + XElement languageItemsElement = newPackageXml.Elements("Languages").First(); // Act - var xml = Serializer.Serialize(new[] { languageNbNo, languageEnGb }); + XElement xml = Serializer.Serialize(new[] { languageNbNo, languageEnGb }); // Assert Assert.That(xml.ToString(), Is.EqualTo(languageItemsElement.ToString())); @@ -87,15 +90,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void CreateDictionaryData() { - var localizationService = GetRequiredService(); + ILocalizationService localizationService = GetRequiredService(); - var languageNbNo = new LanguageBuilder() + ILanguage languageNbNo = new LanguageBuilder() .WithCultureInfo("nb-NO") .WithCultureName("Norwegian") .Build(); localizationService.Save(languageNbNo); - var languageEnGb = new LanguageBuilder() + ILanguage languageEnGb = new LanguageBuilder() .WithCultureInfo("en-GB") .Build(); localizationService.Save(languageEnGb); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs index 192971f405..b47c8fb51e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs @@ -1,4 +1,8 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; +using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; @@ -18,6 +22,7 @@ namespace Umbraco.Tests.Services public class ExternalLoginServiceTests : UmbracoIntegrationTest { private IUserService UserService => GetRequiredService(); + private IExternalLoginService ExternalLoginService => GetRequiredService(); [Test] @@ -26,11 +31,11 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var providerKey = Guid.NewGuid().ToString("N"); - var latest = DateTime.Now.AddDays(-1); - var oldest = DateTime.Now.AddDays(-10); + string providerKey = Guid.NewGuid().ToString("N"); + DateTime latest = DateTime.Now.AddDays(-1); + DateTime oldest = DateTime.Now.AddDays(-10); - using (var scope = ScopeProvider.CreateScope()) + using (Core.Scoping.IScope scope = ScopeProvider.CreateScope()) { // insert duplicates manuall scope.Database.Insert(new ExternalLoginDto @@ -50,7 +55,7 @@ namespace Umbraco.Tests.Services } // try to save 2 other duplicates - var externalLogins = new[] + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test2", providerKey), new ExternalLogin("test2", providerKey), @@ -64,7 +69,7 @@ namespace Umbraco.Tests.Services // duplicates will be removed, keeping the latest entries Assert.AreEqual(2, logins.Count); - var test1 = logins.Single(x => x.LoginProvider == "test1"); + IIdentityUserLogin test1 = logins.Single(x => x.LoginProvider == "test1"); Assert.Greater(test1.CreateDate, latest); } @@ -74,8 +79,8 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var providerKey = Guid.NewGuid().ToString("N"); - var externalLogins = new[] + string providerKey = Guid.NewGuid().ToString("N"); + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test1", providerKey), new ExternalLogin("test1", providerKey) @@ -99,7 +104,7 @@ namespace Umbraco.Tests.Services }; ExternalLoginService.Save(extLogin); - var found = ExternalLoginService.GetAll(user.Id); + IEnumerable found = ExternalLoginService.GetAll(user.Id); Assert.AreEqual(1, found.Count()); Assert.IsTrue(extLogin.HasIdentity); @@ -132,9 +137,9 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var providerKey1 = Guid.NewGuid().ToString("N"); - var providerKey2 = Guid.NewGuid().ToString("N"); - var extLogins = new[] + string providerKey1 = Guid.NewGuid().ToString("N"); + string providerKey2 = Guid.NewGuid().ToString("N"); + ExternalLogin[] extLogins = new[] { new ExternalLogin("test1", providerKey1, "hello"), new ExternalLogin("test2", providerKey2, "world") @@ -160,9 +165,9 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var providerKey1 = Guid.NewGuid().ToString("N"); - var providerKey2 = Guid.NewGuid().ToString("N"); - var extLogins = new[] + string providerKey1 = Guid.NewGuid().ToString("N"); + string providerKey2 = Guid.NewGuid().ToString("N"); + ExternalLogin[] extLogins = new[] { new ExternalLogin("test1", providerKey1, "hello"), new ExternalLogin("test2", providerKey2, "world") @@ -173,7 +178,6 @@ namespace Umbraco.Tests.Services Assert.AreEqual(1, found.Count); var asExtended = found.ToList(); Assert.AreEqual(1, found.Count); - } [Test] @@ -182,7 +186,7 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var externalLogins = new[] + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test1", Guid.NewGuid().ToString("N")), new ExternalLogin("test2", Guid.NewGuid().ToString("N")) @@ -205,7 +209,7 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var externalLogins = new[] + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test1", Guid.NewGuid().ToString("N")), new ExternalLogin("test2", Guid.NewGuid().ToString("N")), @@ -237,7 +241,7 @@ namespace Umbraco.Tests.Services var user = new User(GlobalSettings, "Test", "test@test.com", "test", "helloworldtest"); UserService.Save(user); - var externalLogins = new[] + ExternalLogin[] externalLogins = new[] { new ExternalLogin("test1", Guid.NewGuid().ToString("N"), "hello world") }; @@ -247,7 +251,6 @@ namespace Umbraco.Tests.Services var logins = ExternalLoginService.GetAll(user.Id).ToList(); Assert.AreEqual("hello world", logins[0].UserData); - } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/FileServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/FileServiceTests.cs index 1820573cc2..9ca4b79a6e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/FileServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/FileServiceTests.cs @@ -1,7 +1,11 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using System.Threading; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -18,8 +22,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Template_Then_Assign_Child() { - var child = FileService.CreateTemplateWithIdentity("Child", "child", "test"); - var parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); + ITemplate child = FileService.CreateTemplateWithIdentity("Child", "child", "test"); + ITemplate parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); child.SetMasterTemplate(parent); FileService.SaveTemplate(child); @@ -27,14 +31,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services child = FileService.GetTemplate(child.Id); Assert.AreEqual(parent.Alias, child.MasterTemplateAlias); - } [Test] public void Create_Template_With_Child_Then_Unassign() { - var parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); - var child = FileService.CreateTemplateWithIdentity("Child", "child", "test", parent); + ITemplate parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); + ITemplate child = FileService.CreateTemplateWithIdentity("Child", "child", "test", parent); child.SetMasterTemplate(null); FileService.SaveTemplate(child); @@ -47,11 +50,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Query_Template_Children() { - var parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); - var child1 = FileService.CreateTemplateWithIdentity("Child1", "child1", "test", parent); - var child2 = FileService.CreateTemplateWithIdentity("Child2", "child2", "test", parent); + ITemplate parent = FileService.CreateTemplateWithIdentity("Parent", "parent", "test"); + ITemplate child1 = FileService.CreateTemplateWithIdentity("Child1", "child1", "test", parent); + ITemplate child2 = FileService.CreateTemplateWithIdentity("Child2", "child2", "test", parent); - var children = FileService.GetTemplates(parent.Id).Select(x => x.Id).ToArray(); + int[] children = FileService.GetTemplates(parent.Id).Select(x => x.Id).ToArray(); Assert.IsTrue(children.Contains(child1.Id)); Assert.IsTrue(children.Contains(child2.Id)); @@ -60,7 +63,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Template_With_Custom_Alias() { - var template = FileService.CreateTemplateWithIdentity("Test template", "customTemplateAlias", "test"); + ITemplate template = FileService.CreateTemplateWithIdentity("Test template", "customTemplateAlias", "test"); FileService.SaveTemplate(template); @@ -69,6 +72,5 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("Test template", template.Name); Assert.AreEqual("customTemplateAlias", template.Alias); } - } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/KeyValueServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/KeyValueServiceTests.cs index 8248e89dc2..5ffbe871a7 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/KeyValueServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/KeyValueServiceTests.cs @@ -1,4 +1,7 @@ -using System.Threading; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Threading; using NUnit.Framework; using Umbraco.Core.Services; using Umbraco.Tests.Integration.Testing; @@ -20,7 +23,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void GetValue_ForMissingKey_ReturnsNull() { // Act - var value = KeyValueService.GetValue("foo"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.IsNull(value); @@ -32,7 +35,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services KeyValueService.SetValue("foo", "bar"); // Act - var value = KeyValueService.GetValue("foo"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.AreEqual("bar", value); @@ -45,7 +48,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Act KeyValueService.SetValue("foo", "buzz"); - var value = KeyValueService.GetValue("foo"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.AreEqual("buzz", value); @@ -57,8 +60,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services KeyValueService.SetValue("foo", "bar"); // Act - var result = KeyValueService.TrySetValue("foo", "bar", "buzz"); - var value = KeyValueService.GetValue("foo"); + bool result = KeyValueService.TrySetValue("foo", "bar", "buzz"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.IsTrue(result); @@ -71,8 +74,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services KeyValueService.SetValue("foo", "bar"); // Act - var result = KeyValueService.TrySetValue("foo", "bang", "buzz"); - var value = KeyValueService.GetValue("foo"); + bool result = KeyValueService.TrySetValue("foo", "bang", "buzz"); + string value = KeyValueService.GetValue("foo"); // Assert Assert.IsFalse(result); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs index 5076a3bbf7..a920682f4f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/LocalizationServiceTests.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; @@ -6,6 +9,7 @@ using System.Threading; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Persistence; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -34,15 +38,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private ILocalizationService LocalizationService => GetRequiredService(); [SetUp] - public void SetUp() - { - CreateTestData(); - } + public void SetUp() => CreateTestData(); [Test] public void Can_Get_Root_Dictionary_Items() { - var rootItems = LocalizationService.GetRootDictionaryItems(); + IEnumerable rootItems = LocalizationService.GetRootDictionaryItems(); Assert.NotNull(rootItems); Assert.IsTrue(rootItems.Any()); @@ -51,14 +52,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Determint_If_DictionaryItem_Exists() { - var exists = LocalizationService.DictionaryItemExists("Parent"); + bool exists = LocalizationService.DictionaryItemExists("Parent"); Assert.IsTrue(exists); } [Test] public void Can_Get_All_Languages() { - var languages = LocalizationService.GetAllLanguages(); + IEnumerable languages = LocalizationService.GetAllLanguages(); Assert.NotNull(languages); Assert.IsTrue(languages.Any()); Assert.That(languages.Count(), Is.EqualTo(3)); @@ -67,41 +68,41 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Dictionary_Item_By_Int_Id() { - var parentItem = LocalizationService.GetDictionaryItemById(_parentItemIntId); + IDictionaryItem parentItem = LocalizationService.GetDictionaryItemById(_parentItemIntId); Assert.NotNull(parentItem); - var childItem = LocalizationService.GetDictionaryItemById(_childItemIntId); + IDictionaryItem childItem = LocalizationService.GetDictionaryItemById(_childItemIntId); Assert.NotNull(childItem); } [Test] public void Can_Get_Dictionary_Item_By_Guid_Id() { - var parentItem = LocalizationService.GetDictionaryItemById(_parentItemGuidId); + IDictionaryItem parentItem = LocalizationService.GetDictionaryItemById(_parentItemGuidId); Assert.NotNull(parentItem); - var childItem = LocalizationService.GetDictionaryItemById(_childItemGuidId); + IDictionaryItem childItem = LocalizationService.GetDictionaryItemById(_childItemGuidId); Assert.NotNull(childItem); } [Test] public void Can_Get_Dictionary_Item_By_Key() { - var parentItem = LocalizationService.GetDictionaryItemByKey("Parent"); + IDictionaryItem parentItem = LocalizationService.GetDictionaryItemByKey("Parent"); Assert.NotNull(parentItem); - var childItem = LocalizationService.GetDictionaryItemByKey("Child"); + IDictionaryItem childItem = LocalizationService.GetDictionaryItemByKey("Child"); Assert.NotNull(childItem); } [Test] public void Can_Get_Dictionary_Item_Children() { - var item = LocalizationService.GetDictionaryItemChildren(_parentItemGuidId); + IEnumerable item = LocalizationService.GetDictionaryItemChildren(_parentItemGuidId); Assert.NotNull(item); Assert.That(item.Count(), Is.EqualTo(1)); - foreach (var dictionaryItem in item) + foreach (IDictionaryItem dictionaryItem in item) { Assert.AreEqual(_parentItemGuidId, dictionaryItem.ParentId); Assert.IsFalse(string.IsNullOrEmpty(dictionaryItem.ItemKey)); @@ -111,15 +112,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Dictionary_Item_Descendants() { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { - var en = LocalizationService.GetLanguageById(_englishLangId); - var dk = LocalizationService.GetLanguageById(_danishLangId); + ILanguage en = LocalizationService.GetLanguageById(_englishLangId); + ILanguage dk = LocalizationService.GetLanguageById(_danishLangId); - var currParentId = _childItemGuidId; - for (var i = 0; i < 25; i++) + Guid currParentId = _childItemGuidId; + for (int i = 0; i < 25; i++) { - //Create 2 per level + // Create 2 per level var desc1 = new DictionaryItem(currParentId, "D1" + i) { Translations = new List @@ -145,12 +146,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; scope.Database.AsUmbracoDatabase().EnableSqlCount = true; - var items = LocalizationService.GetDictionaryItemDescendants(_parentItemGuidId).ToArray(); + IDictionaryItem[] items = LocalizationService.GetDictionaryItemDescendants(_parentItemGuidId).ToArray(); Debug.WriteLine("SQL CALLS: " + scope.Database.AsUmbracoDatabase().SqlCount); Assert.AreEqual(51, items.Length); - //there's a call or two to get languages, so apart from that there should only be one call per level + + // There's a call or two to get languages, so apart from that there should only be one call per level. Assert.Less(scope.Database.AsUmbracoDatabase().SqlCount, 30); } } @@ -158,8 +160,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_GetLanguageById() { - var danish = LocalizationService.GetLanguageById(_danishLangId); - var english = LocalizationService.GetLanguageById(_englishLangId); + ILanguage danish = LocalizationService.GetLanguageById(_danishLangId); + ILanguage english = LocalizationService.GetLanguageById(_englishLangId); Assert.NotNull(danish); Assert.NotNull(english); } @@ -167,8 +169,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_GetLanguageByIsoCode() { - var danish = LocalizationService.GetLanguageByIsoCode("da-DK"); - var english = LocalizationService.GetLanguageByIsoCode("en-GB"); + ILanguage danish = LocalizationService.GetLanguageByIsoCode("da-DK"); + ILanguage english = LocalizationService.GetLanguageByIsoCode("en-GB"); Assert.NotNull(danish); Assert.NotNull(english); } @@ -176,54 +178,54 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Does_Not_Fail_When_Language_Doesnt_Exist() { - var language = LocalizationService.GetLanguageByIsoCode("sv-SE"); + ILanguage language = LocalizationService.GetLanguageByIsoCode("sv-SE"); Assert.Null(language); } [Test] public void Does_Not_Fail_When_DictionaryItem_Doesnt_Exist() { - var item = LocalizationService.GetDictionaryItemByKey("RandomKey"); + IDictionaryItem item = LocalizationService.GetDictionaryItemByKey("RandomKey"); Assert.Null(item); } [Test] public void Can_Delete_Language() { - var languageNbNo = new LanguageBuilder() + ILanguage languageNbNo = new LanguageBuilder() .WithCultureInfo("nb-NO") .Build(); LocalizationService.Save(languageNbNo, 0); Assert.That(languageNbNo.HasIdentity, Is.True); - var languageId = languageNbNo.Id; + int languageId = languageNbNo.Id; LocalizationService.Delete(languageNbNo); - var language = LocalizationService.GetLanguageById(languageId); + ILanguage language = LocalizationService.GetLanguageById(languageId); Assert.Null(language); } [Test] public void Can_Delete_Language_Used_As_Fallback() { - var languageDaDk = LocalizationService.GetLanguageByIsoCode("da-DK"); - var languageNbNo = new LanguageBuilder() + ILanguage languageDaDk = LocalizationService.GetLanguageByIsoCode("da-DK"); + ILanguage languageNbNo = new LanguageBuilder() .WithCultureInfo("nb-NO") .WithFallbackLanguageId(languageDaDk.Id) .Build(); LocalizationService.Save(languageNbNo, 0); - var languageId = languageDaDk.Id; + int languageId = languageDaDk.Id; LocalizationService.Delete(languageDaDk); - var language = LocalizationService.GetLanguageById(languageId); + ILanguage language = LocalizationService.GetLanguageById(languageId); Assert.Null(language); } [Test] public void Can_Create_DictionaryItem_At_Root() { - var english = LocalizationService.GetLanguageByIsoCode("en-US"); + ILanguage english = LocalizationService.GetLanguageByIsoCode("en-US"); var item = (IDictionaryItem)new DictionaryItem("Testing123") { @@ -234,7 +236,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services }; LocalizationService.Save(item); - //re-get + // re-get item = LocalizationService.GetDictionaryItemById(item.Id); Assert.Greater(item.Id, 0); @@ -247,10 +249,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Create_DictionaryItem_At_Root_With_Identity() { - var item = LocalizationService.CreateDictionaryItemWithIdentity( + IDictionaryItem item = LocalizationService.CreateDictionaryItemWithIdentity( "Testing12345", null, "Hellooooo"); - //re-get + // re-get item = LocalizationService.GetDictionaryItemById(item.Id); Assert.IsNotNull(item); @@ -258,9 +260,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(item.HasIdentity); Assert.IsFalse(item.ParentId.HasValue); Assert.AreEqual("Testing12345", item.ItemKey); - var allLangs = LocalizationService.GetAllLanguages(); + IEnumerable allLangs = LocalizationService.GetAllLanguages(); Assert.Greater(allLangs.Count(), 0); - foreach (var language in allLangs) + foreach (ILanguage language in allLangs) { Assert.AreEqual("Hellooooo", item.Translations.Single(x => x.Language.CultureName == language.CultureName).Value); } @@ -269,12 +271,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Add_Translation_To_Existing_Dictionary_Item() { - var english = LocalizationService.GetLanguageByIsoCode("en-US"); + ILanguage english = LocalizationService.GetLanguageByIsoCode("en-US"); - var item = (IDictionaryItem) new DictionaryItem("Testing123"); + var item = (IDictionaryItem)new DictionaryItem("Testing123"); LocalizationService.Save(item); - //re-get + // re-get item = LocalizationService.GetDictionaryItemById(item.Id); item.Translations = new List @@ -285,7 +287,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(item); Assert.AreEqual(1, item.Translations.Count()); - foreach (var translation in item.Translations) + foreach (IDictionaryTranslation translation in item.Translations) { Assert.AreEqual("Hello world", translation.Value); } @@ -299,7 +301,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services LocalizationService.Save(item); - //re-get + // re-get item = LocalizationService.GetDictionaryItemById(item.Id); Assert.AreEqual(2, item.Translations.Count()); @@ -310,30 +312,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Delete_DictionaryItem() { - var item = LocalizationService.GetDictionaryItemByKey("Child"); + IDictionaryItem item = LocalizationService.GetDictionaryItemByKey("Child"); Assert.NotNull(item); LocalizationService.Delete(item); - var deletedItem = LocalizationService.GetDictionaryItemByKey("Child"); + IDictionaryItem deletedItem = LocalizationService.GetDictionaryItemByKey("Child"); Assert.Null(deletedItem); } [Test] public void Can_Update_Existing_DictionaryItem() { - var item = LocalizationService.GetDictionaryItemByKey("Child"); - foreach (var translation in item.Translations) + IDictionaryItem item = LocalizationService.GetDictionaryItemByKey("Child"); + foreach (IDictionaryTranslation translation in item.Translations) { - translation.Value = translation.Value + "UPDATED"; + translation.Value += "UPDATED"; } LocalizationService.Save(item); - var updatedItem = LocalizationService.GetDictionaryItemByKey("Child"); + IDictionaryItem updatedItem = LocalizationService.GetDictionaryItemByKey("Child"); Assert.NotNull(updatedItem); - foreach (var translation in updatedItem.Translations) + foreach (IDictionaryTranslation translation in updatedItem.Translations) { Assert.That(translation.Value.EndsWith("UPDATED"), Is.True); } @@ -343,7 +345,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Find_BaseData_Language() { // Act - var languages = LocalizationService.GetAllLanguages(); + IEnumerable languages = LocalizationService.GetAllLanguages(); // Assert Assert.That(3, Is.EqualTo(languages.Count())); @@ -353,14 +355,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Save_Language_And_GetLanguageByIsoCode() { // Arrange - var isoCode = "en-AU"; - var languageEnAu = new LanguageBuilder() + string isoCode = "en-AU"; + ILanguage languageEnAu = new LanguageBuilder() .WithCultureInfo(isoCode) .Build(); // Act LocalizationService.Save(languageEnAu); - var result = LocalizationService.GetLanguageByIsoCode(isoCode); + ILanguage result = LocalizationService.GetLanguageByIsoCode(isoCode); // Assert Assert.NotNull(result); @@ -370,13 +372,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Save_Language_And_GetLanguageById() { // Arrange - var languageEnAu = new LanguageBuilder() + ILanguage languageEnAu = new LanguageBuilder() .WithCultureInfo("en-AU") .Build(); // Act LocalizationService.Save(languageEnAu); - var result = LocalizationService.GetLanguageById(languageEnAu.Id); + ILanguage result = LocalizationService.GetLanguageById(languageEnAu.Id); // Assert Assert.NotNull(result); @@ -385,23 +387,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Set_Default_Language() { - var languageEnAu = new LanguageBuilder() + ILanguage languageEnAu = new LanguageBuilder() .WithCultureInfo("en-AU") .WithIsDefault(true) .Build(); LocalizationService.Save(languageEnAu); - var result = LocalizationService.GetLanguageById(languageEnAu.Id); + ILanguage result = LocalizationService.GetLanguageById(languageEnAu.Id); Assert.IsTrue(result.IsDefault); - var languageEnNz = new LanguageBuilder() + ILanguage languageEnNz = new LanguageBuilder() .WithCultureInfo("en-NZ") .WithIsDefault(true) .Build(); LocalizationService.Save(languageEnNz); - var result2 = LocalizationService.GetLanguageById(languageEnNz.Id); + ILanguage result2 = LocalizationService.GetLanguageById(languageEnNz.Id); - //re-get + // re-get result = LocalizationService.GetLanguageById(languageEnAu.Id); Assert.IsTrue(result2.IsDefault); @@ -411,15 +413,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Deleted_Language_Should_Not_Exist() { - var isoCode = "en-AU"; - var languageEnAu = new LanguageBuilder() + string isoCode = "en-AU"; + ILanguage languageEnAu = new LanguageBuilder() .WithCultureInfo(isoCode) .Build(); LocalizationService.Save(languageEnAu); // Act LocalizationService.Delete(languageEnAu); - var result = LocalizationService.GetLanguageByIsoCode(isoCode); + ILanguage result = LocalizationService.GetLanguageByIsoCode(isoCode); // Assert Assert.Null(result); @@ -427,10 +429,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void CreateTestData() { - var languageDaDk = new LanguageBuilder() + ILanguage languageDaDk = new LanguageBuilder() .WithCultureInfo("da-DK") .Build(); - var languageEnGb = new LanguageBuilder() + ILanguage languageEnGb = new LanguageBuilder() .WithCultureInfo("en-GB") .Build(); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs index d2c1e3b7fc..df89e32f96 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.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.Threading; using Microsoft.Extensions.Logging; @@ -26,10 +30,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [SetUp] public void SetupTest() { - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) + IScopeProvider scopeProvider = ScopeProvider; + using (IScope scope = scopeProvider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) scopeProvider, AppCaches.Disabled, Mock.Of>(), ShortStringHelper); + var repository = new MacroRepository((IScopeAccessor)scopeProvider, AppCaches.Disabled, Mock.Of>(), ShortStringHelper); repository.Save(new Macro(ShortStringHelper, "test1", "Test1", "~/views/macropartials/test1.cshtml")); repository.Save(new Macro(ShortStringHelper, "test2", "Test2", "~/views/macropartials/test2.cshtml")); @@ -42,7 +46,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_By_Alias() { // Act - var macro = MacroService.GetByAlias("test1"); + IMacro macro = MacroService.GetByAlias("test1"); // Assert Assert.IsNotNull(macro); @@ -53,7 +57,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Get_All() { // Act - var result = MacroService.GetAll(); + IEnumerable result = MacroService.GetAll(); // Assert Assert.AreEqual(3, result.Count()); @@ -63,14 +67,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Create() { // Act - var macro = CreateMacro(); + IMacro macro = CreateMacro(); MacroService.Save(macro); // Assert Assert.IsTrue(macro.HasIdentity); Assert.Greater(macro.Id, 0); Assert.AreNotEqual(Guid.Empty, macro.Key); - var result = MacroService.GetById(macro.Id); + IMacro result = MacroService.GetById(macro.Id); Assert.AreEqual("test", result.Alias); Assert.AreEqual("Test", result.Name); Assert.AreEqual("~/Views/MacroPartials/Test.cshtml", result.MacroSource); @@ -94,7 +98,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MacroService.Delete(macro); // Assert - var result = MacroService.GetById(macro.Id); + IMacro result = MacroService.GetById(macro.Id); Assert.IsNull(result); result = MacroService.GetById(macro.Key); @@ -105,11 +109,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Update() { // Arrange - var macro = CreateMacro(); + IMacro macro = CreateMacro(); MacroService.Save(macro); // Act - var currKey = macro.Key; + Guid currKey = macro.Key; macro.Name = "New name"; macro.Alias = "NewAlias"; MacroService.Save(macro); @@ -120,21 +124,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual("New name", macro.Name); Assert.AreEqual("NewAlias", macro.Alias); Assert.AreEqual(currKey, macro.Key); - } [Test] public void Can_Update_Property() { // Arrange - var macro = CreateMacro(); + IMacro macro = CreateMacro(); macro.Properties.Add(new MacroProperty("blah", "Blah", 0, "blah")); MacroService.Save(macro); Assert.AreNotEqual(Guid.Empty, macro.Properties[0].Key); // Act - var currPropKey = macro.Properties[0].Key; + Guid currPropKey = macro.Properties[0].Key; macro.Properties[0].Alias = "new Alias"; macro.Properties[0].Name = "new Name"; macro.Properties[0].SortOrder = 1; @@ -157,14 +160,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Update_Remove_Property() { // Arrange - var macro = CreateMacro(); + IMacro macro = CreateMacro(); macro.Properties.Add(new MacroProperty("blah1", "Blah1", 0, "blah1")); macro.Properties.Add(new MacroProperty("blah2", "Blah2", 1, "blah2")); macro.Properties.Add(new MacroProperty("blah3", "Blah3", 2, "blah3")); MacroService.Save(macro); - var lastKey = macro.Properties[0].Key; - for (var i = 1; i < macro.Properties.Count; i++) + Guid lastKey = macro.Properties[0].Key; + for (int i = 1; i < macro.Properties.Count; i++) { Assert.AreNotEqual(Guid.Empty, macro.Properties[i].Key); Assert.AreNotEqual(lastKey, macro.Properties[i].Key); @@ -199,7 +202,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Add_And_Remove_Properties() { - var macro = CreateMacro(); + IMacro macro = CreateMacro(); // Adds some properties macro.Properties.Add(new MacroProperty("blah1", "Blah1", 0, "blah1")); @@ -208,11 +211,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services macro.Properties.Add(new MacroProperty("blah4", "Blah4", 0, "blah4")); MacroService.Save(macro); - var result1 = MacroService.GetById(macro.Id); + IMacro result1 = MacroService.GetById(macro.Id); Assert.AreEqual(4, result1.Properties.Values.Count()); // Simulate clearing the sections - foreach (var s in result1.Properties.Values.ToArray()) + foreach (IMacroProperty s in result1.Properties.Values.ToArray()) { result1.Properties.Remove(s.Alias); } @@ -225,27 +228,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert result1 = MacroService.GetById(result1.Id); Assert.AreEqual(2, result1.Properties.Values.Count()); - } [Test] public void Cannot_Save_Macro_With_Empty_Name() { // Arrange - var macro = CreateMacro(name: string.Empty); + IMacro macro = CreateMacro(name: string.Empty); // Act & Assert Assert.Throws(() => MacroService.Save(macro)); } - private static IMacro CreateMacro(string name = "Test") - { - return new MacroBuilder() + private static IMacro CreateMacro(string name = "Test") => + new MacroBuilder() .WithAlias("test") .WithName(name) .WithSource("~/Views/MacroPartials/Test.cshtml") .WithCacheDuration(1234) .Build(); - } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaServiceTests.cs index ca3605217e..3abbc0c38c 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaServiceTests.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.Reflection; using System.Threading; @@ -6,6 +10,7 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Events; using Umbraco.Core.Models; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; using Umbraco.Tests.Common.Builders; @@ -21,8 +26,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class MediaServiceTests : UmbracoIntegrationTest { private IMediaService MediaService => GetRequiredService(); - private IMediaTypeService MediaTypeService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); [Test] public void Can_Update_Media_Property_Values() @@ -51,22 +56,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services /// /// Used to list out all ambiguous events that will require dispatching with a name /// - [Test, Explicit] + [Test] + [Explicit] public void List_Ambiguous_Events() { - var events = MediaService.GetType().GetEvents(BindingFlags.Static | BindingFlags.Public); - var typedEventHandler = typeof(TypedEventHandler<,>); - foreach (var e in events) + EventInfo[] events = MediaService.GetType().GetEvents(BindingFlags.Static | BindingFlags.Public); + Type typedEventHandler = typeof(TypedEventHandler<,>); + foreach (EventInfo e in events) { - //only continue if this is a TypedEventHandler - if (!e.EventHandlerType.IsGenericType) continue; - var typeDef = e.EventHandlerType.GetGenericTypeDefinition(); - if (typedEventHandler != typeDef) continue; + // only continue if this is a TypedEventHandler + if (!e.EventHandlerType.IsGenericType) + { + continue; + } - //get the event arg type - var eventArgType = e.EventHandlerType.GenericTypeArguments[1]; + Type typeDef = e.EventHandlerType.GetGenericTypeDefinition(); + if (typedEventHandler != typeDef) + { + continue; + } - var found = EventNameExtractor.FindEvent(typeof(MediaService), eventArgType, EventNameExtractor.MatchIngNames); + // get the event arg type + Type eventArgType = e.EventHandlerType.GenericTypeArguments[1]; + + Attempt found = EventNameExtractor.FindEvent(typeof(MediaService), eventArgType, EventNameExtractor.MatchIngNames); if (!found.Success && found.Result.Error == EventNameExtractorError.Ambiguous) { Console.WriteLine($"Ambiguous event, source: {typeof(MediaService)}, args: {eventArgType}"); @@ -77,31 +90,38 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_Paged_Children_With_Media_Type_Filter() { - var mediaType1 = MediaTypeBuilder.CreateImageMediaType("Image2"); + MediaType mediaType1 = MediaTypeBuilder.CreateImageMediaType("Image2"); MediaTypeService.Save(mediaType1); - var mediaType2 = MediaTypeBuilder.CreateImageMediaType("Image3"); + MediaType mediaType2 = MediaTypeBuilder.CreateImageMediaType("Image3"); MediaTypeService.Save(mediaType2); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var m1 = MediaBuilder.CreateMediaImage(mediaType1, -1); + Media m1 = MediaBuilder.CreateMediaImage(mediaType1, -1); MediaService.Save(m1); - var m2 = MediaBuilder.CreateMediaImage(mediaType2, -1); + Media m2 = MediaBuilder.CreateMediaImage(mediaType2, -1); MediaService.Save(m2); } - long total; - var provider = ScopeProvider; + IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { - var result = MediaService.GetPagedChildren(-1, 0, 11, out total, + IEnumerable result = MediaService.GetPagedChildren( + -1, + 0, + 11, + out long total, provider.SqlContext.Query() .Where(x => new[] { mediaType1.Id, mediaType2.Id }.Contains(x.ContentTypeId)), Ordering.By("SortOrder", Direction.Ascending)); Assert.AreEqual(11, result.Count()); Assert.AreEqual(20, total); - result = MediaService.GetPagedChildren(-1, 1, 11, out total, + result = MediaService.GetPagedChildren( + -1, + 1, + 11, + out total, provider.SqlContext.Query() .Where(x => new[] { mediaType1.Id, mediaType2.Id }.Contains(x.ContentTypeId)), Ordering.By("SortOrder", Direction.Ascending)); @@ -114,8 +134,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Media() { // Arrange - var mediaItems = CreateTrashedTestMedia(); - var media = MediaService.GetById(mediaItems.Item3.Id); + Tuple mediaItems = CreateTrashedTestMedia(); + IMedia media = MediaService.GetById(mediaItems.Item3.Id); // Act MediaService.Move(media, mediaItems.Item2.Id); @@ -129,8 +149,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Media_To_RecycleBin() { // Arrange - var mediaItems = CreateTrashedTestMedia(); - var media = MediaService.GetById(mediaItems.Item1.Id); + Tuple mediaItems = CreateTrashedTestMedia(); + IMedia media = MediaService.GetById(mediaItems.Item1.Id); // Act MediaService.MoveToRecycleBin(media); @@ -144,12 +164,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Move_Media_From_RecycleBin() { // Arrange - var mediaItems = CreateTrashedTestMedia(); - var media = MediaService.GetById(mediaItems.Item4.Id); + Tuple mediaItems = CreateTrashedTestMedia(); + IMedia media = MediaService.GetById(mediaItems.Item4.Id); // Act - moving out of recycle bin MediaService.Move(media, mediaItems.Item1.Id); - var mediaChild = MediaService.GetById(mediaItems.Item5.Id); + IMedia mediaChild = MediaService.GetById(mediaItems.Item5.Id); // Assert Assert.That(media.ParentId, Is.EqualTo(mediaItems.Item1.Id)); @@ -162,13 +182,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_Media_With_Empty_Name() { // Arrange - var mediaType = MediaTypeBuilder.CreateVideoMediaType(); + MediaType mediaType = MediaTypeBuilder.CreateVideoMediaType(); MediaTypeService.Save(mediaType); - var media = MediaService.CreateMedia(string.Empty, -1, "video"); + IMedia media = MediaService.CreateMedia(string.Empty, -1, "video"); // Act & Assert Assert.Throws(() => MediaService.Save(media)); } + /* [Test] public void Ensure_Content_Xml_Created() @@ -188,14 +209,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Media_By_Path() { - var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); MediaTypeService.Save(mediaType); - var media = MediaBuilder.CreateMediaImage(mediaType, -1); + Media media = MediaBuilder.CreateMediaImage(mediaType, -1); MediaService.Save(media); - var mediaPath = "/media/test-image.png"; - var resolvedMedia = MediaService.GetMediaByPath(mediaPath); + string mediaPath = "/media/test-image.png"; + IMedia resolvedMedia = MediaService.GetMediaByPath(mediaPath); Assert.IsNotNull(resolvedMedia); Assert.That(resolvedMedia.GetValue(Constants.Conventions.Media.File).ToString() == mediaPath); @@ -204,14 +225,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Media_With_Crop_By_Path() { - var mediaType = MediaTypeBuilder.CreateImageMediaTypeWithCrop("Image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaTypeWithCrop("Image2"); MediaTypeService.Save(mediaType); - var media = MediaBuilder.CreateMediaImageWithCrop(mediaType, -1); + Media media = MediaBuilder.CreateMediaImageWithCrop(mediaType, -1); MediaService.Save(media); - var mediaPath = "/media/test-image.png"; - var resolvedMedia = MediaService.GetMediaByPath(mediaPath); + string mediaPath = "/media/test-image.png"; + IMedia resolvedMedia = MediaService.GetMediaByPath(mediaPath); Assert.IsNotNull(resolvedMedia); Assert.That(resolvedMedia.GetValue(Constants.Conventions.Media.File).ToString().Contains(mediaPath)); @@ -220,18 +241,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Paged_Children() { - var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); MediaTypeService.Save(mediaType); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var c1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media c1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaService.Save(c1); } - var service = MediaService; + IMediaService service = MediaService; - long total; - var entities = service.GetPagedChildren(-1, 0, 6, out total).ToArray(); + IMedia[] entities = service.GetPagedChildren(-1, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = service.GetPagedChildren(-1, 1, 6, out total).ToArray(); @@ -242,37 +262,37 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Paged_Children_Dont_Get_Descendants() { - var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); + MediaType mediaType = MediaTypeBuilder.CreateImageMediaType("Image2"); MediaTypeService.Save(mediaType); - // only add 9 as we also add a folder with children - for (var i = 0; i < 9; i++) + + // Only add 9 as we also add a folder with children. + for (int i = 0; i < 9; i++) { - var m1 = MediaBuilder.CreateMediaImage(mediaType, -1); + Media m1 = MediaBuilder.CreateMediaImage(mediaType, -1); MediaService.Save(m1); } - var mediaTypeForFolder = MediaTypeBuilder.CreateImageMediaType("Folder2"); + MediaType mediaTypeForFolder = MediaTypeBuilder.CreateImageMediaType("Folder2"); MediaTypeService.Save(mediaTypeForFolder); - var mediaFolder = MediaBuilder.CreateMediaFolder(mediaTypeForFolder, -1); + Media mediaFolder = MediaBuilder.CreateMediaFolder(mediaTypeForFolder, -1); MediaService.Save(mediaFolder); - for (var i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) { - var m1 = MediaBuilder.CreateMediaImage(mediaType, mediaFolder.Id); + Media m1 = MediaBuilder.CreateMediaImage(mediaType, mediaFolder.Id); MediaService.Save(m1); } - var service = MediaService; + IMediaService service = MediaService; - long total; - // children in root including the folder - not the descendants in the folder - var entities = service.GetPagedChildren(-1, 0, 6, out total).ToArray(); + // Children in root including the folder - not the descendants in the folder. + IMedia[] entities = service.GetPagedChildren(-1, 0, 6, out long total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = service.GetPagedChildren(-1, 1, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); - // children in folder + // Children in folder. entities = service.GetPagedChildren(mediaFolder.Id, 0, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); @@ -283,27 +303,27 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private Tuple CreateTrashedTestMedia() { - //Create and Save folder-Media -> 1050 - var folderMediaType = MediaTypeService.Get(1031); - var folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); + // Create and Save folder-Media -> 1050 + IMediaType folderMediaType = MediaTypeService.Get(1031); + Media folder = MediaBuilder.CreateMediaFolder(folderMediaType, -1); MediaService.Save(folder); - //Create and Save folder-Media -> 1051 - var folder2 = MediaBuilder.CreateMediaFolder(folderMediaType, -1); + // Create and Save folder-Media -> 1051 + Media folder2 = MediaBuilder.CreateMediaFolder(folderMediaType, -1); MediaService.Save(folder2); - //Create and Save image-Media -> 1052 - var imageMediaType = MediaTypeService.Get(1032); - var image = MediaBuilder.CreateMediaImage(imageMediaType, 1050); + // Create and Save image-Media -> 1052 + IMediaType imageMediaType = MediaTypeService.Get(1032); + Media image = MediaBuilder.CreateMediaImage(imageMediaType, 1050); MediaService.Save(image); - //Create and Save folder-Media that is trashed -> 1053 - var folderTrashed = MediaBuilder.CreateMediaFolder(folderMediaType, -21); + // Create and Save folder-Media that is trashed -> 1053 + Media folderTrashed = MediaBuilder.CreateMediaFolder(folderMediaType, -21); folderTrashed.Trashed = true; MediaService.Save(folderTrashed); - //Create and Save image-Media child of folderTrashed -> 1054 - var imageTrashed = MediaBuilder.CreateMediaImage(imageMediaType, folderTrashed.Id); + // Create and Save image-Media child of folderTrashed -> 1054 + Media imageTrashed = MediaBuilder.CreateMediaImage(imageMediaType, folderTrashed.Id); imageTrashed.Trashed = true; MediaService.Save(imageTrashed); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs index 8a38bdc6eb..2a1b5c3101 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MediaTypeServiceTests.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; @@ -19,27 +22,28 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class MediaTypeServiceTests : UmbracoIntegrationTest { private MediaService MediaService => (MediaService)GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); [Test] public void Get_With_Missing_Guid() { // Arrange - //Act - var result = MediaTypeService.Get(Guid.NewGuid()); + // Act + IMediaType result = MediaTypeService.Get(Guid.NewGuid()); - //Assert + // Assert Assert.IsNull(result); } [Test] public void Empty_Description_Is_Always_Null_After_Saving_Media_Type() { - var mediaType = MediaTypeBuilder.CreateSimpleMediaType("mediaType", "Media Type"); + MediaType mediaType = MediaTypeBuilder.CreateSimpleMediaType("mediaType", "Media Type"); mediaType.Description = null; MediaTypeService.Save(mediaType); - var mediaType2 = MediaTypeBuilder.CreateSimpleMediaType("mediaType2", "Media Type 2"); + MediaType mediaType2 = MediaTypeBuilder.CreateSimpleMediaType("mediaType2", "Media Type 2"); mediaType2.Description = string.Empty; MediaTypeService.Save(mediaType2); @@ -57,17 +61,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMediaType contentType3 = MediaTypeBuilder.CreateSimpleMediaType("test3", "Test3"); MediaTypeService.Save(contentType3); - var contentTypes = new[] { contentType1, contentType2, contentType3 }; - var parentId = -1; + IMediaType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; + int parentId = -1; var ids = new List(); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - for (var index = 0; index < contentTypes.Length; index++) + for (int index = 0; index < contentTypes.Length; index++) { - var contentType = contentTypes[index]; - var contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); + IMediaType contentType = contentTypes[index]; + Media contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); MediaService.Save(contentItem); parentId = contentItem.Id; @@ -75,13 +79,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } } - //delete the first content type, all other content of different content types should be in the recycle bin + // delete the first content type, all other content of different content types should be in the recycle bin MediaTypeService.Delete(contentTypes[0]); - var found = MediaService.GetByIds(ids); + IEnumerable found = MediaService.GetByIds(ids); Assert.AreEqual(4, found.Count()); - foreach (var content in found) + foreach (IMedia content in found) { Assert.IsTrue(content.Trashed); } @@ -101,17 +105,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMediaType contentType3 = MediaTypeBuilder.CreateSimpleMediaType("test3", "Test3"); MediaTypeService.Save(contentType3); - var contentTypes = new[] { contentType1, contentType2, contentType3 }; - var parentId = -1; + IMediaType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; + int parentId = -1; var ids = new List(); - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - for (var index = 0; index < contentTypes.Length; index++) + for (int index = 0; index < contentTypes.Length; index++) { - var contentType = contentTypes[index]; - var contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); + IMediaType contentType = contentTypes[index]; + Media contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); MediaService.Save(contentItem); parentId = contentItem.Id; @@ -119,7 +123,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } } - foreach (var contentType in contentTypes.Reverse()) + foreach (IMediaType contentType in contentTypes.Reverse()) { MediaTypeService.Delete(contentType); } @@ -132,12 +136,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void MediaServiceOnTrashed(IMediaService sender, MoveEventArgs e) { - foreach (var item in e.MoveInfoCollection) + foreach (MoveEventInfo item in e.MoveInfoCollection) { - //if this item doesn't exist then Fail! - var exists = MediaService.GetById(item.Entity.Id); + // if this item doesn't exist then Fail! + IMedia exists = MediaService.GetById(item.Entity.Id); if (exists == null) + { Assert.Fail("The item doesn't exist"); + } } } @@ -149,7 +155,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MediaTypeService.Save(mediaType); // Act - var sut = mediaType.DeepCloneWithResetIdentities("Image2_2"); + IMediaType sut = mediaType.DeepCloneWithResetIdentities("Image2_2"); Assert.IsNotNull(sut); MediaTypeService.Save(sut); @@ -170,15 +176,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Copy_MediaType_To_New_Parent_By_Performing_Clone() { // Arrange - var parentMediaType1 = MediaTypeBuilder.CreateSimpleMediaType("parent1", "Parent1"); + MediaType parentMediaType1 = MediaTypeBuilder.CreateSimpleMediaType("parent1", "Parent1"); MediaTypeService.Save(parentMediaType1); - var parentMediaType2 = MediaTypeBuilder.CreateSimpleMediaType("parent2", "Parent2", null, true); + MediaType parentMediaType2 = MediaTypeBuilder.CreateSimpleMediaType("parent2", "Parent2", null, true); MediaTypeService.Save(parentMediaType2); var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2") as IMediaType; MediaTypeService.Save(mediaType); // Act - var clone = mediaType.DeepCloneWithResetIdentities("newcategory"); + IMediaType clone = mediaType.DeepCloneWithResetIdentities("newcategory"); Assert.IsNotNull(clone); clone.RemoveContentType("parent1"); clone.AddContentType(parentMediaType2); @@ -188,8 +194,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert Assert.That(clone.HasIdentity, Is.True); - var clonedMediaType = MediaTypeService.Get(clone.Id); - var originalMediaType = MediaTypeService.Get(mediaType.Id); + IMediaType clonedMediaType = MediaTypeService.Get(clone.Id); + IMediaType originalMediaType = MediaTypeService.Get(mediaType.Id); Assert.That(clonedMediaType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedMediaType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberGroupServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberGroupServiceTests.cs index e0119bccb4..5abd76aaf8 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberGroupServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberGroupServiceTests.cs @@ -1,6 +1,10 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Threading; using NUnit.Framework; +using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Common.Builders.Extensions; @@ -19,10 +23,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services /// /// Used to list out all ambiguous events that will require dispatching with a name /// - [Test, Explicit] + [Test] + [Explicit] public void List_Ambiguous_Events() { - var memberGroup = new MemberGroupBuilder() + MemberGroup memberGroup = new MemberGroupBuilder() .WithName(string.Empty) .Build(); Assert.Throws(() => MemberGroupService.Save(memberGroup)); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs index a22810ff22..5e195aa077 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs @@ -1,7 +1,11 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.Linq; using System.Threading; +using NPoco; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; @@ -12,6 +16,7 @@ using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Common; using Umbraco.Tests.Common.Builders; @@ -28,14 +33,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class MemberServiceTests : UmbracoIntegrationTest { private IMemberTypeService MemberTypeService => GetRequiredService(); + private IMemberService MemberService => GetRequiredService(); [SetUp] - public void SetupTest() - { + public void SetupTest() => + // TODO: remove this once IPublishedSnapShotService has been implemented with nucache. global::Umbraco.Core.Services.Implement.MemberTypeService.ClearScopeEvents(); - } [Test] public void Can_Update_Member_Property_Values() @@ -64,11 +69,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_By_Username() { - var memberType = MemberTypeService.Get("member"); + IMemberType memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true); MemberService.Save(member); - var member2 = MemberService.GetByUsername(member.Username); + IMember member2 = MemberService.GetByUsername(member.Username); Assert.IsNotNull(member2); Assert.AreEqual(member.Email, member2.Email); @@ -77,8 +82,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Set_Last_Login_Date() { - var now = DateTime.Now; - var memberType = MemberTypeService.Get("member"); + DateTime now = DateTime.Now; + IMemberType memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true) { LastLoginDate = now, @@ -86,10 +91,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services }; MemberService.Save(member); - var newDate = now.AddDays(10); + DateTime newDate = now.AddDays(10); MemberService.SetLastLogin(member.Username, newDate); - //re-get + // re-get member = MemberService.GetById(member.Id); Assert.That(member.LastLoginDate, Is.EqualTo(newDate).Within(1).Seconds); @@ -99,7 +104,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Create_Member_With_Properties() { - var memberType = MemberTypeService.Get("member"); + IMemberType memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true); MemberService.Save(member); @@ -111,14 +116,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var publishedSnapshotAccessor = new TestPublishedSnapshotAccessor(); var variationContextAccessor = new TestVariationContextAccessor(); - var pmember = PublishedMember.Create(member, pmemberType, false, publishedSnapshotAccessor, variationContextAccessor, GetRequiredService()); + IPublishedContent pmember = PublishedMember.Create(member, pmemberType, false, publishedSnapshotAccessor, variationContextAccessor, GetRequiredService()); // contains the umbracoMember... properties created when installing, on the member type // contains the other properties, that PublishedContentType adds (BuiltinMemberProperties) // // TODO: see TODO in PublishedContentType, this list contains duplicates - - var aliases = new[] + string[] aliases = new[] { Constants.Conventions.Member.Comments, Constants.Conventions.Member.FailedPasswordAttempts, @@ -142,7 +146,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsTrue(properties.Select(x => x.Alias).ContainsAll(aliases)); - var email = properties[aliases.IndexOf(nameof(IMember.Email))]; + IPublishedProperty email = properties[aliases.IndexOf(nameof(IMember.Email))]; Assert.AreEqual("xemail", email.GetSourceValue()); } @@ -155,7 +159,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.Save(member); Assert.AreNotEqual(0, member.Id); - var foundMember = MemberService.GetById(member.Id); + IMember foundMember = MemberService.GetById(member.Id); Assert.IsNotNull(foundMember); Assert.AreEqual("test@test.com", foundMember.Email); } @@ -169,7 +173,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.Save(member); Assert.AreNotEqual(0, member.Id); - var foundMember = MemberService.GetById(member.Id); + IMember foundMember = MemberService.GetById(member.Id); Assert.IsNotNull(foundMember); Assert.AreEqual("test@test.marketing", foundMember.Email); } @@ -179,7 +183,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { MemberService.AddRole("MyTestRole"); - var found = MemberService.GetAllRoles(); + IEnumerable found = MemberService.GetAllRoles(); Assert.AreEqual(1, found.Count()); Assert.AreEqual("MyTestRole", found.Single()); @@ -191,7 +195,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole"); MemberService.AddRole("MyTestRole"); - var found = MemberService.GetAllRoles(); + IEnumerable found = MemberService.GetAllRoles(); Assert.AreEqual(1, found.Count()); Assert.AreEqual("MyTestRole", found.Single()); @@ -204,10 +208,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole2"); MemberService.AddRole("MyTestRole3"); - var found = MemberService.GetAllRoles(); + IEnumerable found = MemberService.GetAllRoles(); Assert.AreEqual(3, found.Count()); } + [Test] public void Can_Get_All_Roles_IDs() { @@ -215,10 +220,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole2"); MemberService.AddRole("MyTestRole3"); - var found = MemberService.GetAllRolesIds(); + IEnumerable found = MemberService.GetAllRolesIds(); Assert.AreEqual(3, found.Count()); } + [Test] public void Can_Get_All_Roles_By_Member_Id() { @@ -232,11 +238,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole3"); MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" }); - var memberRoles = MemberService.GetAllRoles(member.Id); + IEnumerable memberRoles = MemberService.GetAllRoles(member.Id); Assert.AreEqual(2, memberRoles.Count()); - } + [Test] public void Can_Get_All_Roles_Ids_By_Member_Id() { @@ -250,11 +256,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole3"); MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" }); - var memberRoles = MemberService.GetAllRolesIds(member.Id); + IEnumerable memberRoles = MemberService.GetAllRolesIds(member.Id); Assert.AreEqual(2, memberRoles.Count()); - } + [Test] public void Can_Get_All_Roles_By_Member_Username() { @@ -262,7 +268,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberTypeService.Save(memberType); IMember member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); MemberService.Save(member); - //need to test with '@' symbol in the lookup + + // need to test with '@' symbol in the lookup IMember member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); MemberService.Save(member2); @@ -271,10 +278,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AddRole("MyTestRole3"); MemberService.AssignRoles(new[] { member.Id, member2.Id }, new[] { "MyTestRole1", "MyTestRole2" }); - var memberRoles = MemberService.GetAllRoles("test"); + IEnumerable memberRoles = MemberService.GetAllRoles("test"); Assert.AreEqual(2, memberRoles.Count()); - var memberRoles2 = MemberService.GetAllRoles("test2@test.com"); + IEnumerable memberRoles2 = MemberService.GetAllRoles("test2@test.com"); Assert.AreEqual(2, memberRoles2.Count()); } @@ -285,7 +292,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.DeleteRole("MyTestRole1", false); - var memberRoles = MemberService.GetAllRoles(); + IEnumerable memberRoles = MemberService.GetAllRoles(); Assert.AreEqual(0, memberRoles.Count()); } @@ -309,7 +316,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { MemberService.AddRole("MyTestRole1"); int roleId; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { roleId = scope.Database.ExecuteScalar("SELECT id from umbracoNode where [text] = 'MyTestRole1'"); scope.Complete(); @@ -317,19 +324,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.Insert(new Member2MemberGroupDto { MemberGroup = roleId, Member = member1.Id }); scope.Database.Insert(new Member2MemberGroupDto { MemberGroup = roleId, Member = member2.Id }); scope.Complete(); } - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -342,7 +349,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Act & Assert Assert.Throws(() => MemberService.Save(member)); - } [TestCase("MyTestRole1", "test1", StringPropertyMatchType.StartsWith, 1)] @@ -355,16 +361,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); - var member3 = MemberBuilder.CreateSimpleMember(memberType, "test3", "test3@test.com", "pass", "test3"); + Member member3 = MemberBuilder.CreateSimpleMember(memberType, "test3", "test3@test.com", "pass", "test3"); MemberService.Save(member3); MemberService.AssignRoles(new[] { member1.Id, member2.Id, member3.Id }, new[] { roleName1 }); - var result = MemberService.FindMembersInRole(roleName1, usernameToMatch, matchType); + IEnumerable result = MemberService.FindMembersInRole(roleName1, usernameToMatch, matchType); Assert.AreEqual(resultCount, result.Count()); } @@ -375,9 +381,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); // temp make sure they exist @@ -386,7 +392,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -398,9 +404,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); // temp make sure they exist @@ -409,7 +415,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "mytestrole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -421,14 +427,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -440,14 +446,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1@test.com"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1@test.com"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); MemberService.Save(member2); MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -457,15 +463,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); - //implicitly create the role + // implicitly create the role MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } @@ -475,17 +481,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1", "MyTestRole2" }); - MemberService.DissociateRoles(new[] {member1.Id }, new[] {"MyTestRole1"}); + MemberService.DissociateRoles(new[] { member1.Id }, new[] { "MyTestRole1" }); MemberService.DissociateRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole2" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(1, membersInRole.Count()); membersInRole = MemberService.GetMembersInRole("MyTestRole2"); Assert.AreEqual(0, membersInRole.Count()); @@ -496,9 +502,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); + Member member1 = MemberBuilder.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); MemberService.Save(member1); - var member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); + Member member2 = MemberBuilder.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); MemberService.Save(member2); MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1", "MyTestRole2" }); @@ -506,7 +512,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.DissociateRoles(new[] { member1.Username }, new[] { "MyTestRole1" }); MemberService.DissociateRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole2" }); - var membersInRole = MemberService.GetMembersInRole("MyTestRole1"); + IEnumerable membersInRole = MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(1, membersInRole.Count()); membersInRole = MemberService.GetMembersInRole("MyTestRole2"); Assert.AreEqual(0, membersInRole.Count()); @@ -521,7 +527,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberService.Save(member); MemberService.Delete(member); - var deleted = MemberService.GetById(member.Id); + IMember deleted = MemberService.GetById(member.Id); // Assert Assert.That(deleted, Is.Null); @@ -562,17 +568,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMember member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); MemberService.Save(member); - var resolved = MemberService.GetByEmail(member.Email); + IMember resolved = MemberService.GetByEmail(member.Email); - //NOTE: This will not trigger a property isDirty because this is not based on a 'Property', it is + // NOTE: This will not trigger a property isDirty because this is not based on a 'Property', it is // just a c# property of the Member object resolved.Email = "changed@test.com"; - //NOTE: this WILL trigger a property isDirty because setting this c# property actually sets a value of + // NOTE: this WILL trigger a property isDirty because setting this c# property actually sets a value of // the underlying 'Property' resolved.FailedPasswordAttempts = 1234; - var dirtyMember = (ICanBeDirty) resolved; + var dirtyMember = (ICanBeDirty)resolved; var dirtyProperties = resolved.Properties.Where(x => x.IsDirty()).ToList(); Assert.IsTrue(dirtyMember.IsDirty()); Assert.AreEqual(1, dirtyProperties.Count); @@ -598,7 +604,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMember member = MemberBuilder.CreateSimpleMember(memberType, "Test Real Name", "test@test.com", "pass", "testUsername"); MemberService.Save(member); - Assert.AreEqual("Test Real Name", member.Name); } @@ -631,11 +636,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - long totalRecs; - var found = MemberService.GetAll(0, 2, out totalRecs); + IEnumerable found = MemberService.GetAll(0, 2, out long totalRecs); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); @@ -648,11 +652,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - long totalRecs; - var found = MemberService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, true, null, "Member No-"); + IEnumerable found = MemberService.GetAll(0, 2, out long totalRecs, "username", Direction.Ascending, true, null, "Member No-"); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); @@ -671,14 +674,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "Bob", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "Bob", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindMembersByDisplayName("B", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); + IEnumerable found = MemberService.FindMembersByDisplayName("B", 0, 100, out long totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(1, found.Count()); } @@ -688,14 +690,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //don't find this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello","hello"); + + // don't find this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByEmail("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); + IEnumerable found = MemberService.FindByEmail("tes", 0, 100, out long totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } @@ -705,14 +707,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByEmail("test.com", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith); + IEnumerable found = MemberService.FindByEmail("test.com", 0, 100, out long totalRecs, StringPropertyMatchType.EndsWith); Assert.AreEqual(11, found.Count()); } @@ -722,14 +724,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByEmail("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains); + IEnumerable found = MemberService.FindByEmail("test", 0, 100, out long totalRecs, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } @@ -739,14 +741,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByEmail("hello@test.com", 0, 100, out totalRecs, StringPropertyMatchType.Exact); + IEnumerable found = MemberService.FindByEmail("hello@test.com", 0, 100, out long totalRecs, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } @@ -756,14 +758,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //don't find this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // don't find this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByUsername("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); + IEnumerable found = MemberService.FindByUsername("tes", 0, 100, out long totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } @@ -773,14 +775,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByUsername("llo", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith); + IEnumerable found = MemberService.FindByUsername("llo", 0, 100, out long totalRecs, StringPropertyMatchType.EndsWith); Assert.AreEqual(1, found.Count()); } @@ -790,14 +792,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hellotest"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hellotest"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByUsername("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains); + IEnumerable found = MemberService.FindByUsername("test", 0, 100, out long totalRecs, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } @@ -807,14 +809,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - //include this - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // include this + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - long totalRecs; - var found = MemberService.FindByUsername("hello", 0, 100, out totalRecs, StringPropertyMatchType.Exact); + IEnumerable found = MemberService.FindByUsername("hello", 0, 100, out long totalRecs, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } @@ -824,12 +826,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "title", "hello member", StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); @@ -840,12 +842,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "title", " member", StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); @@ -856,12 +858,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "title", "Member No", StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); @@ -872,13 +874,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("title", "title of mine"); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "title", "mine", StringPropertyMatchType.EndsWith); Assert.AreEqual(1, found.Count()); @@ -888,21 +890,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Exact() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 2); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 2, ValuePropertyMatchType.Exact); Assert.AreEqual(2, found.Count()); @@ -912,21 +918,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Greater_Than() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 10); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 3, ValuePropertyMatchType.GreaterThan); Assert.AreEqual(7, found.Count()); @@ -936,21 +946,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Greater_Than_Equal_To() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 10); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 3, ValuePropertyMatchType.GreaterThanOrEqualTo); Assert.AreEqual(8, found.Count()); @@ -960,21 +974,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Less_Than() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.DateTime, ValueStorageType.Date, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.DateTime, + ValueStorageType.Date, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 1); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 5, ValuePropertyMatchType.LessThan); Assert.AreEqual(6, found.Count()); @@ -984,21 +1002,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Int_Value_Less_Than_Or_Equal() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "number") - { - Name = "Number", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -51 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "number") + { + Name = "Number", + DataTypeId = -51, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("number", i)); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 1); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "number", 5, ValuePropertyMatchType.LessThanOrEqualTo); Assert.AreEqual(7, found.Count()); @@ -1008,21 +1030,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Exact() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 2, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 2, 0), ValuePropertyMatchType.Exact); Assert.AreEqual(2, found.Count()); @@ -1032,21 +1058,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Greater_Than() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThan); Assert.AreEqual(7, found.Count()); @@ -1056,21 +1086,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Greater_Than_Equal_To() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThanOrEqualTo); Assert.AreEqual(8, found.Count()); @@ -1080,21 +1114,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Less_Than() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThan); Assert.AreEqual(6, found.Count()); @@ -1104,21 +1142,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Property_Date_Value_Less_Than_Or_Equal() { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); - memberType.AddPropertyType(new PropertyType(ShortStringHelper, Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer, "date") - { - Name = "Date", - //NOTE: This is what really determines the db type - the above definition doesn't really do anything - DataTypeId = -36 - }, "Content"); + memberType.AddPropertyType( + new PropertyType( + ShortStringHelper, + Constants.PropertyEditors.Aliases.Integer, + ValueStorageType.Integer, + "date") + { + Name = "Date", + DataTypeId = -36, // NOTE: This is what really determines the db type - the above definition doesn't really do anything + }, "Content"); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0)); MemberService.Save(customMember); - var found = MemberService.GetMembersByPropertyValue( + IEnumerable found = MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThanOrEqualTo); Assert.AreEqual(7, found.Count()); @@ -1129,12 +1171,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetCount(MemberCountType.All); + int found = MemberService.GetCount(MemberCountType.All); Assert.AreEqual(11, found); } @@ -1144,14 +1186,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.IsLockedOut = i % 2 == 0); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.IsLockedOut = i % 2 == 0); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.IsLockedOut, true); MemberService.Save(customMember); - var found = MemberService.GetCount(MemberCountType.LockedOut); + int found = MemberService.GetCount(MemberCountType.LockedOut); Assert.AreEqual(6, found); } @@ -1161,14 +1203,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.IsApproved = i % 2 == 0); + IEnumerable members = MemberBuilder.CreateMultipleSimpleMembers(memberType, 10, (i, member) => member.IsApproved = i % 2 == 0); MemberService.Save(members); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.IsApproved, false); MemberService.Save(customMember); - var found = MemberService.GetCount(MemberCountType.Approved); + int found = MemberService.GetCount(MemberCountType.Approved); Assert.AreEqual(5, found); } @@ -1182,12 +1224,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberTypeService.Save(memberType); Assert.IsFalse(memberType.PropertyTypes.Any(x => x.Alias == Constants.Conventions.Member.Comments)); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); - //this should not throw an exception + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + + // this should not throw an exception customMember.Comments = "hello world"; MemberService.Save(customMember); - var found = MemberService.GetById(customMember.Id); + IMember found = MemberService.GetById(customMember.Id); Assert.IsTrue(found.Comments.IsNullOrWhiteSpace()); } @@ -1201,19 +1244,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "test", "test"); - var date = DateTime.Now; + Member member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "test", "test"); + DateTime date = DateTime.Now; member.LastLoginDate = DateTime.Now; MemberService.Save(member); - var result = MemberService.GetById(member.Id); + IMember result = MemberService.GetById(member.Id); Assert.AreEqual( date.TruncateTo(DateTimeExtensions.DateTruncate.Second), result.LastLoginDate.TruncateTo(DateTimeExtensions.DateTruncate.Second)); - //now ensure the col is correct - var sqlContext = GetRequiredService(); - var sql = sqlContext.Sql().Select() + // now ensure the col is correct + ISqlContext sqlContext = GetRequiredService(); + Sql sql = sqlContext.Sql().Select() .From() .InnerJoin().On(dto => dto.PropertyTypeId, dto => dto.Id) .InnerJoin().On((left, right) => left.VersionId == right.Id) @@ -1221,7 +1264,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services .Where(dto => dto.Alias == Constants.Conventions.Member.LastLoginDate); List colResult; - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { colResult = scope.Database.Fetch(sql); scope.Complete(); @@ -1240,10 +1283,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); + Member customMember = MemberBuilder.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); MemberService.Save(customMember); - var found = MemberService.GetById(customMember.Id); + IMember found = MemberService.GetById(customMember.Id); Assert.IsTrue(found.IsApproved); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberTypeServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberTypeServiceTests.cs index 5c61501a10..6e25d7f405 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberTypeServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberTypeServiceTests.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.Threading; using NUnit.Framework; @@ -17,6 +21,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class MemberTypeServiceTests : UmbracoIntegrationTest { private IMemberService MemberService => GetRequiredService(); + private IMemberTypeService MemberTypeService => GetRequiredService(); [SetUp] @@ -31,9 +36,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - //re-get + + // re-get memberType = MemberTypeService.Get(memberType.Id); - foreach (var p in memberType.PropertyTypes) + foreach (IPropertyType p in memberType.PropertyTypes) { Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias)); } @@ -44,15 +50,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var prop = memberType.PropertyTypes.First().Alias; + string prop = memberType.PropertyTypes.First().Alias; memberType.SetMemberCanEditProperty(prop, true); MemberTypeService.Save(memberType); - //re-get + + // re-get memberType = MemberTypeService.Get(memberType.Id); - foreach (var p in memberType.PropertyTypes.Where(x => x.Alias != prop)) + foreach (IPropertyType p in memberType.PropertyTypes.Where(x => x.Alias != prop)) { Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias)); } + Assert.IsTrue(memberType.MemberCanEditProperty(prop)); } @@ -61,9 +69,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - //re-get + + // re-get memberType = MemberTypeService.Get(memberType.Id); - foreach (var p in memberType.PropertyTypes) + foreach (IPropertyType p in memberType.PropertyTypes) { Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias)); } @@ -74,15 +83,17 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeService.Save(memberType); - var prop = memberType.PropertyTypes.First().Alias; + string prop = memberType.PropertyTypes.First().Alias; memberType.SetMemberCanViewProperty(prop, true); MemberTypeService.Save(memberType); - //re-get + + // re-get memberType = MemberTypeService.Get(memberType.Id); - foreach (var p in memberType.PropertyTypes.Where(x => x.Alias != prop)) + foreach (IPropertyType p in memberType.PropertyTypes.Where(x => x.Alias != prop)) { Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias)); } + Assert.IsTrue(memberType.MemberCanViewProperty(prop)); } @@ -93,14 +104,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services MemberTypeService.Save(memberType); IMember member = MemberBuilder.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); MemberService.Save(member); - var initProps = member.Properties.Count; + int initProps = member.Properties.Count; - //remove a property (NOT ONE OF THE DEFAULTS) - var standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); + // remove a property (NOT ONE OF THE DEFAULTS) + Dictionary standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); memberType.RemovePropertyType(memberType.PropertyTypes.First(x => standardProps.ContainsKey(x.Alias) == false).Alias); MemberTypeService.Save(memberType); - //re-load it from the db + // re-load it from the db member = MemberService.GetById(member.Id); Assert.AreEqual(initProps - 1, member.Properties.Count); @@ -119,12 +130,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Empty_Description_Is_Always_Null_After_Saving_Member_Type() { - var service = MemberTypeService; - var memberType = MemberTypeBuilder.CreateSimpleMemberType(); + IMemberTypeService service = MemberTypeService; + MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); memberType.Description = null; service.Save(memberType); - var memberType2 = MemberTypeBuilder.CreateSimpleMemberType("memberType2", "Member Type 2"); + MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType("memberType2", "Member Type 2"); memberType2.Description = string.Empty; service.Save(memberType2); @@ -132,9 +143,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.IsNull(memberType2.Description); } - //[Test] - //public void Can_Save_MemberType_Structure_And_Create_A_Member_Based_On_It() - //{ + // [Test] + // public void Can_Save_MemberType_Structure_And_Create_A_Member_Based_On_It() + // { // // Arrange // var cs = MemberService; // var cts = MemberTypeService; @@ -148,7 +159,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // /*,"Navigation"*/); // cts.Save(ctBase); - // var ctHomePage = new MemberType(ctBase) + // var ctHomePage = new MemberType(ctBase) // { // Name = "Home Page", // Alias = "HomePage", @@ -160,19 +171,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // /*,"Navigation"*/); // cts.Save(ctHomePage); - // // Act + // // Act // var homeDoc = cs.CreateMember("Test", "test@test.com", "test", "HomePage"); - // // Assert + // // Assert // Assert.That(ctBase.HasIdentity, Is.True); // Assert.That(ctHomePage.HasIdentity, Is.True); // Assert.That(homeDoc.HasIdentity, Is.True); // Assert.That(homeDoc.ContentTypeId, Is.EqualTo(ctHomePage.Id)); - //} + // } - //[Test] - //public void Can_Create_And_Save_MemberType_Composition() - //{ + // [Test] + // public void Can_Create_And_Save_MemberType_Composition() + // { // /* // * Global // * - Components @@ -182,23 +193,23 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // var global = MemberTypeBuilder.CreateSimpleContentType("global", "Global"); // service.Save(global); - // var components = MemberTypeBuilder.CreateSimpleContentType("components", "Components", global); + // var components = MemberTypeBuilder.CreateSimpleContentType("components", "Components", global); // service.Save(components); - // var component = MemberTypeBuilder.CreateSimpleContentType("component", "Component", components); + // var component = MemberTypeBuilder.CreateSimpleContentType("component", "Component", components); // service.Save(component); - // var category = MemberTypeBuilder.CreateSimpleContentType("category", "Category", global); + // var category = MemberTypeBuilder.CreateSimpleContentType("category", "Category", global); // service.Save(category); - // var success = category.AddContentType(component); + // var success = category.AddContentType(component); - // Assert.That(success, Is.False); - //} + // Assert.That(success, Is.False); + // } - //[Test] - //public void Can_Remove_ContentType_Composition_From_ContentType() - //{ + // [Test] + // public void Can_Remove_ContentType_Composition_From_ContentType() + // { // //Test for U4-2234 // var cts = ContentTypeService; // //Arrange @@ -211,11 +222,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // var homepage = CreateHomepage(site); // cts.Save(homepage); - // //Add banner to homepage + // //Add banner to homepage // var added = homepage.AddContentType(banner); // cts.Save(homepage); - // //Assert composition + // //Assert composition // var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); // var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); // Assert.That(added, Is.True); @@ -223,42 +234,42 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert.That(bannerPropertyExists, Is.True); // Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); - // //Remove banner from homepage + // //Remove banner from homepage // var removed = homepage.RemoveContentType(banner.Alias); // cts.Save(homepage); - // //Assert composition + // //Assert composition // var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); // var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); // Assert.That(removed, Is.True); // Assert.That(bannerStillExists, Is.False); // Assert.That(bannerPropertyStillExists, Is.False); // Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(4)); - //} + // } - //[Test] - //public void Can_Copy_ContentType_By_Performing_Clone() - //{ + // [Test] + // public void Can_Copy_ContentType_By_Performing_Clone() + // { // // Arrange // var service = ContentTypeService; // var metaContentType = MemberTypeBuilder.CreateMetaContentType(); // service.Save(metaContentType); - // var simpleContentType = MemberTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType); + // var simpleContentType = MemberTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType); // service.Save(simpleContentType); // var categoryId = simpleContentType.Id; - // // Act + // // Act // var sut = simpleContentType.Clone("newcategory"); // service.Save(sut); - // // Assert + // // Assert // Assert.That(sut.HasIdentity, Is.True); - // var contentType = service.GetContentType(sut.Id); + // var contentType = service.GetContentType(sut.Id); // var category = service.GetContentType(categoryId); - // Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); + // Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); // Assert.AreEqual(contentType.ParentId, category.ParentId); // Assert.AreEqual(contentType.Level, category.Level); // Assert.AreEqual(contentType.PropertyTypes.Count(), category.PropertyTypes.Count()); @@ -269,10 +280,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id); // Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id); - //} + // } - //private ContentType CreateComponent() - //{ + // private ContentType CreateComponent() + // { // var component = new ContentType(-1) // { // Alias = "component", @@ -285,15 +296,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Trashed = false // }; - // var contentCollection = new PropertyTypeCollection(); + // var contentCollection = new PropertyTypeCollection(); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "componentGroup", Name = "Component Group", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); // component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); - // return component; - //} + // return component; + // } - //private ContentType CreateBannerComponent(ContentType parent) - //{ + // private ContentType CreateBannerComponent(ContentType parent) + // { // var banner = new ContentType(parent) // { // Alias = "banner", @@ -306,7 +317,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Trashed = false // }; - // var propertyType = new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) + // var propertyType = new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) // { // Alias = "bannerName", // Name = "Banner Name", @@ -318,10 +329,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // }; // banner.AddPropertyType(propertyType, "Component"); // return banner; - //} + // } - //private ContentType CreateSite() - //{ + // private ContentType CreateSite() + // { // var site = new ContentType(-1) // { // Alias = "site", @@ -334,15 +345,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Trashed = false // }; - // var contentCollection = new PropertyTypeCollection(); + // var contentCollection = new PropertyTypeCollection(); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "hostname", Name = "Hostname", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); // site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); - // return site; - //} + // return site; + // } - //private ContentType CreateHomepage(ContentType parent) - //{ + // private ContentType CreateHomepage(ContentType parent) + // { // var contentType = new ContentType(parent) // { // Alias = "homepage", @@ -355,36 +366,36 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // Trashed = false // }; - // var contentCollection = new PropertyTypeCollection(); + // var contentCollection = new PropertyTypeCollection(); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "title", Name = "Title", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "bodyText", Name = "Body Text", Description = "", HelpText = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -87 }); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "author", Name = "Author", Description = "Name of the author", HelpText = "", Mandatory = false, SortOrder = 3, DataTypeDefinitionId = -88 }); - // contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); + // contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); - // return contentType; - //} + // return contentType; + // } - //private IEnumerable CreateContentTypeHierarchy() - //{ + // private IEnumerable CreateContentTypeHierarchy() + // { // //create the master type // var masterContentType = MemberTypeBuilder.CreateSimpleContentType("masterContentType", "MasterContentType"); // masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); // ContentTypeService.Save(masterContentType); - // //add the one we just created + // //add the one we just created // var list = new List { masterContentType }; - // for (var i = 0; i < 10; i++) + // for (var i = 0; i < 10; i++) // { // var contentType = MemberTypeBuilder.CreateSimpleContentType("childType" + i, "ChildType" + i, // //make the last entry in the list, this one's parent // list.Last()); - // list.Add(contentType); + // list.Add(contentType); // } - // return list; - //} + // return list; + // } } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/PublicAccessServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/PublicAccessServiceTests.cs index 9b46a37245..b4b78365c6 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/PublicAccessServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/PublicAccessServiceTests.cs @@ -1,7 +1,11 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Linq; using System.Threading; using NUnit.Framework; +using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Tests.Common.Builders; @@ -16,8 +20,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class PublicAccessServiceTests : UmbracoIntegrationTest { private IContentService ContentService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IPublicAccessService PublicAccessService => GetRequiredService(); private Content _content; @@ -25,10 +32,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [SetUp] public void CreateTestData() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // else, FK violation on contentType! - var ct = ContentTypeBuilder.CreateSimpleContentType("blah", "Blah", defaultTemplateId: template.Id); + ContentType ct = ContentTypeBuilder.CreateSimpleContentType("blah", "Blah", defaultTemplateId: template.Id); ContentTypeService.Save(ct); _content = ContentBuilder.CreateSimpleContent(ct, "Test", -1); @@ -39,17 +46,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Add_New_Entry() { // Arrange - - // Act - var entry = new PublicAccessEntry(_content, _content, _content, new[] + PublicAccessRule[] rules = new[] { new PublicAccessRule() { RuleType = "TestType", RuleValue = "TestVal" }, - }); - var result = PublicAccessService.Save(entry); + }; + var entry = new PublicAccessEntry(_content, _content, _content, rules); + + // Act + Attempt result = PublicAccessService.Save(entry); // Assert Assert.IsTrue(result.Success); @@ -65,19 +73,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Add_Rule() { // Arrange - var entry = new PublicAccessEntry(_content, _content, _content, new[] + PublicAccessRule[] rules = new[] { new PublicAccessRule() { RuleType = "TestType", RuleValue = "TestVal" }, - }); + }; + var entry = new PublicAccessEntry(_content, _content, _content, rules); PublicAccessService.Save(entry); // Act - var updated = PublicAccessService.AddRule(_content, "TestType2", "AnotherVal"); - //re-get + Attempt> updated = PublicAccessService.AddRule(_content, "TestType2", "AnotherVal"); + + // re-get entry = PublicAccessService.GetEntryForContent(_content); // Assert @@ -90,21 +100,22 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Add_Multiple_Value_For_Same_Rule_Type() { // Arrange - var entry = new PublicAccessEntry(_content, _content, _content, new[] + PublicAccessRule[] rules = new[] { new PublicAccessRule() { RuleType = "TestType", RuleValue = "TestVal" }, - }); + }; + var entry = new PublicAccessEntry(_content, _content, _content, rules); PublicAccessService.Save(entry); // Act - var updated1 = PublicAccessService.AddRule(_content, "TestType", "AnotherVal1"); - var updated2 = PublicAccessService.AddRule(_content, "TestType", "AnotherVal2"); + Attempt> updated1 = PublicAccessService.AddRule(_content, "TestType", "AnotherVal1"); + Attempt> updated2 = PublicAccessService.AddRule(_content, "TestType", "AnotherVal2"); - //re-get + // re-get entry = PublicAccessService.GetEntryForContent(_content); // Assert @@ -119,7 +130,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Remove_Rule() { // Arrange - var entry = new PublicAccessEntry(_content, _content, _content, new[] + PublicAccessRule[] rules = new[] { new PublicAccessRule() { @@ -131,12 +142,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services RuleType = "TestType", RuleValue = "TestValue2" }, - }); + }; + var entry = new PublicAccessEntry(_content, _content, _content, rules); PublicAccessService.Save(entry); // Act - var removed = PublicAccessService.RemoveRule(_content, "TestType", "TestValue1"); - //re-get + Attempt removed = PublicAccessService.RemoveRule(_content, "TestType", "TestValue1"); + + // re-get entry = PublicAccessService.GetEntryForContent(_content); // Assert diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RedirectUrlServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RedirectUrlServiceTests.cs index 89cde051e3..72a5eb4302 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RedirectUrlServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RedirectUrlServiceTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using System.Threading; using Microsoft.Extensions.Logging; using Moq; @@ -54,7 +57,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services } } - [Test] public void Can_Get_Most_Recent_RedirectUrl() { diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs index 3196b54201..1965c737a5 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.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; @@ -18,49 +21,57 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class RelationServiceTests : UmbracoIntegrationTest { private IContentTypeService ContentTypeService => GetRequiredService(); + private IContentService ContentService => GetRequiredService(); + private IMediaTypeService MediaTypeService => GetRequiredService(); + private IMediaService MediaService => GetRequiredService(); + private IRelationService RelationService => GetRequiredService(); [Test] public void Get_Paged_Relations_By_Relation_Type() { - //Create content + // Create content var createdContent = new List(); - var contentType = ContentTypeBuilder.CreateBasicContentType("blah"); + ContentType contentType = ContentTypeBuilder.CreateBasicContentType("blah"); ContentTypeService.Save(contentType); for (int i = 0; i < 3; i++) { - var c1 = ContentBuilder.CreateBasicContent(contentType); + Content c1 = ContentBuilder.CreateBasicContent(contentType); ContentService.Save(c1); createdContent.Add(c1); } - //Create media + // Create media var createdMedia = new List(); - var imageType = MediaTypeBuilder.CreateImageMediaType("myImage"); + MediaType imageType = MediaTypeBuilder.CreateImageMediaType("myImage"); MediaTypeService.Save(imageType); for (int i = 0; i < 3; i++) { - var c1 = MediaBuilder.CreateMediaImage(imageType, -1); + Media c1 = MediaBuilder.CreateMediaImage(imageType, -1); MediaService.Save(c1); createdMedia.Add(c1); } - var relType = RelationService.GetRelationTypeByAlias(Constants.Conventions.RelationTypes.RelatedMediaAlias); + IRelationType relType = RelationService.GetRelationTypeByAlias(Constants.Conventions.RelationTypes.RelatedMediaAlias); // Relate content to media - foreach (var content in createdContent) - foreach (var media in createdMedia) + foreach (IContent content in createdContent) + { + foreach (IMedia media in createdMedia) + { RelationService.Relate(content.Id, media.Id, relType); + } + } - var paged = RelationService.GetPagedByRelationTypeId(relType.Id, 0, 4, out var totalRecs).ToList(); + var paged = RelationService.GetPagedByRelationTypeId(relType.Id, 0, 4, out long totalRecs).ToList(); Assert.AreEqual(9, totalRecs); Assert.AreEqual(4, paged.Count); - //next page + // next page paged.AddRange(RelationService.GetPagedByRelationTypeId(relType.Id, 1, 4, out totalRecs)); Assert.AreEqual(9, totalRecs); @@ -73,27 +84,30 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Return_List_Of_Content_Items_Where_Media_Item_Referenced() { - var mt = MediaTypeBuilder.CreateSimpleMediaType("testMediaType", "Test Media Type"); + MediaType mt = MediaTypeBuilder.CreateSimpleMediaType("testMediaType", "Test Media Type"); MediaTypeService.Save(mt); - var m1 = MediaBuilder.CreateSimpleMedia(mt, "hello 1", -1); + Media m1 = MediaBuilder.CreateSimpleMedia(mt, "hello 1", -1); MediaService.Save(m1); - var ct = ContentTypeBuilder.CreateTextPageContentType("richTextTest"); + ContentType ct = ContentTypeBuilder.CreateTextPageContentType("richTextTest"); ct.AllowedTemplates = Enumerable.Empty(); ContentTypeService.Save(ct); - void createContentWithMediaRefs() + void CreateContentWithMediaRefs() { - var content = ContentBuilder.CreateTextpageContent(ct, "my content 2", -1); - //'bodyText' is a property with a RTE property editor which we knows automatically tracks relations + Content content = ContentBuilder.CreateTextpageContent(ct, "my content 2", -1); + + // 'bodyText' is a property with a RTE property editor which we knows automatically tracks relations content.Properties["bodyText"].SetValue(@"

"); ContentService.Save(content); } - for (var i = 0; i < 6; i++) - createContentWithMediaRefs(); //create 6 content items referencing the same media + for (int i = 0; i < 6; i++) + { + CreateContentWithMediaRefs(); // create 6 content items referencing the same media + } var relations = RelationService.GetByChildId(m1.Id, Constants.Conventions.RelationTypes.RelatedMediaAlias).ToList(); Assert.AreEqual(6, relations.Count); @@ -105,12 +119,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Create_RelationType_Without_Name() { - var rs = RelationService; + IRelationService rs = RelationService; IRelationType rt = new RelationType("Test", "repeatedEventOccurence", false, Constants.ObjectTypes.Document, Constants.ObjectTypes.Media); Assert.DoesNotThrow(() => rs.Save(rt)); - //re-get + // re-get rt = RelationService.GetRelationTypeById(rt.Id); Assert.AreEqual("Test", rt.Name); @@ -123,12 +137,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Create_Relation_Type_Without_Object_Types() { - var rs = RelationService; + IRelationService rs = RelationService; IRelationType rt = new RelationType("repeatedEventOccurence", "repeatedEventOccurence", false, null, null); Assert.DoesNotThrow(() => rs.Save(rt)); - //re-get + // re-get rt = RelationService.GetRelationTypeById(rt.Id); Assert.IsNull(rt.ChildObjectType); @@ -138,7 +152,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Relation_Returns_Parent_Child_Object_Types_When_Creating() { - var r = CreateAndSaveRelation("Test", "test"); + IRelation r = CreateAndSaveRelation("Test", "test"); Assert.AreEqual(Constants.ObjectTypes.Document, r.ParentObjectType); Assert.AreEqual(Constants.ObjectTypes.Media, r.ChildObjectType); @@ -147,7 +161,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Relation_Returns_Parent_Child_Object_Types_When_Getting() { - var r = CreateAndSaveRelation("Test", "test"); + IRelation r = CreateAndSaveRelation("Test", "test"); // re-get r = RelationService.GetById(r.Id); @@ -159,9 +173,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Insert_Bulk_Relations() { - var rs = RelationService; + IRelationService rs = RelationService; - var newRelations = CreateRelations(10); + IEnumerable newRelations = CreateRelations(10); Assert.IsTrue(newRelations.All(x => !x.HasIdentity)); @@ -173,43 +187,45 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Update_Bulk_Relations() { - var rs = RelationService; + IRelationService rs = RelationService; - var date = DateTime.Now.AddDays(-10); - var newRelations = CreateRelations(10); - foreach (var r in newRelations) + DateTime date = DateTime.Now.AddDays(-10); + IEnumerable newRelations = CreateRelations(10); + foreach (IRelation r in newRelations) { r.CreateDate = date; r.UpdateDate = date; } - //insert + // insert RelationService.Save(newRelations); Assert.IsTrue(newRelations.All(x => x.UpdateDate == date)); - var newDate = DateTime.Now.AddDays(-5); - foreach (var r in newRelations) + DateTime newDate = DateTime.Now.AddDays(-5); + foreach (IRelation r in newRelations) + { r.UpdateDate = newDate; + } - //update + // update RelationService.Save(newRelations); Assert.IsTrue(newRelations.All(x => x.UpdateDate == newDate)); } private IRelation CreateAndSaveRelation(string name, string alias) { - var rs = RelationService; + IRelationService rs = RelationService; var rt = new RelationType(name, alias, false, null, null); rs.Save(rt); - var ct = ContentTypeBuilder.CreateBasicContentType(); + ContentType ct = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(ct); - var mt = MediaTypeBuilder.CreateImageMediaType("img"); + MediaType mt = MediaTypeBuilder.CreateImageMediaType("img"); MediaTypeService.Save(mt); - var c1 = ContentBuilder.CreateBasicContent(ct); - var c2 = MediaBuilder.CreateMediaImage(mt, -1); + Content c1 = ContentBuilder.CreateBasicContent(ct); + Media c2 = MediaBuilder.CreateMediaImage(mt, -1); ContentService.Save(c1); MediaService.Save(c2); @@ -226,21 +242,21 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services /// private IEnumerable CreateRelations(int count) { - var rs = RelationService; - var rtName = Guid.NewGuid().ToString(); + IRelationService rs = RelationService; + string rtName = Guid.NewGuid().ToString(); var rt = new RelationType(rtName, rtName, false, null, null); rs.Save(rt); - var ct = ContentTypeBuilder.CreateBasicContentType(); + ContentType ct = ContentTypeBuilder.CreateBasicContentType(); ContentTypeService.Save(ct); - var mt = MediaTypeBuilder.CreateImageMediaType("img"); + MediaType mt = MediaTypeBuilder.CreateImageMediaType("img"); MediaTypeService.Save(mt); return Enumerable.Range(1, count).Select(index => { - var c1 = ContentBuilder.CreateBasicContent(ct); - var c2 = MediaBuilder.CreateMediaImage(mt, -1); + Content c1 = ContentBuilder.CreateBasicContent(ct); + Media c2 = MediaBuilder.CreateMediaImage(mt, -1); ContentService.Save(c1); MediaService.Save(c2); @@ -248,6 +264,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services }).ToList(); } - //TODO: Create a relation for entities of the wrong Entity Type (GUID) based on the Relation Type's defined parent/child object types + // TODO: Create a relation for entities of the wrong Entity Type (GUID) based on the Relation Type's defined parent/child object types } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/TagServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/TagServiceTests.cs index c48f56e9a7..3c3455fabd 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/TagServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/TagServiceTests.cs @@ -1,4 +1,7 @@ -using System.Linq; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.Linq; using System.Threading; using Newtonsoft.Json; using NUnit.Framework; @@ -15,8 +18,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { /// /// Tests covering methods in the TagService class. - /// This is more of an integration test as it involves multiple layers - /// as well as configuration. + /// Involves multiple layers as well as configuration. /// [TestFixture] [Apartment(ApartmentState.STA)] @@ -24,18 +26,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class TagServiceTests : UmbracoIntegrationTest { private IContentService ContentService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private ITagService TagService => GetRequiredService(); + private IDataTypeService DataTypeService => GetRequiredService(); + private IJsonSerializer Serializer => GetRequiredService(); + private PropertyEditorCollection PropertyEditorCollection => GetRequiredService(); + private IContentType _contentType; [SetUp] public void CreateTestData() { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // else, FK violation on contentType! _contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", defaultTemplateId: template.Id); @@ -56,7 +65,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // change content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "elephant" }, true); - content1.RemoveTags(PropertyEditorCollection, DataTypeService, Serializer,"tags", new[] { "cow" }); + content1.RemoveTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "cow" }); ContentService.SaveAndPublish(content1); // more changes @@ -67,14 +76,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // get it back content1 = ContentService.GetById(content1.Id); - var tagsValue = content1.GetValue("tags").ToString(); - var tagsValues = JsonConvert.DeserializeObject(tagsValue); + string tagsValue = content1.GetValue("tags").ToString(); + string[] tagsValues = JsonConvert.DeserializeObject(tagsValue); Assert.AreEqual(3, tagsValues.Length); Assert.Contains("pig", tagsValues); Assert.Contains("goat", tagsValues); Assert.Contains("elephant", tagsValues); - var tags = TagService.GetTagsForProperty(content1.Id, "tags").ToArray(); + ITag[] tags = TagService.GetTagsForProperty(content1.Id, "tags").ToArray(); Assert.IsTrue(tags.All(x => x.Group == "default")); tagsValues = tags.Select(x => x.Text).ToArray(); @@ -87,15 +96,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void TagList_Contains_NodeCount() { - var content1 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 1", -1); + Content content1 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 1", -1); content1.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "cow", "pig", "goat" }); ContentService.SaveAndPublish(content1); - var content2 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 2", -1); + Content content2 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 2", -1); content2.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "cow", "pig" }); ContentService.SaveAndPublish(content2); - var content3 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 3", -1); + Content content3 = ContentBuilder.CreateSimpleContent(_contentType, "Tagged content 3", -1); content3.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "cow" }); ContentService.SaveAndPublish(content3); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ThreadSafetyServiceTest.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ThreadSafetyServiceTest.cs index 9600d62051..f727963d84 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ThreadSafetyServiceTest.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ThreadSafetyServiceTest.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using System; using System.Collections.Generic; using System.Diagnostics; @@ -36,7 +39,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public class ThreadSafetyServiceTest : UmbracoIntegrationTest { private IContentService ContentService => GetRequiredService(); + private IMediaService MediaService => GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); [SetUp] @@ -45,12 +50,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services CreateTestData(); } - private const int MaxThreadCount = 20; private void Save(ContentService service, IContent content) { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.Execute("SET LOCK_TIMEOUT 60000"); service.Save(content); @@ -60,7 +64,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private void Save(MediaService service, IMedia media) { - using (var scope = ScopeProvider.CreateScope()) + using (IScope scope = ScopeProvider.CreateScope()) { scope.Database.Execute("SET LOCK_TIMEOUT 60000"); service.Save(media); @@ -75,8 +79,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // comment out to trace locks return done; - //new Thread(() => - //{ + // new Thread(() => + // { // using (var scope = ScopeProvider.CreateScope()) // while (done.IsSet == false) // { @@ -89,17 +93,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services // } // Thread.Sleep(50); // } - //}).Start(); - //return done; + // }).Start(); + // return done; } [Test] public void Ensure_All_Threads_Execute_Successfully_Content_Service() { if (Environment.GetEnvironmentVariable("UMBRACO_TMP") != null) + { Assert.Ignore("Do not run on VSTS."); + } - var log = GetRequiredService>(); + ILogger log = GetRequiredService>(); // the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton var contentService = (ContentService)ContentService; @@ -109,9 +115,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services log.LogInformation("Starting..."); - var done = TraceLocks(); + ManualResetEventSlim done = TraceLocks(); - for (var i = 0; i < MaxThreadCount; i++) + for (int i = 0; i < MaxThreadCount; i++) { var t = new Thread(() => { @@ -119,23 +125,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { log.LogInformation("[{0}] Running...", Thread.CurrentThread.ManagedThreadId); - var name1 = "test-" + Guid.NewGuid(); - var content1 = contentService.Create(name1, -1, "umbTextpage"); + string name1 = "test-" + Guid.NewGuid(); + IContent content1 = contentService.Create(name1, -1, "umbTextpage"); log.LogInformation("[{0}] Saving content #1.", Thread.CurrentThread.ManagedThreadId); Save(contentService, content1); - Thread.Sleep(100); //quick pause for maximum overlap! + Thread.Sleep(100); // quick pause for maximum overlap! - var name2 = "test-" + Guid.NewGuid(); - var content2 = contentService.Create(name2, -1, "umbTextpage"); + string name2 = "test-" + Guid.NewGuid(); + IContent content2 = contentService.Create(name2, -1, "umbTextpage"); log.LogInformation("[{0}] Saving content #2.", Thread.CurrentThread.ManagedThreadId); Save(contentService, content2); } catch (Exception e) { - lock (exceptions) { exceptions.Add(e); } + lock (exceptions) + { + exceptions.Add(e); + } } }); threads.Add(t); @@ -154,8 +163,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services log.LogInformation("Checking exceptions"); if (exceptions.Count == 0) { - //now look up all items, there should be 40! - var items = contentService.GetRootContent(); + // now look up all items, there should be 40! + IEnumerable items = contentService.GetRootContent(); Assert.AreEqual(2 * MaxThreadCount, items.Count()); } else @@ -168,9 +177,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Ensure_All_Threads_Execute_Successfully_Media_Service() { if (Environment.GetEnvironmentVariable("UMBRACO_TMP") != null) + { Assert.Ignore("Do not run on VSTS."); + } - var log = GetRequiredService>(); + ILogger log = GetRequiredService>(); // mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton var mediaService = (MediaService)MediaService; @@ -180,9 +191,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services log.LogInformation("Starting..."); - var done = TraceLocks(); + ManualResetEventSlim done = TraceLocks(); - for (var i = 0; i < MaxThreadCount; i++) + for (int i = 0; i < MaxThreadCount; i++) { var t = new Thread(() => { @@ -190,30 +201,33 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { log.LogInformation("[{0}] Running...", Thread.CurrentThread.ManagedThreadId); - var name1 = "test-" + Guid.NewGuid(); - var media1 = mediaService.CreateMedia(name1, -1, Constants.Conventions.MediaTypes.Folder); + string name1 = "test-" + Guid.NewGuid(); + IMedia media1 = mediaService.CreateMedia(name1, -1, Constants.Conventions.MediaTypes.Folder); log.LogInformation("[{0}] Saving media #1.", Thread.CurrentThread.ManagedThreadId); Save(mediaService, media1); - Thread.Sleep(100); //quick pause for maximum overlap! + Thread.Sleep(100); // quick pause for maximum overlap! - var name2 = "test-" + Guid.NewGuid(); - var media2 = mediaService.CreateMedia(name2, -1, Constants.Conventions.MediaTypes.Folder); + string name2 = "test-" + Guid.NewGuid(); + IMedia media2 = mediaService.CreateMedia(name2, -1, Constants.Conventions.MediaTypes.Folder); log.LogInformation("[{0}] Saving media #2.", Thread.CurrentThread.ManagedThreadId); Save(mediaService, media2); } catch (Exception e) { - lock (exceptions) { exceptions.Add(e); } + lock (exceptions) + { + exceptions.Add(e); + } } }); threads.Add(t); } - //start all threads + // start all threads threads.ForEach(x => x.Start()); - //wait for all to complete + // wait for all to complete threads.ForEach(x => x.Join()); done.Set(); @@ -221,20 +235,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services if (exceptions.Count == 0) { // now look up all items, there should be 40! - var items = mediaService.GetRootMedia(); + IEnumerable items = mediaService.GetRootMedia(); Assert.AreEqual(2 * MaxThreadCount, items.Count()); } else { throw new Exception("Exceptions!", exceptions.First()); // rethrow the first one... } - } public void CreateTestData() { // Create and Save ContentType "umbTextpage" -> 1045 - var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage"); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage"); contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"); ContentTypeService.Save(contentType); } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs index 8b5189378d..e0d29ca634 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.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.Security.Cryptography; @@ -27,23 +30,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class UserServiceTests : UmbracoIntegrationTest { - private UserService UserService => (UserService) GetRequiredService(); + private UserService UserService => (UserService)GetRequiredService(); + private IContentTypeService ContentTypeService => GetRequiredService(); + private IFileService FileService => GetRequiredService(); + private IContentService ContentService => GetRequiredService(); [Test] public void Get_User_Permissions_For_Unassigned_Permission_Nodes() { // Arrange - var user = CreateTestUser(out _); + IUser user = CreateTestUser(out _); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -52,7 +58,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.Save(content); // Act - var permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); + EntityPermission[] permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); // Assert Assert.AreEqual(3, permissions.Length); @@ -65,14 +71,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_User_Permissions_For_Assigned_Permission_Nodes() { // Arrange - var user = CreateTestUser(out var userGroup); + IUser user = CreateTestUser(out IUserGroup userGroup); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -87,7 +93,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content[2], ActionBrowse.ActionLetter, new int[] { userGroup.Id }); // Act - var permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); + EntityPermission[] permissions = UserService.GetPermissions(user, content[0].Id, content[1].Id, content[2].Id).ToArray(); // Assert Assert.AreEqual(3, permissions.Length); @@ -100,14 +106,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_UserGroup_Assigned_Permissions() { // Arrange - var userGroup = CreateTestUserGroup(); + UserGroup userGroup = CreateTestUserGroup(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -122,7 +128,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content.ElementAt(2), ActionBrowse.ActionLetter, new int[] { userGroup.Id }); // Act - var permissions = UserService.GetPermissions(userGroup, false, content[0].Id, content[1].Id, content[2].Id).ToArray(); + EntityPermission[] permissions = UserService.GetPermissions(userGroup, false, content[0].Id, content[1].Id, content[2].Id).ToArray(); // Assert Assert.AreEqual(3, permissions.Length); @@ -135,14 +141,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_UserGroup_Assigned_And_Default_Permissions() { // Arrange - var userGroup = CreateTestUserGroup(); + UserGroup userGroup = CreateTestUserGroup(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -156,7 +162,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content[1], ActionDelete.ActionLetter, new int[] { userGroup.Id }); // Act - var permissions = UserService.GetPermissions(userGroup, true, content[0].Id, content[1].Id, content[2].Id) + EntityPermission[] permissions = UserService.GetPermissions(userGroup, true, content[0].Id, content[1].Id, content[2].Id) .ToArray(); // Assert @@ -170,31 +176,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_All_User_Permissions_For_All_Nodes_With_Explicit_Permission() { // Arrange - var userGroup1 = CreateTestUserGroup(); - var userGroup2 = CreateTestUserGroup("test2", "Test 2"); - var userGroup3 = CreateTestUserGroup("test3", "Test 3"); - var user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); + UserGroup userGroup1 = CreateTestUserGroup(); + UserGroup userGroup2 = CreateTestUserGroup("test2", "Test 2"); + UserGroup userGroup3 = CreateTestUserGroup("test3", "Test 3"); + IUser user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); - var defaultPermissionCount = userGroup3.Permissions.Count(); + int defaultPermissionCount = userGroup3.Permissions.Count(); user.AddGroup(userGroup1); user.AddGroup(userGroup2); user.AddGroup(userGroup3); UserService.Save(user); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType) }; ContentService.Save(content); - //assign permissions - we aren't assigning anything explicit for group3 and nothing explicit for content[2] /w group2 + + // assign permissions - we aren't assigning anything explicit for group3 and nothing explicit for content[2] /w group2 ContentService.SetPermission(content[0], ActionBrowse.ActionLetter, new int[] { userGroup1.Id }); ContentService.SetPermission(content[0], ActionDelete.ActionLetter, new int[] { userGroup1.Id }); ContentService.SetPermission(content[0], ActionMove.ActionLetter, new int[] { userGroup2.Id }); @@ -203,46 +210,52 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content[2], ActionDelete.ActionLetter, new int[] { userGroup1.Id }); // Act - //we don't pass in any nodes so it will return all of them - var result = UserService.GetPermissions(user).ToArray(); + // we don't pass in any nodes so it will return all of them + EntityPermission[] result = UserService.GetPermissions(user).ToArray(); var permissions = result .GroupBy(x => x.EntityId) .ToDictionary(x => x.Key, x => x.GroupBy(a => a.UserGroupId).ToDictionary(a => a.Key, a => a.ToArray())); // Assert - //there will be 3 since that is how many content items there are + // there will be 3 since that is how many content items there are Assert.AreEqual(3, permissions.Count); - //test permissions contains content[0] + // test permissions contains content[0] Assert.IsTrue(permissions.ContainsKey(content[0].Id)); - //test that this permissions set contains permissions for all groups + + // test that this permissions set contains permissions for all groups Assert.IsTrue(permissions[content[0].Id].ContainsKey(userGroup1.Id)); Assert.IsTrue(permissions[content[0].Id].ContainsKey(userGroup2.Id)); Assert.IsTrue(permissions[content[0].Id].ContainsKey(userGroup3.Id)); - //test that the correct number of permissions are returned for each group + + // test that the correct number of permissions are returned for each group Assert.AreEqual(2, permissions[content[0].Id][userGroup1.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(1, permissions[content[0].Id][userGroup2.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[0].Id][userGroup3.Id].SelectMany(x => x.AssignedPermissions).Count()); - //test permissions contains content[1] + // test permissions contains content[1] Assert.IsTrue(permissions.ContainsKey(content[1].Id)); - //test that this permissions set contains permissions for all groups + + // test that this permissions set contains permissions for all groups Assert.IsTrue(permissions[content[1].Id].ContainsKey(userGroup1.Id)); Assert.IsTrue(permissions[content[1].Id].ContainsKey(userGroup2.Id)); Assert.IsTrue(permissions[content[1].Id].ContainsKey(userGroup3.Id)); - //test that the correct number of permissions are returned for each group + + // test that the correct number of permissions are returned for each group Assert.AreEqual(1, permissions[content[1].Id][userGroup1.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(1, permissions[content[1].Id][userGroup2.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[1].Id][userGroup3.Id].SelectMany(x => x.AssignedPermissions).Count()); - //test permissions contains content[2] + // test permissions contains content[2] Assert.IsTrue(permissions.ContainsKey(content[2].Id)); - //test that this permissions set contains permissions for all groups + + // test that this permissions set contains permissions for all groups Assert.IsTrue(permissions[content[2].Id].ContainsKey(userGroup1.Id)); Assert.IsTrue(permissions[content[2].Id].ContainsKey(userGroup2.Id)); Assert.IsTrue(permissions[content[2].Id].ContainsKey(userGroup3.Id)); - //test that the correct number of permissions are returned for each group + + // test that the correct number of permissions are returned for each group Assert.AreEqual(1, permissions[content[2].Id][userGroup1.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[2].Id][userGroup2.Id].SelectMany(x => x.AssignedPermissions).Count()); Assert.AreEqual(defaultPermissionCount, permissions[content[2].Id][userGroup3.Id].SelectMany(x => x.AssignedPermissions).Count()); @@ -252,14 +265,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_All_User_Group_Permissions_For_All_Nodes() { // Arrange - var userGroup = CreateTestUserGroup(); + UserGroup userGroup = CreateTestUserGroup(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var content = new[] + Content[] content = new[] { ContentBuilder.CreateSimpleContent(contentType), ContentBuilder.CreateSimpleContent(contentType), @@ -274,7 +287,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(content[2], ActionDelete.ActionLetter, new int[] { userGroup.Id }); // Act - //we don't pass in any nodes so it will return all of them + // we don't pass in any nodes so it will return all of them var permissions = UserService.GetPermissions(userGroup, true) .GroupBy(x => x.EntityId) .ToDictionary(x => x.Key, x => x); @@ -292,11 +305,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Calculate_Permissions_For_User_For_Path() { - //see: http://issues.umbraco.org/issue/U4-10075#comment=67-40085 + // see: http://issues.umbraco.org/issue/U4-10075#comment=67-40085 // for an overview of what this is testing - const string path = "-1,1,2,3,4"; - var pathIds = path.GetIdsFromPathReversed(); + int[] pathIds = path.GetIdsFromPathReversed(); const int groupA = 7; const int groupB = 8; @@ -304,51 +316,51 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services var userGroups = new Dictionary { - {groupA, new[] {"S", "D", "F"}}, - {groupB, new[] {"S", "D", "G", "K"}}, - {groupC, new[] {"F", "G"}} + { groupA, new[] { "S", "D", "F" } }, + { groupB, new[] { "S", "D", "G", "K" } }, + { groupC, new[] { "F", "G" } } }; - var permissions = new[] + EntityPermission[] permissions = new[] { - new EntityPermission(groupA, 1, userGroups[groupA], isDefaultPermissions:true), - new EntityPermission(groupA, 2, userGroups[groupA], isDefaultPermissions:true), - new EntityPermission(groupA, 3, userGroups[groupA], isDefaultPermissions:true), - new EntityPermission(groupA, 4, userGroups[groupA], isDefaultPermissions:true), + new EntityPermission(groupA, 1, userGroups[groupA], isDefaultPermissions: true), + new EntityPermission(groupA, 2, userGroups[groupA], isDefaultPermissions: true), + new EntityPermission(groupA, 3, userGroups[groupA], isDefaultPermissions: true), + new EntityPermission(groupA, 4, userGroups[groupA], isDefaultPermissions: true), - new EntityPermission(groupB, 1, userGroups[groupB], isDefaultPermissions:true), - new EntityPermission(groupB, 2, new []{"F", "R"}, isDefaultPermissions:false), - new EntityPermission(groupB, 3, userGroups[groupB], isDefaultPermissions:true), - new EntityPermission(groupB, 4, userGroups[groupB], isDefaultPermissions:true), + new EntityPermission(groupB, 1, userGroups[groupB], isDefaultPermissions: true), + new EntityPermission(groupB, 2, new[] { "F", "R" }, isDefaultPermissions: false), + new EntityPermission(groupB, 3, userGroups[groupB], isDefaultPermissions: true), + new EntityPermission(groupB, 4, userGroups[groupB], isDefaultPermissions: true), - new EntityPermission(groupC, 1, userGroups[groupC], isDefaultPermissions:true), - new EntityPermission(groupC, 2, userGroups[groupC], isDefaultPermissions:true), - new EntityPermission(groupC, 3, new []{"Q", "Z"}, isDefaultPermissions:false), - new EntityPermission(groupC, 4, userGroups[groupC], isDefaultPermissions:true), + new EntityPermission(groupC, 1, userGroups[groupC], isDefaultPermissions: true), + new EntityPermission(groupC, 2, userGroups[groupC], isDefaultPermissions: true), + new EntityPermission(groupC, 3, new[] { "Q", "Z" }, isDefaultPermissions: false), + new EntityPermission(groupC, 4, userGroups[groupC], isDefaultPermissions: true), }; - //Permissions for Id 4 - var result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds); + // Permissions for Id 4 + EntityPermissionSet result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds); Assert.AreEqual(4, result.EntityId); - var allPermissions = result.GetAllPermissions().ToArray(); + string[] allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(6, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "R", "Q", "Z" })); - //Permissions for Id 3 + // Permissions for Id 3 result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds.Skip(1).ToArray()); Assert.AreEqual(3, result.EntityId); allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(6, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "R", "Q", "Z" })); - //Permissions for Id 2 + // Permissions for Id 2 result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds.Skip(2).ToArray()); Assert.AreEqual(2, result.EntityId); allPermissions = result.GetAllPermissions().ToArray(); Assert.AreEqual(5, allPermissions.Length, string.Join(",", allPermissions)); Assert.IsTrue(allPermissions.ContainsAll(new[] { "S", "D", "F", "G", "R" })); - //Permissions for Id 1 + // Permissions for Id 1 result = UserService.CalculatePermissionsForPathForUser(permissions, pathIds.Skip(3).ToArray()); Assert.AreEqual(1, result.EntityId); allPermissions = result.GetAllPermissions().ToArray(); @@ -359,16 +371,16 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Determine_Deepest_Explicit_Permissions_For_Group_For_Path_1() { - var path = "-1,1,2,3"; - var pathIds = path.GetIdsFromPathReversed(); - var defaults = new[] { "A", "B" }; + string path = "-1,1,2,3"; + int[] pathIds = path.GetIdsFromPathReversed(); + string[] defaults = new[] { "A", "B" }; var permissions = new List { - new EntityPermission(9876, 1, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 2, new []{"B","C", "D"}, isDefaultPermissions:false), - new EntityPermission(9876, 3, defaults, isDefaultPermissions:true) + new EntityPermission(9876, 1, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 2, new[] { "B", "C", "D" }, isDefaultPermissions: false), + new EntityPermission(9876, 3, defaults, isDefaultPermissions: true) }; - var result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); + EntityPermission result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); Assert.AreEqual(3, result.AssignedPermissions.Length); Assert.IsFalse(result.IsDefaultPermissions); Assert.IsTrue(result.AssignedPermissions.ContainsAll(new[] { "B", "C", "D" })); @@ -379,32 +391,32 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Determine_Deepest_Explicit_Permissions_For_Group_For_Path_2() { - var path = "-1,1,2,3"; - var pathIds = path.GetIdsFromPathReversed(); - var defaults = new[] { "A", "B", "C" }; + string path = "-1,1,2,3"; + int[] pathIds = path.GetIdsFromPathReversed(); + string[] defaults = new[] { "A", "B", "C" }; var permissions = new List { - new EntityPermission(9876, 1, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 2, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 3, defaults, isDefaultPermissions:true) + new EntityPermission(9876, 1, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 2, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 3, defaults, isDefaultPermissions: true) }; - var result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: false); + EntityPermission result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: false); Assert.IsNull(result); } [Test] public void Determine_Deepest_Explicit_Permissions_For_Group_For_Path_3() { - var path = "-1,1,2,3"; - var pathIds = path.GetIdsFromPathReversed(); - var defaults = new[] { "A", "B" }; + string path = "-1,1,2,3"; + int[] pathIds = path.GetIdsFromPathReversed(); + string[] defaults = new[] { "A", "B" }; var permissions = new List { - new EntityPermission(9876, 1, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 2, defaults, isDefaultPermissions:true), - new EntityPermission(9876, 3, defaults, isDefaultPermissions:true) + new EntityPermission(9876, 1, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 2, defaults, isDefaultPermissions: true), + new EntityPermission(9876, 3, defaults, isDefaultPermissions: true) }; - var result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); + EntityPermission result = UserService.GetPermissionsForPathForGroup(permissions, pathIds, fallbackToDefaultPermissions: true); Assert.AreEqual(2, result.AssignedPermissions.Length); Assert.IsTrue(result.IsDefaultPermissions); Assert.IsTrue(result.AssignedPermissions.ContainsAll(defaults)); @@ -416,18 +428,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_User_Implicit_Permissions() { // Arrange - var userGroup = CreateTestUserGroup(); + UserGroup userGroup = CreateTestUserGroup(); - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); - var parent = ContentBuilder.CreateSimpleContent(contentType); + Content parent = ContentBuilder.CreateSimpleContent(contentType); ContentService.Save(parent); - var child1 = ContentBuilder.CreateSimpleContent(contentType, "child1", parent.Id); + Content child1 = ContentBuilder.CreateSimpleContent(contentType, "child1", parent.Id); ContentService.Save(child1); - var child2 = ContentBuilder.CreateSimpleContent(contentType, "child2", child1.Id); + Content child2 = ContentBuilder.CreateSimpleContent(contentType, "child2", child1.Id); ContentService.Save(child2); ContentService.SetPermission(parent, ActionBrowse.ActionLetter, new int[] { userGroup.Id }); @@ -437,20 +449,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services ContentService.SetPermission(parent, ActionDelete.ActionLetter, new int[] { userGroup.Id }); // Act - var permissions = UserService.GetPermissionsForPath(userGroup, child2.Path); + EntityPermissionSet permissions = UserService.GetPermissionsForPath(userGroup, child2.Path); // Assert - var allPermissions = permissions.GetAllPermissions().ToArray(); + string[] allPermissions = permissions.GetAllPermissions().ToArray(); Assert.AreEqual(3, allPermissions.Length); } [Test] public void Can_Delete_User() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); UserService.Delete(user, true); - var deleted = UserService.GetUserById(user.Id); + IUser deleted = UserService.GetUserById(user.Id); // Assert Assert.That(deleted, Is.Null); @@ -459,10 +471,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Disables_User_Instead_Of_Deleting_If_Flag_Not_Set() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); UserService.Delete(user); - var deleted = UserService.GetUserById(user.Id); + IUser deleted = UserService.GetUserById(user.Id); // Assert Assert.That(deleted, Is.Not.Null); @@ -471,8 +483,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Exists_By_Username() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); - var user2 = UserService.CreateUserWithIdentity("john2@umbraco.io", "john2@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user2 = UserService.CreateUserWithIdentity("john2@umbraco.io", "john2@umbraco.io"); Assert.IsTrue(UserService.Exists("JohnDoe")); Assert.IsFalse(UserService.Exists("notFound")); Assert.IsTrue(UserService.Exists("john2@umbraco.io")); @@ -481,7 +493,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Email() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetByEmail(user.Email)); Assert.IsNull(UserService.GetByEmail("do@not.find")); @@ -490,7 +502,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Username() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetByUsername(user.Username)); Assert.IsNull(UserService.GetByUsername("notFound")); @@ -499,7 +511,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Username_With_Backslash() { - var user = UserService.CreateUserWithIdentity("mydomain\\JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("mydomain\\JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetByUsername(user.Username)); Assert.IsNull(UserService.GetByUsername("notFound")); @@ -508,7 +520,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Object_Id() { - var user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); Assert.IsNotNull(UserService.GetUserById(user.Id)); Assert.IsNull(UserService.GetUserById(9876)); @@ -517,14 +529,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Find_By_Email_Starts_With() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - //don't find this - var customUser = UserBuilder.CreateUser(); + + // don't find this + User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@hello.com"; UserService.Save(customUser); - var found = UserService.FindByEmail("tes", 0, 100, out _, StringPropertyMatchType.StartsWith); + IEnumerable found = UserService.FindByEmail("tes", 0, 100, out _, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } @@ -532,14 +545,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Find_By_Email_Ends_With() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - //include this - var customUser = UserBuilder.CreateUser(); + + // include this + User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@test.com"; UserService.Save(customUser); - var found = UserService.FindByEmail("test.com", 0, 100, out _, StringPropertyMatchType.EndsWith); + IEnumerable found = UserService.FindByEmail("test.com", 0, 100, out _, StringPropertyMatchType.EndsWith); Assert.AreEqual(11, found.Count()); } @@ -547,14 +561,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Find_By_Email_Contains() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - //include this - var customUser = UserBuilder.CreateUser(); + + // include this + User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@test.com"; UserService.Save(customUser); - var found = UserService.FindByEmail("test", 0, 100, out _, StringPropertyMatchType.Contains); + IEnumerable found = UserService.FindByEmail("test", 0, 100, out _, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } @@ -562,14 +577,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Find_By_Email_Exact() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - //include this - var customUser = UserBuilder.CreateUser(); + + // include this + User customUser = UserBuilder.CreateUser(); customUser.Email = "hello@test.com"; UserService.Save(customUser); - var found = UserService.FindByEmail("hello@test.com", 0, 100, out _, StringPropertyMatchType.Exact); + IEnumerable found = UserService.FindByEmail("hello@test.com", 0, 100, out _, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } @@ -577,12 +593,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_All_Paged_Users() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - var found = UserService.GetAll(0, 2, out var totalRecs); + IEnumerable found = UserService.GetAll(0, 2, out long totalRecs); Assert.AreEqual(2, found.Count()); + // + 1 because of the built in admin user Assert.AreEqual(11, totalRecs); Assert.AreEqual("admin", found.First().Username); @@ -592,10 +609,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_All_Paged_Users_With_Filter() { - var users = UserBuilder. CreateMulipleUsers(10).ToArray(); + IUser[] users = UserBuilder.CreateMulipleUsers(10).ToArray(); UserService.Save(users); - var found = UserService.GetAll(0, 2, out var totalRecs, "username", Direction.Ascending, filter: "test"); + IEnumerable found = UserService.GetAll(0, 2, out long totalRecs, "username", Direction.Ascending, filter: "test"); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); @@ -606,19 +623,20 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_All_Paged_Users_For_Group() { - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); UserService.Save(userGroup); - var users = UserBuilder. CreateMulipleUsers(10).ToArray(); - for (var i = 0; i < 10;) + IUser[] users = UserBuilder.CreateMulipleUsers(10).ToArray(); + for (int i = 0; i < 10;) { users[i].AddGroup(userGroup.ToReadOnlyGroup()); i = i + 2; } + UserService.Save(users); long totalRecs; - var found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, includeUserGroups: new[] { userGroup.Alias }); + IEnumerable found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, includeUserGroups: new[] { userGroup.Alias }); Assert.AreEqual(2, found.Count()); Assert.AreEqual(5, totalRecs); @@ -629,24 +647,26 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_All_Paged_Users_For_Group_With_Filter() { - var userGroup = UserGroupBuilder.CreateUserGroup(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(); UserService.Save(userGroup); - var users = UserBuilder. CreateMulipleUsers(10).ToArray(); - for (var i = 0; i < 10;) + IUser[] users = UserBuilder.CreateMulipleUsers(10).ToArray(); + for (int i = 0; i < 10;) { users[i].AddGroup(userGroup.ToReadOnlyGroup()); i = i + 2; } - for (var i = 0; i < 10;) + + for (int i = 0; i < 10;) { users[i].Name = "blah" + users[i].Name; i = i + 3; } + UserService.Save(users); long totalRecs; - var found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, userGroups: new[] { userGroup.Alias }, filter: "blah"); + IEnumerable found = UserService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, userGroups: new[] { userGroup.Alias }, filter: "blah"); Assert.AreEqual(2, found.Count()); Assert.AreEqual(2, totalRecs); @@ -657,12 +677,12 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Count_All_Users() { - var users = UserBuilder. CreateMulipleUsers(10); + IEnumerable users = UserBuilder.CreateMulipleUsers(10); UserService.Save(users); - var customUser = UserBuilder.CreateUser(); + User customUser = UserBuilder.CreateUser(); UserService.Save(customUser); - var found = UserService.GetCount(MemberCountType.All); + int found = UserService.GetCount(MemberCountType.All); // + 1 because of the built in admin user Assert.AreEqual(12, found); @@ -672,24 +692,24 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Count_All_Online_Users() { - var users = UserBuilder. CreateMulipleUsers(10, (i, member) => member.LastLoginDate = DateTime.Now.AddMinutes(i * -2)); + IEnumerable users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.LastLoginDate = DateTime.Now.AddMinutes(i * -2)); UserService.Save(users); - var customUser = UserBuilder.CreateUser(); + User customUser = UserBuilder.CreateUser(); throw new NotImplementedException(); } [Test] public void Count_All_Locked_Users() { - var users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsLockedOut = i % 2 == 0); + IEnumerable users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsLockedOut = i % 2 == 0); UserService.Save(users); - var customUser = UserBuilder.CreateUser(); + User customUser = UserBuilder.CreateUser(); customUser.IsLockedOut = true; UserService.Save(customUser); - var found = UserService.GetCount(MemberCountType.LockedOut); + int found = UserService.GetCount(MemberCountType.LockedOut); Assert.AreEqual(6, found); } @@ -697,14 +717,14 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Count_All_Approved_Users() { - var users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsApproved = i % 2 == 0); + IEnumerable users = UserBuilder.CreateMulipleUsers(10, (i, member) => member.IsApproved = i % 2 == 0); UserService.Save(users); - var customUser = UserBuilder.CreateUser(); + User customUser = UserBuilder.CreateUser(); customUser.IsApproved = false; UserService.Save(customUser); - var found = UserService.GetCount(MemberCountType.Approved); + int found = UserService.GetCount(MemberCountType.Approved); // + 1 because of the built in admin user Assert.AreEqual(6, found); @@ -714,7 +734,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Can_Persist_New_User() { // Act - var membershipUser = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); + IUser membershipUser = UserService.CreateUserWithIdentity("JohnDoe", "john@umbraco.io"); // Assert Assert.That(membershipUser.HasIdentity, Is.True); @@ -728,10 +748,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { // Act // NOTE: Normally the hash'ing would be handled in the membership provider, so the service just saves the password - var password = "123456"; + string password = "123456"; var hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); - var encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); + string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); var globalSettings = new GlobalSettings(); var membershipUser = new User(globalSettings, "JohnDoe", "john@umbraco.io", encodedPassword, encodedPassword); UserService.Save(membershipUser); @@ -756,11 +776,11 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services userGroup.AddAllowedSection("mediat"); UserService.Save(userGroup); - var result1 = UserService.GetUserGroupById(userGroup.Id); + IUserGroup result1 = UserService.GetUserGroupById(userGroup.Id); Assert.AreEqual(2, result1.AllowedSections.Count()); - //adds some allowed sections + // adds some allowed sections userGroup.AddAllowedSection("test1"); userGroup.AddAllowedSection("test2"); userGroup.AddAllowedSection("test3"); @@ -771,19 +791,19 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services Assert.AreEqual(6, result1.AllowedSections.Count()); - //simulate clearing the sections - foreach (var s in userGroup.AllowedSections) + // simulate clearing the sections + foreach (string s in userGroup.AllowedSections) { result1.RemoveAllowedSection(s); } - //now just re-add a couple + // now just re-add a couple result1.AddAllowedSection("test3"); result1.AddAllowedSection("test4"); UserService.Save(result1); // Assert - //re-get + // re-get result1 = UserService.GetUserGroupById(userGroup.Id); Assert.AreEqual(2, result1.AllowedSections.Count()); } @@ -804,18 +824,18 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services UserService.Save(userGroup1); UserService.Save(userGroup2); - //adds some allowed sections + // adds some allowed sections userGroup1.AddAllowedSection("test"); userGroup2.AddAllowedSection("test"); UserService.Save(userGroup1); UserService.Save(userGroup2); - //now clear the section from all users + // now clear the section from all users UserService.DeleteSectionFromAllUserGroups("test"); // Assert - var result1 = UserService.GetUserGroupById(userGroup1.Id); - var result2 = UserService.GetUserGroupById(userGroup2.Id); + IUserGroup result1 = UserService.GetUserGroupById(userGroup1.Id); + IUserGroup result2 = UserService.GetUserGroupById(userGroup2.Id); Assert.IsFalse(result1.AllowedSections.Contains("test")); Assert.IsFalse(result2.AllowedSections.Contains("test")); } @@ -847,15 +867,15 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services UserService.Save(userGroup3); // Assert - var result1 = UserService.GetUserGroupById(userGroup1.Id); - var result2 = UserService.GetUserGroupById(userGroup2.Id); - var result3 = UserService.GetUserGroupById(userGroup3.Id); + IUserGroup result1 = UserService.GetUserGroupById(userGroup1.Id); + IUserGroup result2 = UserService.GetUserGroupById(userGroup2.Id); + IUserGroup result3 = UserService.GetUserGroupById(userGroup3.Id); Assert.IsTrue(result1.AllowedSections.Contains("test")); Assert.IsTrue(result2.AllowedSections.Contains("test")); Assert.IsFalse(result3.AllowedSections.Contains("test")); - //now add the section to all groups - foreach (var userGroup in new[] { userGroup1, userGroup2, userGroup3 }) + // now add the section to all groups + foreach (UserGroup userGroup in new[] { userGroup1, userGroup2, userGroup3 }) { userGroup.AddAllowedSection("test"); UserService.Save(userGroup); @@ -881,7 +901,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_User_With_Empty_Username() { // Arrange - var user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); user.Username = string.Empty; // Act & Assert @@ -892,7 +912,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Cannot_Save_User_With_Empty_Name() { // Arrange - var user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); + IUser user = UserService.CreateUserWithIdentity("John Doe", "john@umbraco.io"); user.Name = string.Empty; // Act & Assert @@ -903,10 +923,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Profile_Username() { // Arrange - var user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); + IUser user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); // Act - var profile = UserService.GetProfileByUserName(user.Username); + IProfile profile = UserService.GetProfileByUserName(user.Username); // Assert Assert.IsNotNull(profile); @@ -918,10 +938,10 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_By_Profile_Id() { // Arrange - var user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); + IUser user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); // Act - var profile = UserService.GetProfileById((int)user.Id); + IProfile profile = UserService.GetProfileById((int)user.Id); // Assert Assert.IsNotNull(profile); @@ -932,7 +952,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Get_By_Profile_Id_Must_Return_Null_If_User_Does_Not_Exist() { - var profile = UserService.GetProfileById(42); + IProfile profile = UserService.GetProfileById(42); // Assert Assert.IsNull(profile); @@ -941,7 +961,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void GetProfilesById_Must_Return_Empty_If_User_Does_Not_Exist() { - var profiles = UserService.GetProfilesById(42); + IEnumerable profiles = UserService.GetProfilesById(42); // Assert CollectionAssert.IsEmpty(profiles); @@ -951,10 +971,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services public void Get_User_By_Username() { // Arrange - var originalUser = CreateTestUser(out _); + IUser originalUser = CreateTestUser(out _); // Act - var updatedItem = (User)UserService.GetByUsername(originalUser.Username); // Assert @@ -975,31 +994,35 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services [Test] public void Can_Get_Assigned_StartNodes_For_User() { - var startContentItems = BuildContentItems(3); + Content[] startContentItems = BuildContentItems(3); - var testUserGroup = CreateTestUserGroup(); + UserGroup testUserGroup = CreateTestUserGroup(); - var userGroupId = testUserGroup.Id; + int userGroupId = testUserGroup.Id; CreateTestUsers(startContentItems.Select(x => x.Id).ToArray(), testUserGroup, 3); - var usersInGroup = UserService.GetAllInGroup(userGroupId); + IEnumerable usersInGroup = UserService.GetAllInGroup(userGroupId); - foreach (var user in usersInGroup) + foreach (IUser user in usersInGroup) + { Assert.AreEqual(user.StartContentIds.Length, startContentItems.Length); + } } private Content[] BuildContentItems(int numberToCreate) { - var template = TemplateBuilder.CreateTextPageTemplate(); + Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); - var contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); + ContentType contentType = ContentTypeBuilder.CreateSimpleContentType(defaultTemplateId: template.Id); ContentTypeService.Save(contentType); var startContentItems = new List(); - for (var i = 0; i < numberToCreate; i++) + for (int i = 0; i < numberToCreate; i++) + { startContentItems.Add(ContentBuilder.CreateSimpleContent(contentType)); + } ContentService.Save(startContentItems); @@ -1010,7 +1033,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { userGroup = CreateTestUserGroup(); - var user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); + IUser user = UserService.CreateUserWithIdentity("test1", "test1@test.com"); user.AddGroup(userGroup.ToReadOnlyGroup()); @@ -1023,9 +1046,9 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services { var users = new List(); - for (var i = 0; i < numberToCreate; i++) + for (int i = 0; i < numberToCreate; i++) { - var user = UserService.CreateUserWithIdentity($"test{i}", $"test{i}@test.com"); + IUser user = UserService.CreateUserWithIdentity($"test{i}", $"test{i}@test.com"); user.AddGroup(userGroup.ToReadOnlyGroup()); var updateable = (User)user; @@ -1041,8 +1064,8 @@ namespace Umbraco.Tests.Integration.Umbraco.Infrastructure.Services private UserGroup CreateTestUserGroup(string alias = "testGroup", string name = "Test Group") { - var permissions = "ABCDEFGHIJ1234567".ToCharArray().Select(x => x.ToString()).ToArray(); - var userGroup = UserGroupBuilder.CreateUserGroup(alias, name, permissions: permissions); + string[] permissions = "ABCDEFGHIJ1234567".ToCharArray().Select(x => x.ToString()).ToArray(); + UserGroup userGroup = UserGroupBuilder.CreateUserGroup(alias, name, permissions: permissions); UserService.Save(userGroup); diff --git a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs index dc88455d68..4350029159 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; @@ -44,13 +47,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters ContentTypes = new[] { new NestedContentConfiguration.ContentType { Alias = "feature" } - } + } }; - var complexTestEditor = Services.GetRequiredService(); - var testEditor = Services.GetRequiredService(); - var dataTypeService = Services.GetRequiredService(); - var serializer = Services.GetRequiredService(); + ComplexTestEditor complexTestEditor = Services.GetRequiredService(); + TestEditor testEditor = Services.GetRequiredService(); + IDataTypeService dataTypeService = Services.GetRequiredService(); + IConfigurationEditorJsonSerializer serializer = Services.GetRequiredService(); var complexDataType = new DataType(complexTestEditor, serializer) { @@ -65,85 +68,84 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters dataTypeService.Save(complexDataType); dataTypeService.Save(testDataType); - var fileService = Services.GetRequiredService(); - var template = TemplateBuilder.CreateTextPageTemplate(); + IFileService fileService = Services.GetRequiredService(); + Template template = TemplateBuilder.CreateTextPageTemplate(); fileService.SaveTemplate(template); _contentType = ContentTypeBuilder.CreateTextPageContentType(ContentTypeAlias, defaultTemplateId: template.Id); // add complex editor - foreach (var pt in _contentType.PropertyTypes) + foreach (IPropertyType pt in _contentType.PropertyTypes) { pt.DataTypeId = testDataType.Id; } _contentType.AddPropertyType( - new PropertyType(_shortStringHelper, "complexTest", ValueStorageType.Ntext) { Alias = "complex", Name = "Complex", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = complexDataType.Id }, + new PropertyType(_shortStringHelper, "complexTest", ValueStorageType.Ntext) { Alias = "complex", Name = "Complex", Description = string.Empty, Mandatory = false, SortOrder = 1, DataTypeId = complexDataType.Id }, "Content"); // make them all validate with a regex rule that will not pass - foreach (var prop in _contentType.PropertyTypes) + foreach (IPropertyType prop in _contentType.PropertyTypes) { prop.ValidationRegExp = "^donotmatch$"; prop.ValidationRegExpMessage = "Does not match!"; } - var contentTypeService = Services.GetRequiredService(); + IContentTypeService contentTypeService = Services.GetRequiredService(); contentTypeService.Save(_contentType); } - // - // protected override void Compose() - // { - // base.Compose(); - // - // var complexEditorConfig = new NestedContentConfiguration - // { - // ContentTypes = new[] - // { - // new NestedContentConfiguration.ContentType { Alias = "feature" } - // } - // }; - // var dataTypeService = new Mock(); - // dataTypeService.Setup(x => x.GetDataType(It.IsAny())) - // .Returns((int id) => id == ComplexDataTypeId - // ? Mock.Of(x => x.Configuration == complexEditorConfig) - // : Mock.Of()); - // - // var contentTypeService = new Mock(); - // contentTypeService.Setup(x => x.GetAll(It.IsAny())) - // .Returns(() => new List - // { - // _contentType - // }); - // - // var textService = new Mock(); - // textService.Setup(x => x.Localize("validation/invalidPattern", It.IsAny(), It.IsAny>())).Returns(() => "invalidPattern"); - // textService.Setup(x => x.Localize("validation/invalidNull", It.IsAny(), It.IsAny>())).Returns("invalidNull"); - // textService.Setup(x => x.Localize("validation/invalidEmpty", It.IsAny(), It.IsAny>())).Returns("invalidEmpty"); - // - // composition.Services.AddUnique(x => Mock.Of(x => x.GetDataType(It.IsAny()) == Mock.Of())); - // composition.Services.AddUnique(x => dataTypeService.Object); - // composition.Services.AddUnique(x => contentTypeService.Object); - // composition.Services.AddUnique(x => textService.Object); - // - // Composition.WithCollectionBuilder() - // .Add() - // .Add(); - // } + //// protected override void Compose() + //// { + //// base.Compose(); + //// + //// var complexEditorConfig = new NestedContentConfiguration + //// { + //// ContentTypes = new[] + //// { + //// new NestedContentConfiguration.ContentType { Alias = "feature" } + //// } + //// }; + //// var dataTypeService = new Mock(); + //// dataTypeService.Setup(x => x.GetDataType(It.IsAny())) + //// .Returns((int id) => id == ComplexDataTypeId + //// ? Mock.Of(x => x.Configuration == complexEditorConfig) + //// : Mock.Of()); + //// + //// var contentTypeService = new Mock(); + //// contentTypeService.Setup(x => x.GetAll(It.IsAny())) + //// .Returns(() => new List + //// { + //// _contentType + //// }); + //// + //// var textService = new Mock(); + //// textService.Setup(x => x.Localize("validation/invalidPattern", It.IsAny(), It.IsAny>())).Returns(() => "invalidPattern"); + //// textService.Setup(x => x.Localize("validation/invalidNull", It.IsAny(), It.IsAny>())).Returns("invalidNull"); + //// textService.Setup(x => x.Localize("validation/invalidEmpty", It.IsAny(), It.IsAny>())).Returns("invalidEmpty"); + //// + //// composition.Services.AddUnique(x => Mock.Of(x => x.GetDataType(It.IsAny()) == Mock.Of())); + //// composition.Services.AddUnique(x => dataTypeService.Object); + //// composition.Services.AddUnique(x => contentTypeService.Object); + //// composition.Services.AddUnique(x => textService.Object); + //// + //// Composition.WithCollectionBuilder() + //// .Add() + //// .Add(); + //// } [Test] public void Validating_ContentItemSave() { - var logger = Services.GetRequiredService>(); - var backofficeSecurityFactory = Services.GetRequiredService(); + ILogger logger = Services.GetRequiredService>(); + IBackOfficeSecurityFactory backofficeSecurityFactory = Services.GetRequiredService(); backofficeSecurityFactory.EnsureBackOfficeSecurity(); - var propertyValidationService = Services.GetRequiredService(); - var umbracoMapper = Services.GetRequiredService(); + IPropertyValidationService propertyValidationService = Services.GetRequiredService(); + UmbracoMapper umbracoMapper = Services.GetRequiredService(); var validator = new ContentSaveModelValidator(logger, propertyValidationService); - var content = ContentBuilder.CreateTextpageContent(_contentType, "test", -1); + Content content = ContentBuilder.CreateTextpageContent(_contentType, "test", -1); var id1 = new Guid("c8df5136-d606-41f0-9134-dea6ae0c2fd9"); var id2 = new Guid("f916104a-4082-48b2-a515-5c4bf2230f38"); @@ -151,7 +153,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters // TODO: Ok now test with a 4th level complex nested editor - var complexValue = @"[{ + string complexValue = @"[{ ""key"": """ + id1.ToString() + @""", ""name"": ""Hello world"", ""ncContentTypeAlias"": """ + ContentTypeAlias + @""", @@ -175,7 +177,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters content.SetValue("complex", complexValue); // map the persisted properties to a model representing properties to save - //var saveProperties = content.Properties.Select(x => Mapper.Map(x)).ToList(); + // var saveProperties = content.Properties.Select(x => Mapper.Map(x)).ToList(); var saveProperties = content.Properties.Select(x => { return new ContentPropertyBasic @@ -214,13 +216,13 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters ContentItemBinder.BindModel(save, content, _modelBinderHelper, umbracoMapper); var modelState = new ModelStateDictionary(); - var isValid = validator.ValidatePropertiesData(save, saveVariants[0], saveVariants[0].PropertyCollectionDto, modelState); + bool isValid = validator.ValidatePropertiesData(save, saveVariants[0], saveVariants[0].PropertyCollectionDto, modelState); // list results for debugging - foreach (var state in modelState) + foreach (KeyValuePair state in modelState) { Console.WriteLine(state.Key); - foreach (var error in state.Value.Errors) + foreach (ModelError error in state.Value.Errors) { Console.WriteLine("\t" + error.ErrorMessage); } @@ -231,26 +233,25 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters Assert.AreEqual(11, modelState.Keys.Count()); const string complexPropertyKey = "_Properties.complex.invariant.null"; Assert.IsTrue(modelState.Keys.Contains(complexPropertyKey)); - foreach (var state in modelState.Where(x => x.Key != complexPropertyKey)) + foreach (KeyValuePair state in modelState.Where(x => x.Key != complexPropertyKey)) { - foreach (var error in state.Value.Errors) + foreach (ModelError error in state.Value.Errors) { Assert.IsFalse(error.ErrorMessage.DetectIsJson()); // non complex is just an error message } } - var complexEditorErrors = modelState.Single(x => x.Key == complexPropertyKey).Value.Errors; - Assert.AreEqual(1, complexEditorErrors.Count); - var nestedError = complexEditorErrors[0]; - var jsonError = JsonConvert.DeserializeObject(nestedError.ErrorMessage); - var modelStateKeys = new[] { "_Properties.title.invariant.null.innerFieldId", "_Properties.title.invariant.null.value", "_Properties.bodyText.invariant.null.innerFieldId", "_Properties.bodyText.invariant.null.value" }; + ModelErrorCollection complexEditorErrors = modelState.Single(x => x.Key == complexPropertyKey).Value.Errors; + Assert.AreEqual(1, complexEditorErrors.Count); + ModelError nestedError = complexEditorErrors[0]; + JArray jsonError = JsonConvert.DeserializeObject(nestedError.ErrorMessage); + + string[] modelStateKeys = new[] { "_Properties.title.invariant.null.innerFieldId", "_Properties.title.invariant.null.value", "_Properties.bodyText.invariant.null.innerFieldId", "_Properties.bodyText.invariant.null.value" }; AssertNestedValidation(jsonError, 0, id1, modelStateKeys); AssertNestedValidation(jsonError, 1, id2, modelStateKeys.Concat(new[] { "_Properties.complex.invariant.null.innerFieldId", "_Properties.complex.invariant.null.value" }).ToArray()); var nestedJsonError = jsonError.SelectToken("$[1].complex") as JArray; Assert.IsNotNull(nestedJsonError); AssertNestedValidation(nestedJsonError, 0, id3, modelStateKeys); - - } private void AssertNestedValidation(JArray jsonError, int index, Guid id, string[] modelStateKeys) @@ -259,7 +260,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters Assert.AreEqual(id.ToString(), jsonError.SelectToken("$[" + index + "].$id").Value()); Assert.AreEqual("textPage", jsonError.SelectToken("$[" + index + "].$elementTypeAlias").Value()); Assert.IsNotNull(jsonError.SelectToken("$[" + index + "].ModelState")); - foreach (var key in modelStateKeys) + foreach (string key in modelStateKeys) { var error = jsonError.SelectToken("$[" + index + "].ModelState['" + key + "']") as JArray; Assert.IsNotNull(error); @@ -267,38 +268,45 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters } } - //[HideFromTypeFinder] + // [HideFromTypeFinder] [DataEditor("complexTest", "test", "test")] public class ComplexTestEditor : NestedContentPropertyEditor { - public ComplexTestEditor(ILoggerFactory loggerFactory, Lazy propertyEditors, IDataTypeService dataTypeService, IContentTypeService contentTypeService, ILocalizationService localizationService, - IIOHelper ioHelper, ILocalizedTextService localizedTextService, IShortStringHelper shortStringHelper, IJsonSerializer jsonSerializer) - : base(loggerFactory, propertyEditors, dataTypeService, localizationService, contentTypeService, ioHelper, shortStringHelper, localizedTextService, jsonSerializer) + public ComplexTestEditor( + ILoggerFactory loggerFactory, + Lazy propertyEditors, + IDataTypeService dataTypeService, + IContentTypeService contentTypeService, + ILocalizationService localizationService, + IIOHelper ioHelper, + ILocalizedTextService localizedTextService, + IShortStringHelper shortStringHelper, + IJsonSerializer jsonSerializer) + : base(loggerFactory, propertyEditors, dataTypeService, localizationService, contentTypeService, ioHelper, shortStringHelper, localizedTextService, jsonSerializer) { } protected override IDataValueEditor CreateValueEditor() { - var editor = base.CreateValueEditor(); + IDataValueEditor editor = base.CreateValueEditor(); editor.Validators.Add(new NeverValidateValidator()); return editor; } } - //[HideFromTypeFinder] - [DataEditor("test", "test", "test")] // This alias aligns with the prop editor alias for all properties created from MockedContentTypes.CreateTextPageContentType - public class TestEditor : DataEditor - { - public TestEditor( - ILoggerFactory loggerFactory, - IDataTypeService dataTypeService, - ILocalizationService localizationService, - ILocalizedTextService localizedTextService, - IShortStringHelper shortStringHelper, - IJsonSerializer jsonSerializer) - : base(loggerFactory, dataTypeService, localizationService, localizedTextService, shortStringHelper, jsonSerializer) + // [HideFromTypeFinder] + [DataEditor("test", "test", "test")] // This alias aligns with the prop editor alias for all properties created from MockedContentTypes.CreateTextPageContentType + public class TestEditor : DataEditor + { + public TestEditor( + ILoggerFactory loggerFactory, + IDataTypeService dataTypeService, + ILocalizationService localizationService, + ILocalizedTextService localizedTextService, + IShortStringHelper shortStringHelper, + IJsonSerializer jsonSerializer) + : base(loggerFactory, dataTypeService, localizationService, localizedTextService, shortStringHelper, jsonSerializer) { - } protected override IDataValueEditor CreateValueEditor() => new TestValueEditor(DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper, JsonSerializer, Attribute); @@ -316,7 +324,6 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters { Validators.Add(new NeverValidateValidator()); } - } } @@ -327,6 +334,5 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.Backoffice.Filters yield return new ValidationResult("WRONG!", new[] { "innerFieldId" }); } } - } } diff --git a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/UmbracoBackOfficeServiceCollectionExtensionsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/UmbracoBackOfficeServiceCollectionExtensionsTests.cs index 37863da472..1f07a1f45f 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/UmbracoBackOfficeServiceCollectionExtensionsTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/UmbracoBackOfficeServiceCollectionExtensionsTests.cs @@ -1,3 +1,6 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; @@ -16,7 +19,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.BackOffice [Test] public void AddUmbracoBackOfficeIdentity_ExpectBackOfficeUserStoreResolvable() { - var userStore = Services.GetService>(); + IUserStore userStore = Services.GetService>(); Assert.IsNotNull(userStore); Assert.AreEqual(typeof(BackOfficeUserStore), userStore.GetType()); @@ -25,7 +28,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.BackOffice [Test] public void AddUmbracoBackOfficeIdentity_ExpectBackOfficeClaimsPrincipalFactoryResolvable() { - var principalFactory = Services.GetService>(); + IUserClaimsPrincipalFactory principalFactory = Services.GetService>(); Assert.IsNotNull(principalFactory); Assert.AreEqual(typeof(BackOfficeClaimsPrincipalFactory), principalFactory.GetType()); @@ -34,7 +37,7 @@ namespace Umbraco.Tests.Integration.Umbraco.Web.BackOffice [Test] public void AddUmbracoBackOfficeIdentity_ExpectBackOfficeUserManagerResolvable() { - var userManager = Services.GetService(); + IBackOfficeUserManager userManager = Services.GetService(); Assert.NotNull(userManager); }