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