Merge remote-tracking branch 'origin/netcore/netcore' into netcore/feature/more-files-from-infrastructure-to-core

# Conflicts:
#	src/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/ConvertersTests.cs
This commit is contained in:
Nikolaj
2020-12-09 08:45:28 +01:00
55 changed files with 440 additions and 3027 deletions

View File

@@ -1,4 +1,4 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Moq;
using Umbraco.Core.Configuration.Models;
@@ -48,10 +48,8 @@ namespace Umbraco.Tests.UnitTests.TestHelpers.Objects
new TestVariationContextAccessor(),
new TestDefaultCultureAccessor(),
Options.Create<GlobalSettings>(globalSettings),
Mock.Of<IUserService>(),
hostingEnvironment,
new UriUtility(hostingEnvironment),
httpContextAccessor,
new AspNetCoreCookieManager(httpContextAccessor),
Mock.Of<IRequestAccessor>(),
backofficeSecurityAccessorMock.Object

View File

@@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;
using Umbraco.Core.Scoping;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
{
[TestFixture]
public class DefaultCachePolicyTests
{
private IScopeAccessor DefaultAccessor
{
get
{
var accessor = new Mock<IScopeAccessor>();
var scope = new Mock<IScope>();
scope.Setup(x => x.RepositoryCacheMode).Returns(RepositoryCacheMode.Default);
accessor.Setup(x => x.AmbientScope).Returns(scope.Object);
return accessor.Object;
}
}
[Test]
public void Caches_Single()
{
var isCached = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback(() =>
{
isCached = true;
});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
AuditItem unused = defaultPolicy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), o => null);
Assert.IsTrue(isCached);
}
[Test]
public void Get_Single_From_Cache()
{
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Get(It.IsAny<string>())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah"));
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
AuditItem found = defaultPolicy.Get(1, id => null, ids => null);
Assert.IsNotNull(found);
}
[Test]
public void Caches_Per_Id_For_Get_All()
{
var cached = new List<string>();
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback((string cacheKey, Func<object> o, TimeSpan? t, bool b, string[] s) =>
{
cached.Add(cacheKey);
});
cache.Setup(x => x.SearchByKey(It.IsAny<string>())).Returns(new AuditItem[] {});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
AuditItem[] unused = defaultPolicy.GetAll(new object[] {}, ids => new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
});
Assert.AreEqual(2, cached.Count);
}
[Test]
public void Get_All_Without_Ids_From_Cache()
{
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.SearchByKey(It.IsAny<string>())).Returns(new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
AuditItem[] found = defaultPolicy.GetAll(new object[] {}, ids => new[] { (AuditItem)null });
Assert.AreEqual(2, found.Length);
}
[Test]
public void If_CreateOrUpdate_Throws_Cache_Is_Removed()
{
var cacheCleared = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Clear(It.IsAny<string>()))
.Callback(() =>
{
cacheCleared = true;
});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
try
{
defaultPolicy.Update(new AuditItem(1, AuditType.Copy, 123, "test", "blah"), item => throw new Exception("blah!"));
}
catch
{
//we need this catch or nunit throw up
}
finally
{
Assert.IsTrue(cacheCleared);
}
}
[Test]
public void If_Removes_Throws_Cache_Is_Removed()
{
var cacheCleared = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Clear(It.IsAny<string>()))
.Callback(() =>
{
cacheCleared = true;
});
var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
try
{
defaultPolicy.Delete(new AuditItem(1, AuditType.Copy, 123, "test", "blah"), item => throw new Exception("blah!"));
}
catch
{
//we need this catch or nunit throw up
}
finally
{
Assert.IsTrue(cacheCleared);
}
}
}
}

View File

@@ -0,0 +1,222 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Collections;
using Umbraco.Core.Models;
using Umbraco.Core.Scoping;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
{
[TestFixture]
public class FullDataSetCachePolicyTests
{
private IScopeAccessor DefaultAccessor
{
get
{
var accessor = new Mock<IScopeAccessor>();
var scope = new Mock<IScope>();
scope.Setup(x => x.RepositoryCacheMode).Returns(RepositoryCacheMode.Default);
accessor.Setup(x => x.AmbientScope).Returns(scope.Object);
return accessor.Object;
}
}
[Test]
public void Caches_Single()
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
};
var isCached = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback(() =>
{
isCached = true;
});
var policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var unused = policy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), ids => getAll);
Assert.IsTrue(isCached);
}
[Test]
public void Get_Single_From_Cache()
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
};
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Get(It.IsAny<string>())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah"));
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var found = defaultPolicy.Get(1, id => null, ids => getAll);
Assert.IsNotNull(found);
}
[Test]
public void Get_All_Caches_Empty_List()
{
var getAll = new AuditItem[] {};
var cached = new List<string>();
IList list = null;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback((string cacheKey, Func<object> o, TimeSpan? t, bool b, string[] s) =>
{
cached.Add(cacheKey);
list = o() as IList;
});
cache.Setup(x => x.Get(It.IsAny<string>())).Returns(() =>
{
//return null if this is the first pass
return cached.Any() ? new DeepCloneableList<AuditItem>(ListCloneBehavior.CloneOnce) : null;
});
var policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var found = policy.GetAll(new object[] {}, ids => getAll);
Assert.AreEqual(1, cached.Count);
Assert.IsNotNull(list);
//Do it again, ensure that its coming from the cache!
policy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
found = policy.GetAll(new object[] { }, ids => getAll);
Assert.AreEqual(1, cached.Count);
Assert.IsNotNull(list);
}
[Test]
public void Get_All_Caches_As_Single_List()
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
};
var cached = new List<string>();
IList list = null;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback((string cacheKey, Func<object> o, TimeSpan? t, bool b, string[] s) =>
{
cached.Add(cacheKey);
list = o() as IList;
});
cache.Setup(x => x.Get(It.IsAny<string>())).Returns(new AuditItem[] { });
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var found = defaultPolicy.GetAll(new object[] { }, ids => getAll);
Assert.AreEqual(1, cached.Count);
Assert.IsNotNull(list);
}
[Test]
public void Get_All_Without_Ids_From_Cache()
{
var getAll = new[] { (AuditItem)null };
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Get(It.IsAny<string>())).Returns(() => new DeepCloneableList<AuditItem>(ListCloneBehavior.CloneOnce)
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
});
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
var found = defaultPolicy.GetAll(new object[] { }, ids => getAll);
Assert.AreEqual(2, found.Length);
}
[Test]
public void If_CreateOrUpdate_Throws_Cache_Is_Removed()
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
};
var cacheCleared = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Clear(It.IsAny<string>()))
.Callback(() =>
{
cacheCleared = true;
});
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
try
{
defaultPolicy.Update(new AuditItem(1, AuditType.Copy, 123, "test", "blah"), item => { throw new Exception("blah!"); });
}
catch
{
//we need this catch or nunit throw up
}
finally
{
Assert.IsTrue(cacheCleared);
}
}
[Test]
public void If_Removes_Throws_Cache_Is_Removed()
{
var getAll = new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
};
var cacheCleared = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Clear(It.IsAny<string>()))
.Callback(() =>
{
cacheCleared = true;
});
var defaultPolicy = new FullDataSetRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, item => item.Id, false);
try
{
defaultPolicy.Delete(new AuditItem(1, AuditType.Copy, 123, "test", "blah"), item => { throw new Exception("blah!"); });
}
catch
{
//we need this catch or nunit throw up
}
finally
{
Assert.IsTrue(cacheCleared);
}
}
}
}

View File

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

View File

@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;
using Umbraco.Core.Scoping;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Cache
{
[TestFixture]
public class SingleItemsOnlyCachePolicyTests
{
private IScopeAccessor DefaultAccessor
{
get
{
var accessor = new Mock<IScopeAccessor>();
var scope = new Mock<IScope>();
scope.Setup(x => x.RepositoryCacheMode).Returns(RepositoryCacheMode.Default);
accessor.Setup(x => x.AmbientScope).Returns(scope.Object);
return accessor.Object;
}
}
[Test]
public void Get_All_Doesnt_Cache()
{
var cached = new List<string>();
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback((string cacheKey, Func<object> o, TimeSpan? t, bool b, string[] s) =>
{
cached.Add(cacheKey);
});
cache.Setup(x => x.SearchByKey(It.IsAny<string>())).Returns(new AuditItem[] { });
var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var unused = defaultPolicy.GetAll(new object[] { }, ids => new[]
{
new AuditItem(1, AuditType.Copy, 123, "test", "blah"),
new AuditItem(2, AuditType.Copy, 123, "test", "blah2")
});
Assert.AreEqual(0, cached.Count);
}
[Test]
public void Caches_Single()
{
var isCached = false;
var cache = new Mock<IAppPolicyCache>();
cache.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(), It.IsAny<string[]>()))
.Callback(() =>
{
isCached = true;
});
var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy<AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());
var unused = defaultPolicy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), ids => null);
Assert.IsTrue(isCached);
}
}
}

View File

@@ -68,7 +68,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
private static TypeLoader MockTypeLoader()
{
var ioHelper = IOHelper;
return new TypeLoader(Mock.Of<ITypeFinder>(), Mock.Of<IAppPolicyCache>(), new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot("~/App_Data/TEMP")), Mock.Of<ILogger<TypeLoader>>(), Mock.Of<IProfilingLogger>());
return new TypeLoader(Mock.Of<ITypeFinder>(), Mock.Of<IAppPolicyCache>(), new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of<ILogger<TypeLoader>>(), Mock.Of<IProfilingLogger>());
}
@@ -390,7 +390,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Components
public void AllComposers()
{
var typeFinder = TestHelper.GetTypeFinder();
var typeLoader = new TypeLoader(typeFinder, AppCaches.Disabled.RuntimeCache, new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot("~/App_Data/TEMP")), Mock.Of<ILogger<TypeLoader>>(), Mock.Of<IProfilingLogger>());
var typeLoader = new TypeLoader(typeFinder, AppCaches.Disabled.RuntimeCache, new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of<ILogger<TypeLoader>>(), Mock.Of<IProfilingLogger>());
var register = MockRegister();
var builder = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());

View File

@@ -1,9 +1,10 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
@@ -23,7 +24,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
ProfilingLogger = new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>());
var typeFinder = TestHelper.GetTypeFinder();
TypeLoader = new TypeLoader(typeFinder, NoAppCache.Instance, new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot("~/App_Data/TEMP")), Mock.Of<ILogger<TypeLoader>>(), ProfilingLogger, false, AssembliesToScan);
TypeLoader = new TypeLoader(typeFinder, NoAppCache.Instance, new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of<ILogger<TypeLoader>>(), ProfilingLogger, false, AssembliesToScan);
}
protected virtual IEnumerable<Assembly> AssembliesToScan

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -28,7 +28,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Composing
// this ensures it's reset
var typeFinder = TestHelper.GetTypeFinder();
_typeLoader = new TypeLoader(typeFinder, NoAppCache.Instance,
new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot("~/App_Data/TEMP")),
new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)),
Mock.Of<ILogger<TypeLoader>>(), new ProfilingLogger(Mock.Of<ILogger<ProfilingLogger>>(), Mock.Of<IProfiler>()), false,
// for testing, we'll specify which assemblies are scanned for the PluginTypeResolver

View File

@@ -0,0 +1,191 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.DependencyInjection;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Serialization;
using Umbraco.Core.Services;
using Umbraco.Core.Strings;
using Umbraco.Tests.Common.PublishedContent;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.UnitTests.TestHelpers;
using Umbraco.Web.PublishedCache;
namespace Umbraco.Tests.Published
{
[TestFixture]
public class ConvertersTests
{
[Test]
public void SimpleConverter3Test()
{
var register = new ServiceCollection();
var composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
composition.WithCollectionBuilder<PropertyValueConverterCollectionBuilder>()
.Append<SimpleConverter3A>()
.Append<SimpleConverter3B>();
IPublishedModelFactory factory = new PublishedModelFactory(
new[]
{
typeof(PublishedSnapshotTestObjects.TestElementModel1),
typeof(PublishedSnapshotTestObjects.TestElementModel2),
typeof(PublishedSnapshotTestObjects.TestContentModel1),
typeof(PublishedSnapshotTestObjects.TestContentModel2)
}, Mock.Of<IPublishedValueFallback>());
register.AddTransient(f => factory);
var cacheMock = new Mock<IPublishedContentCache>();
var cacheContent = new Dictionary<int, IPublishedContent>();
cacheMock.Setup(x => x.GetById(It.IsAny<int>())).Returns<int>(id =>
cacheContent.TryGetValue(id, out IPublishedContent content) ? content : null);
var publishedSnapshotMock = new Mock<IPublishedSnapshot>();
publishedSnapshotMock.Setup(x => x.Content).Returns(cacheMock.Object);
var publishedSnapshotAccessorMock = new Mock<IPublishedSnapshotAccessor>();
publishedSnapshotAccessorMock.Setup(x => x.PublishedSnapshot).Returns(publishedSnapshotMock.Object);
register.AddTransient(f => publishedSnapshotAccessorMock.Object);
IServiceProvider registerFactory = composition.CreateServiceProvider();
PropertyValueConverterCollection converters =
registerFactory.GetRequiredService<PropertyValueConverterCollection>();
var serializer = new ConfigurationEditorJsonSerializer();
var dataTypeServiceMock = new Mock<IDataTypeService>();
var dataType1 = new DataType(new VoidEditor(NullLoggerFactory.Instance, dataTypeServiceMock.Object,
Mock.Of<ILocalizationService>(), Mock.Of<ILocalizedTextService>(), Mock.Of<IShortStringHelper>(), new JsonNetSerializer()),
serializer) { Id = 1 };
var dataType2 = new DataType(new VoidEditor("2", NullLoggerFactory.Instance, Mock.Of<IDataTypeService>(),
Mock.Of<ILocalizationService>(), Mock.Of<ILocalizedTextService>(), Mock.Of<IShortStringHelper>(), new JsonNetSerializer()),
serializer) { Id = 2 };
dataTypeServiceMock.Setup(x => x.GetAll()).Returns(new[] { dataType1, dataType2 });
var contentTypeFactory = new PublishedContentTypeFactory(factory, converters, dataTypeServiceMock.Object);
IEnumerable<IPublishedPropertyType> CreatePropertyTypes(IPublishedContentType contentType, int i)
{
yield return contentTypeFactory.CreatePropertyType(contentType, "prop" + i, i);
}
IPublishedContentType elementType1 =
contentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "element1", t => CreatePropertyTypes(t, 1));
IPublishedContentType elementType2 =
contentTypeFactory.CreateContentType(Guid.NewGuid(), 1001, "element2", t => CreatePropertyTypes(t, 2));
IPublishedContentType contentType1 =
contentTypeFactory.CreateContentType(Guid.NewGuid(), 1002, "content1", t => CreatePropertyTypes(t, 1));
IPublishedContentType contentType2 =
contentTypeFactory.CreateContentType(Guid.NewGuid(), 1003, "content2", t => CreatePropertyTypes(t, 2));
var element1 = new PublishedElement(elementType1, Guid.NewGuid(),
new Dictionary<string, object> { { "prop1", "val1" } }, false);
var element2 = new PublishedElement(elementType2, Guid.NewGuid(),
new Dictionary<string, object> { { "prop2", "1003" } }, false);
var cnt1 = new SolidPublishedContent(contentType1)
{
Id = 1003,
Properties = new[]
{
new SolidPublishedProperty { Alias = "prop1", SolidHasValue = true, SolidValue = "val1" }
}
};
var cnt2 = new SolidPublishedContent(contentType1)
{
Id = 1004,
Properties = new[]
{
new SolidPublishedProperty { Alias = "prop2", SolidHasValue = true, SolidValue = "1003" }
}
};
IPublishedModelFactory publishedModelFactory = registerFactory.GetRequiredService<IPublishedModelFactory>();
cacheContent[cnt1.Id] = cnt1.CreateModel(publishedModelFactory);
cacheContent[cnt2.Id] = cnt2.CreateModel(publishedModelFactory);
// can get the actual property Clr type
// ie ModelType gets properly mapped by IPublishedContentModelFactory
// must test ModelClrType with special equals 'cos they are not ref-equals
Assert.IsTrue(ModelType.Equals(typeof(IEnumerable<>).MakeGenericType(ModelType.For("content1")),
contentType2.GetPropertyType("prop2").ModelClrType));
Assert.AreEqual(typeof(IEnumerable<PublishedSnapshotTestObjects.TestContentModel1>),
contentType2.GetPropertyType("prop2").ClrType);
// can create a model for an element
IPublishedElement model1 = factory.CreateModel(element1);
Assert.IsInstanceOf<PublishedSnapshotTestObjects.TestElementModel1>(model1);
Assert.AreEqual("val1", ((PublishedSnapshotTestObjects.TestElementModel1)model1).Prop1);
// can create a model for a published content
IPublishedElement model2 = factory.CreateModel(element2);
Assert.IsInstanceOf<PublishedSnapshotTestObjects.TestElementModel2>(model2);
var mmodel2 = (PublishedSnapshotTestObjects.TestElementModel2)model2;
// and get direct property
Assert.IsInstanceOf<PublishedSnapshotTestObjects.TestContentModel1[]>(
model2.Value(Mock.Of<IPublishedValueFallback>(), "prop2"));
Assert.AreEqual(1,
((PublishedSnapshotTestObjects.TestContentModel1[])model2.Value(Mock.Of<IPublishedValueFallback>(),
"prop2")).Length);
// and get model property
Assert.IsInstanceOf<IEnumerable<PublishedSnapshotTestObjects.TestContentModel1>>(mmodel2.Prop2);
Assert.IsInstanceOf<PublishedSnapshotTestObjects.TestContentModel1[]>(mmodel2.Prop2);
PublishedSnapshotTestObjects.TestContentModel1 mmodel1 = mmodel2.Prop2.First();
// and we get what we want
Assert.AreSame(cacheContent[mmodel1.Id], mmodel1);
}
public class SimpleConverter3A : PropertyValueConverterBase
{
public override bool IsConverter(IPublishedPropertyType propertyType)
=> propertyType.EditorAlias == "Umbraco.Void";
public override Type GetPropertyValueType(IPublishedPropertyType propertyType)
=> typeof(string);
public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType)
=> PropertyCacheLevel.Element;
}
public class SimpleConverter3B : PropertyValueConverterBase
{
private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor;
public SimpleConverter3B(IPublishedSnapshotAccessor publishedSnapshotAccessor) =>
_publishedSnapshotAccessor = publishedSnapshotAccessor;
public override bool IsConverter(IPublishedPropertyType propertyType)
=> propertyType.EditorAlias == "Umbraco.Void.2";
public override Type GetPropertyValueType(IPublishedPropertyType propertyType)
=> typeof(IEnumerable<>).MakeGenericType(ModelType.For("content1"));
public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType)
=> PropertyCacheLevel.Elements;
public override object ConvertSourceToIntermediate(IPublishedElement owner,
IPublishedPropertyType propertyType, object source, bool preview)
{
var s = source as string;
return s?.Split(',').Select(int.Parse).ToArray() ?? Array.Empty<int>();
}
public override object ConvertIntermediateToObject(IPublishedElement owner,
IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter,
bool preview) => ((int[])inter).Select(x =>
(PublishedSnapshotTestObjects.TestContentModel1)_publishedSnapshotAccessor.PublishedSnapshot.Content
.GetById(x)).ToArray();
}
}
}

View File

@@ -0,0 +1,126 @@
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Migrations;
using Umbraco.Tests.Migrations.Stubs;
using Umbraco.Tests.Testing;
namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations
{
[TestFixture]
public class AlterMigrationTests
{
private readonly ILogger<MigrationContext> _logger = Mock.Of<ILogger<MigrationContext>>();
[Test]
public void Drop_Foreign_Key()
{
// Arrange
var database = new TestDatabase();
var context = new MigrationContext(database, _logger);
var stub = new DropForeignKeyMigrationStub(context);
// Act
stub.Migrate();
foreach (TestDatabase.Operation op in database.Operations)
{
Console.WriteLine("{0}\r\n\t{1}", op.Text, op.Sql);
}
// Assert
Assert.That(database.Operations.Count, Is.EqualTo(1));
Assert.That(database.Operations[0].Sql,
Is.EqualTo("ALTER TABLE [umbracoUser2app] DROP CONSTRAINT [FK_umbracoUser2app_umbracoUser_id]"));
}
[Test]
public void CreateColumn()
{
var database = new TestDatabase();
var context = new MigrationContext(database, _logger);
var migration = new CreateColumnMigration(context);
migration.Migrate();
foreach (TestDatabase.Operation op in database.Operations)
{
Console.WriteLine("{0}\r\n\t{1}", op.Text, op.Sql);
}
Assert.That(database.Operations.Count, Is.EqualTo(1));
Assert.That(database.Operations[0].Sql,
Is.EqualTo("ALTER TABLE [bar] ADD [foo] UniqueIdentifier NOT NULL"));
}
public class CreateColumnMigration : MigrationBase
{
public CreateColumnMigration(IMigrationContext context)
: base(context)
{
}
public override void Migrate() => Alter.Table("bar").AddColumn("foo").AsGuid().Do();
}
[Test]
public void AlterColumn()
{
var database = new TestDatabase();
var context = new MigrationContext(database, _logger);
var migration = new AlterColumnMigration(context);
migration.Migrate();
foreach (TestDatabase.Operation op in database.Operations)
{
Console.WriteLine("{0}\r\n\t{1}", op.Text, op.Sql);
}
Assert.That(database.Operations.Count, Is.EqualTo(1));
Assert.That(database.Operations[0].Sql,
Is.EqualTo("ALTER TABLE [bar] ALTER COLUMN [foo] UniqueIdentifier NOT NULL"));
}
public class AlterColumnMigration : MigrationBase
{
public AlterColumnMigration(IMigrationContext context)
: base(context)
{
}
public override void Migrate() =>
// bad/good syntax...
//Alter.Column("foo").OnTable("bar").AsGuid().NotNullable();
Alter.Table("bar").AlterColumn("foo").AsGuid().NotNullable().Do();
}
[Ignore("this doesn't actually test anything")]
[Test]
public void Can_Get_Up_Migration_From_MigrationStub()
{
// Arrange
var database = new TestDatabase();
var context = new MigrationContext(database, _logger);
var stub = new AlterUserTableMigrationStub(context);
// Act
stub.Migrate();
// Assert
Assert.That(database.Operations.Any(), Is.True);
//Console output
Debug.Print("Number of expressions in context: {0}", database.Operations.Count);
Debug.Print("");
foreach (TestDatabase.Operation expression in database.Operations)
{
Debug.Print(expression.ToString());
}
}
}
}

View File

@@ -0,0 +1,235 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using NPoco;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Migrations;
using Umbraco.Core.Migrations.Upgrade;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Scoping;
using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.Testing;
namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations
{
[TestFixture]
public class MigrationPlanTests
{
[Test]
public void CanExecute()
{
NullLoggerFactory loggerFactory = NullLoggerFactory.Instance;
var database = new TestDatabase();
IScope scope = Mock.Of<IScope>();
Mock.Get(scope)
.Setup(x => x.Database)
.Returns(database);
var sqlContext = new SqlContext(new SqlServerSyntaxProvider(), DatabaseType.SQLCe,
Mock.Of<IPocoDataFactory>());
var scopeProvider = new MigrationTests.TestScopeProvider(scope) { SqlContext = sqlContext };
IMigrationBuilder migrationBuilder = Mock.Of<IMigrationBuilder>();
Mock.Get(migrationBuilder)
.Setup(x => x.Build(It.IsAny<Type>(), It.IsAny<IMigrationContext>()))
.Returns<Type, IMigrationContext>((t, c) =>
{
switch (t.Name)
{
case "DeleteRedirectUrlTable":
return new DeleteRedirectUrlTable(c);
case "NoopMigration":
return new NoopMigration();
default:
throw new NotSupportedException();
}
});
MigrationPlan plan = new MigrationPlan("default")
.From(string.Empty)
.To<DeleteRedirectUrlTable>("{4A9A1A8F-0DA1-4BCF-AD06-C19D79152E35}")
.To<NoopMigration>("VERSION.33");
IKeyValueService kvs = Mock.Of<IKeyValueService>();
Mock.Get(kvs).Setup(x => x.GetValue(It.IsAny<string>()))
.Returns<string>(k => k == "Umbraco.Tests.MigrationPlan" ? string.Empty : null);
string state;
using (IScope s = scopeProvider.CreateScope())
{
// read current state
var sourceState = kvs.GetValue("Umbraco.Tests.MigrationPlan") ?? string.Empty;
// execute plan
state = plan.Execute(s, sourceState, migrationBuilder, loggerFactory.CreateLogger<MigrationPlan>(),
loggerFactory);
// save new state
kvs.SetValue("Umbraco.Tests.MigrationPlan", sourceState, state);
s.Complete();
}
Assert.AreEqual("VERSION.33", state);
Assert.AreEqual(1, database.Operations.Count);
Assert.AreEqual("DROP TABLE [umbracoRedirectUrl]", database.Operations[0].Sql);
}
[Test]
public void CanAddMigrations()
{
var plan = new MigrationPlan("default");
plan
.From(string.Empty)
.To("aaa")
.To("bbb")
.To("ccc");
}
[Test]
public void CannotTransitionToSameState()
{
var plan = new MigrationPlan("default");
Assert.Throws<ArgumentException>(() =>
{
plan.From("aaa").To("aaa");
});
}
[Test]
public void OnlyOneTransitionPerState()
{
var plan = new MigrationPlan("default");
plan.From("aaa").To("bbb");
Assert.Throws<InvalidOperationException>(() =>
{
plan.From("aaa").To("ccc");
});
}
[Test]
public void CannotContainTwoMoreHeads()
{
var plan = new MigrationPlan("default");
plan
.From(string.Empty)
.To("aaa")
.To("bbb")
.From("ccc")
.To("ddd");
Assert.Throws<InvalidOperationException>(() => plan.Validate());
}
[Test]
public void CannotContainLoops()
{
var plan = new MigrationPlan("default");
plan
.From("aaa")
.To("bbb")
.To("ccc")
.To("aaa");
Assert.Throws<InvalidOperationException>(() => plan.Validate());
}
[Test]
public void ValidateUmbracoPlan()
{
var plan = new UmbracoPlan(TestHelper.GetUmbracoVersion());
plan.Validate();
Console.WriteLine(plan.FinalState);
Assert.IsFalse(plan.FinalState.IsNullOrWhiteSpace());
}
[Test]
public void CanClone()
{
var plan = new MigrationPlan("default");
plan
.From(string.Empty)
.To("aaa")
.To("bbb")
.To("ccc")
.To("ddd")
.To("eee");
plan
.From("xxx")
.ToWithClone("bbb", "ddd", "yyy")
.To("eee");
WritePlanToConsole(plan);
plan.Validate();
Assert.AreEqual("eee", plan.FollowPath("xxx").Last());
Assert.AreEqual("yyy", plan.FollowPath("xxx", "yyy").Last());
}
[Test]
public void CanMerge()
{
var plan = new MigrationPlan("default");
plan
.From(string.Empty)
.To("aaa")
.Merge()
.To("bbb")
.To("ccc")
.With()
.To("ddd")
.To("eee")
.As("fff")
.To("ggg");
WritePlanToConsole(plan);
plan.Validate();
AssertList(plan.FollowPath(), "", "aaa", "bbb", "ccc", "*", "*", "fff", "ggg");
AssertList(plan.FollowPath("ccc"), "ccc", "*", "*", "fff", "ggg");
AssertList(plan.FollowPath("eee"), "eee", "*", "*", "fff", "ggg");
}
private void AssertList(IReadOnlyList<string> states, params string[] expected)
{
Assert.AreEqual(expected.Length, states.Count, string.Join(", ", states));
for (var i = 0; i < expected.Length; i++)
{
if (expected[i] != "*")
{
Assert.AreEqual(expected[i], states[i], "at:" + i);
}
}
}
private void WritePlanToConsole(MigrationPlan plan)
{
var final = plan.Transitions.First(x => x.Value == null).Key;
Console.WriteLine("plan \"{0}\" to final state \"{1}\":", plan.Name, final);
foreach ((var _, MigrationPlan.Transition transition) in plan.Transitions)
{
if (transition != null)
{
Console.WriteLine(transition);
}
}
}
public class DeleteRedirectUrlTable : MigrationBase
{
public DeleteRedirectUrlTable(IMigrationContext context)
: base(context)
{
}
public override void Migrate() => Delete.Table("umbracoRedirectUrl").Do();
}
}
}

View File

@@ -0,0 +1,117 @@
using System;
using System.Data;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Events;
using Umbraco.Core.Migrations;
using Umbraco.Core.Persistence;
using Umbraco.Core.Scoping;
namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations
{
[TestFixture]
public class MigrationTests
{
public class TestScopeProvider : IScopeProvider
{
private readonly IScope _scope;
public TestScopeProvider(IScope scope) => _scope = scope;
public IScope CreateScope(
IsolationLevel isolationLevel = IsolationLevel.Unspecified,
RepositoryCacheMode repositoryCacheMode = RepositoryCacheMode.Unspecified,
IEventDispatcher eventDispatcher = null,
bool? scopeFileSystems = null,
bool callContext = false,
bool autoComplete = false) => _scope;
public IScope CreateDetachedScope(
IsolationLevel isolationLevel = IsolationLevel.Unspecified,
RepositoryCacheMode repositoryCacheMode = RepositoryCacheMode.Unspecified,
IEventDispatcher eventDispatcher = null,
bool? scopeFileSystems = null) => throw new NotImplementedException();
public void AttachScope(IScope scope, bool callContext = false) => throw new NotImplementedException();
public IScope DetachScope() => throw new NotImplementedException();
public IScopeContext Context { get; set; }
public ISqlContext SqlContext { get; set; }
#if DEBUG_SCOPES
public ScopeInfo GetScopeInfo(IScope scope)
{
throw new NotImplementedException();
}
public IEnumerable<ScopeInfo> ScopeInfos => throw new NotImplementedException();
#endif
}
[Test]
public void RunGoodMigration()
{
var migrationContext =
new MigrationContext(Mock.Of<IUmbracoDatabase>(), Mock.Of<ILogger<MigrationContext>>());
IMigration migration = new GoodMigration(migrationContext);
migration.Migrate();
}
[Test]
public void DetectBadMigration1()
{
var migrationContext =
new MigrationContext(Mock.Of<IUmbracoDatabase>(), Mock.Of<ILogger<MigrationContext>>());
IMigration migration = new BadMigration1(migrationContext);
Assert.Throws<IncompleteMigrationExpressionException>(() => migration.Migrate());
}
[Test]
public void DetectBadMigration2()
{
var migrationContext =
new MigrationContext(Mock.Of<IUmbracoDatabase>(), Mock.Of<ILogger<MigrationContext>>());
IMigration migration = new BadMigration2(migrationContext);
Assert.Throws<IncompleteMigrationExpressionException>(() => migration.Migrate());
}
public class GoodMigration : MigrationBase
{
public GoodMigration(IMigrationContext context)
: base(context)
{
}
public override void Migrate() => Execute.Sql("").Do();
}
public class BadMigration1 : MigrationBase
{
public BadMigration1(IMigrationContext context)
: base(context)
{
}
public override void Migrate() => Alter.Table("foo"); // stop here, don't Do it
}
public class BadMigration2 : MigrationBase
{
public BadMigration2(IMigrationContext context)
: base(context)
{
}
public override void Migrate()
{
Alter.Table("foo"); // stop here, don't Do it
// and try to start another one
Alter.Table("bar");
}
}
}
}

View File

@@ -0,0 +1,147 @@
using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using NPoco;
using NUnit.Framework;
using Umbraco.Core.Migrations;
using Umbraco.Core.Migrations.Upgrade;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Scoping;
using Umbraco.Core.Services;
using Umbraco.Tests.Testing;
namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.Migrations
{
[TestFixture]
public class PostMigrationTests
{
private static readonly ILoggerFactory s_loggerFactory = NullLoggerFactory.Instance;
[Test]
public void ExecutesPlanPostMigration()
{
IMigrationBuilder builder = Mock.Of<IMigrationBuilder>();
Mock.Get(builder)
.Setup(x => x.Build(It.IsAny<Type>(), It.IsAny<IMigrationContext>()))
.Returns<Type, IMigrationContext>((t, c) =>
{
switch (t.Name)
{
case nameof(NoopMigration):
return new NoopMigration();
case nameof(TestPostMigration):
return new TestPostMigration();
default:
throw new NotSupportedException();
}
});
var database = new TestDatabase();
IScope scope = Mock.Of<IScope>();
Mock.Get(scope)
.Setup(x => x.Database)
.Returns(database);
var sqlContext = new SqlContext(
new SqlServerSyntaxProvider(),
DatabaseType.SQLCe,
Mock.Of<IPocoDataFactory>());
var scopeProvider = new MigrationTests.TestScopeProvider(scope) { SqlContext = sqlContext };
MigrationPlan plan = new MigrationPlan("Test")
.From(string.Empty).To("done");
plan.AddPostMigration<TestPostMigration>();
TestPostMigration.MigrateCount = 0;
var upgrader = new Upgrader(plan);
upgrader.Execute(
scopeProvider,
builder,
Mock.Of<IKeyValueService>(),
s_loggerFactory.CreateLogger<Upgrader>(),
s_loggerFactory);
Assert.AreEqual(1, TestPostMigration.MigrateCount);
}
[Test]
public void MigrationCanAddPostMigration()
{
IMigrationBuilder builder = Mock.Of<IMigrationBuilder>();
Mock.Get(builder)
.Setup(x => x.Build(It.IsAny<Type>(), It.IsAny<IMigrationContext>()))
.Returns<Type, IMigrationContext>((t, c) =>
{
switch (t.Name)
{
case nameof(NoopMigration):
return new NoopMigration();
case nameof(TestMigration):
return new TestMigration(c);
case nameof(TestPostMigration):
return new TestPostMigration();
default:
throw new NotSupportedException();
}
});
var database = new TestDatabase();
IScope scope = Mock.Of<IScope>();
Mock.Get(scope)
.Setup(x => x.Database)
.Returns(database);
var sqlContext = new SqlContext(
new SqlServerSyntaxProvider(),
DatabaseType.SQLCe,
Mock.Of<IPocoDataFactory>());
var scopeProvider = new MigrationTests.TestScopeProvider(scope) { SqlContext = sqlContext };
MigrationPlan plan = new MigrationPlan("Test")
.From(string.Empty).To<TestMigration>("done");
TestMigration.MigrateCount = 0;
TestPostMigration.MigrateCount = 0;
new MigrationContext(database, s_loggerFactory.CreateLogger<MigrationContext>());
var upgrader = new Upgrader(plan);
upgrader.Execute(
scopeProvider,
builder,
Mock.Of<IKeyValueService>(),
s_loggerFactory.CreateLogger<Upgrader>(),
s_loggerFactory);
Assert.AreEqual(1, TestMigration.MigrateCount);
Assert.AreEqual(1, TestPostMigration.MigrateCount);
}
public class TestMigration : MigrationBase
{
public TestMigration(IMigrationContext context)
: base(context)
{
}
public static int MigrateCount { get; set; }
public override void Migrate()
{
MigrateCount++;
Context.AddPostMigration<TestPostMigration>();
}
}
public class TestPostMigration : IMigration
{
public static int MigrateCount { get; set; }
public void Migrate() => MigrateCount++;
}
}
}

View File

@@ -0,0 +1,19 @@
using Umbraco.Core.Migrations;
namespace Umbraco.Tests.Migrations.Stubs
{
public class AlterUserTableMigrationStub : MigrationBase
{
public AlterUserTableMigrationStub(IMigrationContext context)
: base(context)
{ }
public override void Migrate()
{
Alter.Table("umbracoUser")
.AddColumn("Birthday")
.AsDateTime()
.Nullable();
}
}
}

View File

@@ -0,0 +1,16 @@
using Umbraco.Core.Migrations;
namespace Umbraco.Tests.Migrations.Stubs
{
public class DropForeignKeyMigrationStub : MigrationBase
{
public DropForeignKeyMigrationStub(IMigrationContext context)
: base(context)
{ }
public override void Migrate()
{
Delete.ForeignKey().FromTable("umbracoUser2app").ForeignColumn("user").ToTable("umbracoUser").PrimaryColumn("id").Do();
}
}
}

View File

@@ -0,0 +1,16 @@
using Umbraco.Core.Migrations;
namespace Umbraco.Tests.Migrations.Stubs
{
/// <summary>
/// This is just a dummy class that is used to ensure that implementations
/// of IMigration is not found if it doesn't have the MigrationAttribute (like this class).
/// </summary>
public class Dummy : IMigration
{
public void Migrate()
{
throw new System.NotImplementedException();
}
}
}

View File

@@ -0,0 +1,14 @@
using Umbraco.Core.Migrations;
namespace Umbraco.Tests.Migrations.Stubs
{
public class FiveZeroMigration : MigrationBase
{
public FiveZeroMigration(IMigrationContext context)
: base(context)
{ }
public override void Migrate()
{ }
}
}

View File

@@ -0,0 +1,17 @@
using Umbraco.Core.Migrations;
namespace Umbraco.Tests.Migrations.Stubs
{
public class FourElevenMigration : MigrationBase
{
public FourElevenMigration(IMigrationContext context)
: base(context)
{ }
public override void Migrate()
{
Alter.Table("umbracoUser").AddColumn("companyPhone").AsString(255);
}
}
}

View File

@@ -0,0 +1,17 @@
using Umbraco.Core.Migrations;
namespace Umbraco.Tests.Migrations.Stubs
{
public class SixZeroMigration1 : MigrationBase
{
public SixZeroMigration1(IMigrationContext context)
: base(context)
{ }
public override void Migrate()
{
Alter.Table("umbracoUser").AddColumn("secret").AsString(255);
}
}
}

View File

@@ -0,0 +1,17 @@
using Umbraco.Core.Migrations;
namespace Umbraco.Tests.Migrations.Stubs
{
public class SixZeroMigration2 : MigrationBase
{
public SixZeroMigration2(IMigrationContext context)
: base(context)
{ }
public override void Migrate()
{
Alter.Table("umbracoUser").AddColumn("secondEmail").AsString(255);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -8,6 +8,7 @@
<ItemGroup>
<ProjectReference Include="..\Umbraco.ModelsBuilder.Embedded\Umbraco.ModelsBuilder.Embedded.csproj" />
<ProjectReference Include="..\Umbraco.PublishedCache.NuCache\Umbraco.PublishedCache.NuCache.csproj" />
<ProjectReference Include="..\Umbraco.Tests.Common\Umbraco.Tests.Common.csproj" />
<ProjectReference Include="..\Umbraco.Web.BackOffice\Umbraco.Web.BackOffice.csproj" />
<ProjectReference Include="..\Umbraco.Web.Common\Umbraco.Web.Common.csproj" />

View File

@@ -1,4 +1,4 @@
using System.Threading.Tasks;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
@@ -38,7 +38,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers
[Test]
public void Can_Construct_And_Get_Result()
{
var httpContextAccessor = Mock.Of<IHttpContextAccessor>();
var hostingEnvironment = Mock.Of<IHostingEnvironment>();
var backofficeSecurityAccessor = Mock.Of<IBackOfficeSecurityAccessor>();
Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of<IBackOfficeSecurity>());
@@ -50,10 +49,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers
new TestVariationContextAccessor(),
new TestDefaultCultureAccessor(),
Options.Create(globalSettings),
Mock.Of<IUserService>(),
hostingEnvironment,
new UriUtility(hostingEnvironment),
httpContextAccessor,
Mock.Of<ICookieManager>(),
Mock.Of<IRequestAccessor>(),
backofficeSecurityAccessor);
@@ -74,7 +71,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers
public void Umbraco_Context_Not_Null()
{
var globalSettings = new GlobalSettings();
var httpContextAccessor = Mock.Of<IHttpContextAccessor>();
var hostingEnvironment = Mock.Of<IHostingEnvironment>();
var backofficeSecurityAccessor = Mock.Of<IBackOfficeSecurityAccessor>();
Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of<IBackOfficeSecurity>());
@@ -84,10 +80,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers
new TestVariationContextAccessor(),
new TestDefaultCultureAccessor(),
Options.Create(globalSettings),
Mock.Of<IUserService>(),
hostingEnvironment,
new UriUtility(hostingEnvironment),
httpContextAccessor,
Mock.Of<ICookieManager>(),
Mock.Of<IRequestAccessor>(),
backofficeSecurityAccessor);
@@ -112,7 +106,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers
var backofficeSecurityAccessor = Mock.Of<IBackOfficeSecurityAccessor>();
Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of<IBackOfficeSecurity>());
var publishedSnapshotService = new Mock<IPublishedSnapshotService>();
var httpContextAccessor = Mock.Of<IHttpContextAccessor>();
var hostingEnvironment = Mock.Of<IHostingEnvironment>();
var globalSettings = new GlobalSettings();
@@ -122,10 +115,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers
new TestVariationContextAccessor(),
new TestDefaultCultureAccessor(),
Options.Create(globalSettings),
Mock.Of<IUserService>(),
hostingEnvironment,
new UriUtility(hostingEnvironment),
httpContextAccessor,
Mock.Of<ICookieManager>(),
Mock.Of<IRequestAccessor>(),
backofficeSecurityAccessor);
@@ -150,7 +141,6 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers
public void Mock_Current_Page()
{
var globalSettings = new GlobalSettings();
var httpContextAccessor = Mock.Of<IHttpContextAccessor>();
var hostingEnvironment = Mock.Of<IHostingEnvironment>();
var backofficeSecurityAccessor = Mock.Of<IBackOfficeSecurityAccessor>();
Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of<IBackOfficeSecurity>());
@@ -160,10 +150,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Website.Controllers
new TestVariationContextAccessor(),
new TestDefaultCultureAccessor(),
Options.Create(globalSettings),
Mock.Of<IUserService>(),
hostingEnvironment,
new UriUtility(hostingEnvironment),
httpContextAccessor,
Mock.Of<ICookieManager>(),
Mock.Of<IRequestAccessor>(),
backofficeSecurityAccessor);