Merge pull request #8008 from electricsheep/feature/netcore-misc-unit-tests

Netcore: #7898 Migrate Misc tests to new test project
This commit is contained in:
Bjarke Berg
2020-05-04 10:20:05 +02:00
committed by GitHub
9 changed files with 362 additions and 325 deletions

View File

@@ -0,0 +1,46 @@
using System;
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.UnitTests.Umbraco.Core
{
[TestFixture]
public class DateTimeExtensionsTests
{
[Test]
public void PeriodicMinutesFrom_PostTime_CalculatesMinutesBetween()
{
var nowDateTime = new DateTime(2017, 1, 1, 10, 30, 0);
var scheduledTime = "1145";
var minutesBetween = nowDateTime.PeriodicMinutesFrom(scheduledTime);
Assert.AreEqual(75, minutesBetween);
}
[Test]
public void PeriodicMinutesFrom_PriorTime_CalculatesMinutesBetween()
{
var nowDateTime = new DateTime(2017, 1, 1, 10, 30, 0);
var scheduledTime = "900";
var minutesBetween = nowDateTime.PeriodicMinutesFrom(scheduledTime);
Assert.AreEqual(1350, minutesBetween);
}
[Test]
public void PeriodicMinutesFrom_PriorTime_WithLeadingZero_CalculatesMinutesBetween()
{
var nowDateTime = new DateTime(2017, 1, 1, 10, 30, 0);
var scheduledTime = "0900";
var minutesBetween = nowDateTime.PeriodicMinutesFrom(scheduledTime);
Assert.AreEqual(1350, minutesBetween);
}
[Test]
public void PeriodicMinutesFrom_SameTime_CalculatesMinutesBetween()
{
var nowDateTime = new DateTime(2017, 1, 1, 10, 30, 0);
var scheduledTime = "1030";
var minutesBetween = nowDateTime.PeriodicMinutesFrom(scheduledTime);
Assert.AreEqual(0, minutesBetween);
}
}
}

View File

@@ -0,0 +1,146 @@
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.UnitTests.Umbraco.Core
{
[TestFixture]
public class HashCodeCombinerTests
{
private DirectoryInfo PrepareFolder()
{
var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
var dir = Directory.CreateDirectory(Path.Combine(assDir.FullName, "HashCombiner",
Guid.NewGuid().ToString("N")));
foreach (var f in dir.GetFiles())
{
f.Delete();
}
return dir;
}
[Test]
public void HashCombiner_Test_String()
{
var combiner1 = new HashCodeCombiner();
combiner1.AddCaseInsensitiveString("Hello");
var combiner2 = new HashCodeCombiner();
combiner2.AddCaseInsensitiveString("hello");
Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
combiner2.AddCaseInsensitiveString("world");
Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
}
[Test]
public void HashCombiner_Test_Int()
{
var combiner1 = new HashCodeCombiner();
combiner1.AddInt(1234);
var combiner2 = new HashCodeCombiner();
combiner2.AddInt(1234);
Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
combiner2.AddInt(1);
Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
}
[Test]
public void HashCombiner_Test_DateTime()
{
var dt = DateTime.Now;
var combiner1 = new HashCodeCombiner();
combiner1.AddDateTime(dt);
var combiner2 = new HashCodeCombiner();
combiner2.AddDateTime(dt);
Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
combiner2.AddDateTime(DateTime.Now);
Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
}
[Test]
public void HashCombiner_Test_File()
{
var dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (var file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
file1.WriteLine("hello");
}
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (var file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
//even though files are the same, the dates are different
file2.WriteLine("hello");
}
var combiner1 = new HashCodeCombiner();
combiner1.AddFile(new FileInfo(file1Path));
var combiner2 = new HashCodeCombiner();
combiner2.AddFile(new FileInfo(file1Path));
var combiner3 = new HashCodeCombiner();
combiner3.AddFile(new FileInfo(file2Path));
Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner3.GetCombinedHashCode());
combiner2.AddFile(new FileInfo(file2Path));
Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
}
[Test]
public void HashCombiner_Test_Folder()
{
var dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (var file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
file1.WriteLine("hello");
}
//first test the whole folder
var combiner1 = new HashCodeCombiner();
combiner1.AddFolder(dir);
var combiner2 = new HashCodeCombiner();
combiner2.AddFolder(dir);
Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode());
//now add a file to the folder
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (var file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
//even though files are the same, the dates are different
file2.WriteLine("hello");
}
var combiner3 = new HashCodeCombiner();
combiner3.AddFolder(dir);
Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner3.GetCombinedHashCode());
}
}
}

View File

@@ -0,0 +1,186 @@
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using Umbraco.Core;
namespace Umbraco.Tests.UnitTests.Umbraco.Core
{
[TestFixture]
public class HashGeneratorTests
{
private string Generate(bool isCaseSensitive, params string[] strs)
{
using (var generator = new HashGenerator())
{
foreach (var str in strs)
{
if (isCaseSensitive)
generator.AddString(str);
else
generator.AddCaseInsensitiveString(str);
}
return generator.GenerateHash();
}
}
[Test]
public void Generate_Hash_Multiple_Strings_Case_Sensitive()
{
var hash1 = Generate(true, "hello", "world");
var hash2 = Generate(true, "hello", "world");
var hashFalse1 = Generate(true, "hello", "worlD");
var hashFalse2 = Generate(true, "hEllo", "world");
Assert.AreEqual(hash1, hash2);
Assert.AreNotEqual(hash1, hashFalse1);
Assert.AreNotEqual(hash1, hashFalse2);
}
[Test]
public void Generate_Hash_Multiple_Strings_Case_Insensitive()
{
var hash1 = Generate(false, "hello", "world");
var hash2 = Generate(false, "hello", "world");
var hashFalse1 = Generate(false, "hello", "worlD");
var hashFalse2 = Generate(false, "hEllo", "world");
Assert.AreEqual(hash1, hash2);
Assert.AreEqual(hash1, hashFalse1);
Assert.AreEqual(hash1, hashFalse2);
}
private DirectoryInfo PrepareFolder()
{
var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
var dir = Directory.CreateDirectory(Path.Combine(assDir.FullName, "HashCombiner",
Guid.NewGuid().ToString("N")));
foreach (var f in dir.GetFiles())
{
f.Delete();
}
return dir;
}
[Test]
public void HashCombiner_Test_String()
{
using (var combiner1 = new HashGenerator())
using (var combiner2 = new HashGenerator())
{
combiner1.AddCaseInsensitiveString("Hello");
combiner2.AddCaseInsensitiveString("hello");
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
combiner2.AddCaseInsensitiveString("world");
Assert.AreNotEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
}
}
[Test]
public void HashCombiner_Test_Int()
{
using (var combiner1 = new HashGenerator())
using (var combiner2 = new HashGenerator())
{
combiner1.AddInt(1234);
combiner2.AddInt(1234);
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
combiner2.AddInt(1);
Assert.AreNotEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
}
}
[Test]
public void HashCombiner_Test_DateTime()
{
using (var combiner1 = new HashGenerator())
using (var combiner2 = new HashGenerator())
{
var dt = DateTime.Now;
combiner1.AddDateTime(dt);
combiner2.AddDateTime(dt);
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
combiner2.AddDateTime(DateTime.Now);
Assert.AreNotEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
}
}
[Test]
public void HashCombiner_Test_File()
{
using (var combiner1 = new HashGenerator())
using (var combiner2 = new HashGenerator())
using (var combiner3 = new HashGenerator())
{
var dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (var file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
file1.WriteLine("hello");
}
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (var file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
//even though files are the same, the dates are different
file2.WriteLine("hello");
}
combiner1.AddFile(new FileInfo(file1Path));
combiner2.AddFile(new FileInfo(file1Path));
combiner3.AddFile(new FileInfo(file2Path));
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
Assert.AreNotEqual(combiner1.GenerateHash(), combiner3.GenerateHash());
combiner2.AddFile(new FileInfo(file2Path));
Assert.AreNotEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
}
}
[Test]
public void HashCombiner_Test_Folder()
{
using (var combiner1 = new HashGenerator())
using (var combiner2 = new HashGenerator())
using (var combiner3 = new HashGenerator())
{
var dir = PrepareFolder();
var file1Path = Path.Combine(dir.FullName, "hastest1.txt");
File.Delete(file1Path);
using (var file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt")))
{
file1.WriteLine("hello");
}
//first test the whole folder
combiner1.AddFolder(dir);
combiner2.AddFolder(dir);
Assert.AreEqual(combiner1.GenerateHash(), combiner2.GenerateHash());
//now add a file to the folder
var file2Path = Path.Combine(dir.FullName, "hastest2.txt");
File.Delete(file2Path);
using (var file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt")))
{
//even though files are the same, the dates are different
file2.WriteLine("hello");
}
combiner3.AddFolder(dir);
Assert.AreNotEqual(combiner1.GenerateHash(), combiner3.GenerateHash());
}
}
}
}

View File

@@ -0,0 +1,130 @@
using System;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Hosting;
using Umbraco.Web;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing
{
// FIXME: not testing virtual directory!
[TestFixture]
public class UriUtilityTests
{
// test normal urls
[TestCase("http://LocalHost/", "http://localhost/")]
[TestCase("http://LocalHost/?x=y", "http://localhost/?x=y")]
[TestCase("http://LocalHost/Home", "http://localhost/home")]
[TestCase("http://LocalHost/Home?x=y", "http://localhost/home?x=y")]
[TestCase("http://LocalHost/Home/Sub1", "http://localhost/home/sub1")]
[TestCase("http://LocalHost/Home/Sub1?x=y", "http://localhost/home/sub1?x=y")]
// same with .aspx
[TestCase("http://LocalHost/Home.aspx", "http://localhost/home")]
[TestCase("http://LocalHost/Home.aspx?x=y", "http://localhost/home?x=y")]
[TestCase("http://LocalHost/Home/Sub1.aspx", "http://localhost/home/sub1")]
[TestCase("http://LocalHost/Home/Sub1.aspx?x=y", "http://localhost/home/sub1?x=y")]
// test that the trailing slash goes but not on hostname
[TestCase("http://LocalHost/", "http://localhost/")]
[TestCase("http://LocalHost/Home/", "http://localhost/home")]
[TestCase("http://LocalHost/Home/?x=y", "http://localhost/home?x=y")]
[TestCase("http://LocalHost/Home/Sub1/", "http://localhost/home/sub1")]
[TestCase("http://LocalHost/Home/Sub1/?x=y", "http://localhost/home/sub1?x=y")]
// test that default.aspx goes, even with parameters
[TestCase("http://LocalHost/deFault.aspx", "http://localhost/")]
[TestCase("http://LocalHost/deFault.aspx?x=y", "http://localhost/?x=y")]
// test with inner .aspx
[TestCase("http://Localhost/Home/Sub1.aspx/Sub2", "http://localhost/home/sub1/sub2")]
[TestCase("http://Localhost/Home/Sub1.aspx/Sub2?x=y", "http://localhost/home/sub1/sub2?x=y")]
[TestCase("http://Localhost/Home.aspx/Sub1.aspx/Sub2?x=y", "http://localhost/home/sub1/sub2?x=y")]
[TestCase("http://Localhost/deFault.aspx/Home.aspx/deFault.aspx/Sub1.aspx", "http://localhost/home/default/sub1")]
public void Uri_To_Umbraco(string sourceUrl, string expectedUrl)
{
// Arrange
var sourceUri = new Uri(sourceUrl);
var uriUtility = BuildUriUtility("/");
// Act
var resultUri = uriUtility.UriToUmbraco(sourceUri);
// Assert
var expectedUri = new Uri(expectedUrl);
Assert.AreEqual(expectedUri.ToString(), resultUri.ToString());
}
// test directoryUrl true, trailingSlash false
[TestCase("/", "/", false)]
[TestCase("/home", "/home", false)]
[TestCase("/home/sub1", "/home/sub1", false)]
// test directoryUrl true, trailingSlash true
[TestCase("/", "/", true)]
[TestCase("/home", "/home/", true)]
[TestCase("/home/sub1", "/home/sub1/", true)]
public void Uri_From_Umbraco(string sourceUrl, string expectedUrl, bool trailingSlash)
{
// Arrange
var sourceUri = new Uri(sourceUrl, UriKind.Relative);
var mockRequestHandlerSettings = new Mock<IRequestHandlerSettings>();
mockRequestHandlerSettings.Setup(x => x.AddTrailingSlash).Returns(trailingSlash);
var uriUtility = BuildUriUtility("/");
// Act
var resultUri = uriUtility.UriFromUmbraco(sourceUri, Mock.Of<IGlobalSettings>(), mockRequestHandlerSettings.Object);
// Assert
var expectedUri = new Uri(expectedUrl, UriKind.Relative);
Assert.AreEqual(expectedUri.ToString(), resultUri.ToString());
}
[TestCase("/", "/", "/")]
[TestCase("/", "/foo", "/foo")]
[TestCase("/", "~/foo", "/foo")]
[TestCase("/vdir", "/", "/vdir/")]
[TestCase("/vdir", "/foo", "/vdir/foo")]
[TestCase("/vdir", "/foo/", "/vdir/foo/")]
[TestCase("/vdir", "~/foo", "/vdir/foo")]
public void Uri_To_Absolute(string virtualPath, string sourceUrl, string expectedUrl)
{
// Arrange
var uriUtility = BuildUriUtility(virtualPath);
// Act
var resultUrl = uriUtility.ToAbsolute(sourceUrl);
// Assert
Assert.AreEqual(expectedUrl, resultUrl);
}
[TestCase("/", "/", "/")]
[TestCase("/", "/foo", "/foo")]
[TestCase("/", "/foo/", "/foo/")]
[TestCase("/vdir", "/vdir", "/")]
[TestCase("/vdir", "/vdir/", "/")]
[TestCase("/vdir", "/vdir/foo", "/foo")]
[TestCase("/vdir", "/vdir/foo/", "/foo/")]
public void Url_To_App_Relative(string virtualPath, string sourceUrl, string expectedUrl)
{
// Arrange
var uriUtility = BuildUriUtility(virtualPath);
// Act
var resultUrl = uriUtility.ToAppRelative(sourceUrl);
// Assert
Assert.AreEqual(expectedUrl, resultUrl);
}
private UriUtility BuildUriUtility(string virtualPath)
{
var mockHostingEnvironment = new Mock<IHostingEnvironment>();
mockHostingEnvironment.Setup(x => x.ApplicationVirtualPath).Returns(virtualPath);
return new UriUtility(mockHostingEnvironment.Object);
}
}
}

View File

@@ -0,0 +1,157 @@
using System.Diagnostics;
using System.Linq;
using System.Xml;
using System.Xml.XPath;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Xml;
using Umbraco.Tests.Common.Builders;
namespace Umbraco.Tests.UnitTests.Umbraco.Core.Xml
{
[TestFixture]
public class XmlHelperTests
{
private XmlDocumentBuilder _builder;
[SetUp]
public void SetUp()
{
_builder = new XmlDocumentBuilder();
}
[Ignore("This is a benchmark test so is ignored by default")]
[Test]
public void Sort_Nodes_Benchmark_Legacy()
{
var xml = _builder.Build();
var original = xml.GetElementById(1173.ToString());
Assert.IsNotNull(original);
long totalTime = 0;
var watch = new Stopwatch();
var iterations = 10000;
for (var i = 0; i < iterations; i++)
{
//don't measure the time for clone!
var parentNode = original.Clone();
watch.Start();
LegacySortNodes(ref parentNode);
watch.Stop();
totalTime += watch.ElapsedMilliseconds;
watch.Reset();
//do assertions just to make sure it is working properly.
var currSort = 0;
foreach (var child in parentNode.SelectNodes("./* [@id]").Cast<XmlNode>())
{
Assert.AreEqual(currSort, int.Parse(child.Attributes["sortOrder"].Value));
currSort++;
}
//ensure the parent node's properties still exist first
Assert.AreEqual("content", parentNode.ChildNodes[0].Name);
Assert.AreEqual("umbracoUrlAlias", parentNode.ChildNodes[1].Name);
//then the child nodes should come straight after
Assert.IsTrue(parentNode.ChildNodes[2].Attributes["id"] != null);
}
Debug.WriteLine("Total time for " + iterations + " iterations is " + totalTime);
}
[Ignore("This is a benchmark test so is ignored by default")]
[Test]
public void Sort_Nodes_Benchmark_New()
{
var xml = _builder.Build();
var original = xml.GetElementById(1173.ToString());
Assert.IsNotNull(original);
long totalTime = 0;
var watch = new Stopwatch();
var iterations = 10000;
for (var i = 0; i < iterations; i++)
{
//don't measure the time for clone!
var parentNode = (XmlElement) original.Clone();
watch.Start();
XmlHelper.SortNodes(
parentNode,
"./* [@id]",
x => x.AttributeValue<int>("sortOrder"));
watch.Stop();
totalTime += watch.ElapsedMilliseconds;
watch.Reset();
//do assertions just to make sure it is working properly.
var currSort = 0;
foreach (var child in parentNode.SelectNodes("./* [@id]").Cast<XmlNode>())
{
Assert.AreEqual(currSort, int.Parse(child.Attributes["sortOrder"].Value));
currSort++;
}
//ensure the parent node's properties still exist first
Assert.AreEqual("content", parentNode.ChildNodes[0].Name);
Assert.AreEqual("umbracoUrlAlias", parentNode.ChildNodes[1].Name);
//then the child nodes should come straight after
Assert.IsTrue(parentNode.ChildNodes[2].Attributes["id"] != null);
}
Debug.WriteLine("Total time for " + iterations + " iterations is " + totalTime);
}
[Test]
public void Sort_Nodes()
{
var xml = _builder.Build();
var original = xml.GetElementById(1173.ToString());
Assert.IsNotNull(original);
var parentNode = (XmlElement) original.Clone();
XmlHelper.SortNodes(
parentNode,
"./* [@id]",
x => x.AttributeValue<int>("sortOrder"));
//do assertions just to make sure it is working properly.
var currSort = 0;
foreach (var child in parentNode.SelectNodes("./* [@id]").Cast<XmlNode>())
{
Assert.AreEqual(currSort, int.Parse(child.Attributes["sortOrder"].Value));
currSort++;
}
//ensure the parent node's properties still exist first
Assert.AreEqual("content", parentNode.ChildNodes[0].Name);
Assert.AreEqual("umbracoUrlAlias", parentNode.ChildNodes[1].Name);
//then the child nodes should come straight after
Assert.IsTrue(parentNode.ChildNodes[2].Attributes["id"] != null);
}
/// <summary>
/// This was the logic to sort before and now lives here just to show the benchmarks tests above.
/// </summary>
/// <param name="parentNode"></param>
private static void LegacySortNodes(ref XmlNode parentNode)
{
var n = parentNode.CloneNode(true);
// remove all children from original node
var xpath = "./* [@id]";
foreach (XmlNode child in parentNode.SelectNodes(xpath))
parentNode.RemoveChild(child);
var nav = n.CreateNavigator();
var expr = nav.Compile(xpath);
expr.AddSort("@sortOrder", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
var iterator = nav.Select(expr);
while (iterator.MoveNext())
parentNode.AppendChild(
((IHasXmlNode) iterator.Current).GetNode());
}
}
}

View File

@@ -0,0 +1,27 @@
using NUnit.Framework;
using Umbraco.Tests.Common.Builders;
namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders
{
[TestFixture]
public class XmlDocumentBuilderTests
{
[Test]
public void Is_Built_Correctly()
{
// Arrange
const string content =
@"<?xml version=""1.0"" encoding=""utf-8""?><root id=""-1""></root>";
var builder = new XmlDocumentBuilder();
// Act
var xml = builder
.WithContent(content)
.Build();
// Assert
Assert.AreEqual(content, xml.OuterXml);
}
}
}