summaryrefslogtreecommitdiff
path: root/src/StardewModdingAPI.Tests
diff options
context:
space:
mode:
Diffstat (limited to 'src/StardewModdingAPI.Tests')
-rw-r--r--src/StardewModdingAPI.Tests/Core/ModResolverTests.cs (renamed from src/StardewModdingAPI.Tests/ModResolverTests.cs)181
-rw-r--r--src/StardewModdingAPI.Tests/Core/TranslationTests.cs (renamed from src/StardewModdingAPI.Tests/TranslationTests.cs)9
-rw-r--r--src/StardewModdingAPI.Tests/Sample.cs (renamed from src/StardewModdingAPI.Tests/Framework/Sample.cs)2
-rw-r--r--src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj8
-rw-r--r--src/StardewModdingAPI.Tests/Utilities/SDateTests.cs253
-rw-r--r--src/StardewModdingAPI.Tests/Utilities/SemanticVersionTests.cs255
6 files changed, 655 insertions, 53 deletions
diff --git a/src/StardewModdingAPI.Tests/ModResolverTests.cs b/src/StardewModdingAPI.Tests/Core/ModResolverTests.cs
index 23aeba64..b451465e 100644
--- a/src/StardewModdingAPI.Tests/ModResolverTests.cs
+++ b/src/StardewModdingAPI.Tests/Core/ModResolverTests.cs
@@ -9,9 +9,8 @@ using StardewModdingAPI.Framework;
using StardewModdingAPI.Framework.Models;
using StardewModdingAPI.Framework.ModLoading;
using StardewModdingAPI.Framework.Serialisation;
-using StardewModdingAPI.Tests.Framework;
-namespace StardewModdingAPI.Tests
+namespace StardewModdingAPI.Tests.Core
{
/// <summary>Unit tests for <see cref="ModResolver"/>.</summary>
[TestFixture]
@@ -31,7 +30,7 @@ namespace StardewModdingAPI.Tests
Directory.CreateDirectory(rootFolder);
// act
- IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0]).ToArray();
+ IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0], new DisabledMod[0]).ToArray();
// assert
Assert.AreEqual(0, mods.Length, 0, $"Expected to find zero manifests, found {mods.Length} instead.");
@@ -46,7 +45,7 @@ namespace StardewModdingAPI.Tests
Directory.CreateDirectory(modFolder);
// act
- IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0]).ToArray();
+ IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0], new DisabledMod[0]).ToArray();
IModMetadata mod = mods.FirstOrDefault();
// assert
@@ -85,7 +84,7 @@ namespace StardewModdingAPI.Tests
File.WriteAllText(filename, JsonConvert.SerializeObject(original));
// act
- IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0]).ToArray();
+ IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0], new DisabledMod[0]).ToArray();
IModMetadata mod = mods.FirstOrDefault();
// assert
@@ -101,7 +100,7 @@ namespace StardewModdingAPI.Tests
Assert.AreEqual(original[nameof(IManifest.Author)], mod.Manifest.Author, "The manifest's author doesn't match.");
Assert.AreEqual(original[nameof(IManifest.Description)], mod.Manifest.Description, "The manifest's description doesn't match.");
Assert.AreEqual(original[nameof(IManifest.EntryDll)], mod.Manifest.EntryDll, "The manifest's entry DLL doesn't match.");
- Assert.AreEqual(original[nameof(IManifest.MinimumApiVersion)], mod.Manifest.MinimumApiVersion, "The manifest's minimum API version doesn't match.");
+ Assert.AreEqual(original[nameof(IManifest.MinimumApiVersion)], mod.Manifest.MinimumApiVersion?.ToString(), "The manifest's minimum API version doesn't match.");
Assert.AreEqual(original[nameof(IManifest.Version)]?.ToString(), mod.Manifest.Version?.ToString(), "The manifest's version doesn't match.");
Assert.IsNotNull(mod.Manifest.ExtraFields, "The extra fields should not be null.");
@@ -160,7 +159,7 @@ namespace StardewModdingAPI.Tests
Mock<IModMetadata> mock = new Mock<IModMetadata>(MockBehavior.Strict);
mock.Setup(p => p.Status).Returns(ModMetadataStatus.Found);
mock.Setup(p => p.Compatibility).Returns(() => null);
- mock.Setup(p => p.Manifest).Returns(this.GetRandomManifest(m => m.MinimumApiVersion = "1.1"));
+ mock.Setup(p => p.Manifest).Returns(this.GetManifest(m => m.MinimumApiVersion = new SemanticVersion("1.1")));
mock.Setup(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<string>())).Returns(() => mock.Object);
// act
@@ -177,7 +176,7 @@ namespace StardewModdingAPI.Tests
Mock<IModMetadata> mock = new Mock<IModMetadata>(MockBehavior.Strict);
mock.Setup(p => p.Status).Returns(ModMetadataStatus.Found);
mock.Setup(p => p.Compatibility).Returns(() => null);
- mock.Setup(p => p.Manifest).Returns(this.GetRandomManifest());
+ mock.Setup(p => p.Manifest).Returns(this.GetManifest());
mock.Setup(p => p.DirectoryPath).Returns(Path.GetTempPath());
mock.Setup(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<string>())).Returns(() => mock.Object);
@@ -192,7 +191,7 @@ namespace StardewModdingAPI.Tests
public void ValidateManifests_Valid_Passes()
{
// set up manifest
- IManifest manifest = this.GetRandomManifest();
+ IManifest manifest = this.GetManifest();
// create DLL
string modFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
@@ -231,9 +230,9 @@ namespace StardewModdingAPI.Tests
{
// arrange
// A B C
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B");
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C");
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B");
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C");
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modA.Object, modB.Object, modC.Object }).ToArray();
@@ -267,9 +266,9 @@ namespace StardewModdingAPI.Tests
// ▲ ▲
// │ │
// └─ C ─┘
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod A", "Mod B" });
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod A", "Mod B" });
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modC.Object, modA.Object, modB.Object }).ToArray();
@@ -286,10 +285,10 @@ namespace StardewModdingAPI.Tests
{
// arrange
// A ◀── B ◀── C ◀── D
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod B" });
- Mock<IModMetadata> modD = this.GetMetadataForDependencyTest("Mod D", dependencies: new[] { "Mod C" });
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod B" });
+ Mock<IModMetadata> modD = this.GetMetadata("Mod D", dependencies: new[] { "Mod C" });
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modC.Object, modA.Object, modB.Object, modD.Object }).ToArray();
@@ -310,12 +309,12 @@ namespace StardewModdingAPI.Tests
// ▲ ▲
// │ │
// E ◀── F
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod B" });
- Mock<IModMetadata> modD = this.GetMetadataForDependencyTest("Mod D", dependencies: new[] { "Mod C" });
- Mock<IModMetadata> modE = this.GetMetadataForDependencyTest("Mod E", dependencies: new[] { "Mod B" });
- Mock<IModMetadata> modF = this.GetMetadataForDependencyTest("Mod F", dependencies: new[] { "Mod C", "Mod E" });
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod B" });
+ Mock<IModMetadata> modD = this.GetMetadata("Mod D", dependencies: new[] { "Mod C" });
+ Mock<IModMetadata> modE = this.GetMetadata("Mod E", dependencies: new[] { "Mod B" });
+ Mock<IModMetadata> modF = this.GetMetadata("Mod F", dependencies: new[] { "Mod C", "Mod E" });
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modC.Object, modA.Object, modB.Object, modD.Object, modF.Object, modE.Object }).ToArray();
@@ -338,11 +337,11 @@ namespace StardewModdingAPI.Tests
// ▲ │
// │ ▼
// └──── E
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod B", "Mod D" }, allowStatusChange: true);
- Mock<IModMetadata> modD = this.GetMetadataForDependencyTest("Mod D", dependencies: new[] { "Mod E" }, allowStatusChange: true);
- Mock<IModMetadata> modE = this.GetMetadataForDependencyTest("Mod E", dependencies: new[] { "Mod C" }, allowStatusChange: true);
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod B", "Mod D" }, allowStatusChange: true);
+ Mock<IModMetadata> modD = this.GetMetadata("Mod D", dependencies: new[] { "Mod E" }, allowStatusChange: true);
+ Mock<IModMetadata> modE = this.GetMetadata("Mod E", dependencies: new[] { "Mod C" }, allowStatusChange: true);
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modC.Object, modA.Object, modB.Object, modD.Object, modE.Object }).ToArray();
@@ -361,9 +360,9 @@ namespace StardewModdingAPI.Tests
{
// arrange
// A ◀── B ◀── C D (failed)
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod B" }, allowStatusChange: true);
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod B" }, allowStatusChange: true);
Mock<IModMetadata> modD = new Mock<IModMetadata>(MockBehavior.Strict);
modD.Setup(p => p.Manifest).Returns<IManifest>(null);
modD.Setup(p => p.Status).Returns(ModMetadataStatus.Failed);
@@ -379,12 +378,80 @@ namespace StardewModdingAPI.Tests
Assert.AreSame(modC.Object, mods[3], "The load order is incorrect: mod C should be fourth since it needs mod B, and is needed by mod D.");
}
+ [Test(Description = "Assert that dependencies are failed if they don't meet the minimum version.")]
+ public void ProcessDependencies_WithMinVersions_FailsIfNotMet()
+ {
+ // arrange
+ // A 1.0 ◀── B (need A 1.1)
+ Mock<IModMetadata> modA = this.GetMetadata(this.GetManifest("Mod A", "1.0"));
+ Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest("Mod B", "1.0", new ManifestDependency("Mod A", "1.1")), allowStatusChange: true);
+
+ // act
+ IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modA.Object, modB.Object }).ToArray();
+
+ // assert
+ Assert.AreEqual(2, mods.Length, 0, "Expected to get the same number of mods input.");
+ modB.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<string>()), Times.Once, "Mod B unexpectedly didn't fail even though it needs a newer version of Mod A.");
+ }
+
+ [Test(Description = "Assert that dependencies are accepted if they meet the minimum version.")]
+ public void ProcessDependencies_WithMinVersions_SucceedsIfMet()
+ {
+ // arrange
+ // A 1.0 ◀── B (need A 1.0-beta)
+ Mock<IModMetadata> modA = this.GetMetadata(this.GetManifest("Mod A", "1.0"));
+ Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest("Mod B", "1.0", new ManifestDependency("Mod A", "1.0-beta")), allowStatusChange: false);
+
+ // act
+ IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modA.Object, modB.Object }).ToArray();
+
+ // assert
+ Assert.AreEqual(2, mods.Length, 0, "Expected to get the same number of mods input.");
+ Assert.AreSame(modA.Object, mods[0], "The load order is incorrect: mod A should be first since it's needed by mod B.");
+ Assert.AreSame(modB.Object, mods[1], "The load order is incorrect: mod B should be second since it needs mod A.");
+ }
+
+#if SMAPI_2_0
+ [Test(Description = "Assert that optional dependencies are sorted correctly if present.")]
+ public void ProcessDependencies_IfOptional()
+ {
+ // arrange
+ // A ◀── B
+ Mock<IModMetadata> modA = this.GetMetadata(this.GetManifest("Mod A", "1.0"));
+ Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest("Mod B", "1.0", new ManifestDependency("Mod A", "1.0", required: false)), allowStatusChange: false);
+
+ // act
+ IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modB.Object, modA.Object }).ToArray();
+
+ // assert
+ Assert.AreEqual(2, mods.Length, 0, "Expected to get the same number of mods input.");
+ Assert.AreSame(modA.Object, mods[0], "The load order is incorrect: mod A should be first since it's needed by mod B.");
+ Assert.AreSame(modB.Object, mods[1], "The load order is incorrect: mod B should be second since it needs mod A.");
+ }
+
+ [Test(Description = "Assert that optional dependencies are accepted if they're missing.")]
+ public void ProcessDependencies_IfOptional_SucceedsIfMissing()
+ {
+ // arrange
+ // A ◀── B where A doesn't exist
+ Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest("Mod B", "1.0", new ManifestDependency("Mod A", "1.0", required: false)), allowStatusChange: false);
+
+ // act
+ IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modB.Object }).ToArray();
+
+ // assert
+ Assert.AreEqual(1, mods.Length, 0, "Expected to get the same number of mods input.");
+ Assert.AreSame(modB.Object, mods[0], "The load order is incorrect: mod B should be first since it's the only mod.");
+ }
+#endif
+
+
/*********
** Private methods
*********/
/// <summary>Get a randomised basic manifest.</summary>
/// <param name="adjust">Adjust the generated manifest.</param>
- private Manifest GetRandomManifest(Action<Manifest> adjust = null)
+ private Manifest GetManifest(Action<Manifest> adjust = null)
{
Manifest manifest = new Manifest
{
@@ -401,26 +468,50 @@ namespace StardewModdingAPI.Tests
/// <summary>Get a randomised basic manifest.</summary>
/// <param name="uniqueID">The mod's name and unique ID.</param>
+ /// <param name="version">The mod version.</param>
/// <param name="dependencies">The dependencies this mod requires.</param>
+ private IManifest GetManifest(string uniqueID, string version, params IManifestDependency[] dependencies)
+ {
+ return this.GetManifest(manifest =>
+ {
+ manifest.Name = uniqueID;
+ manifest.UniqueID = uniqueID;
+ manifest.Version = new SemanticVersion(version);
+ manifest.Dependencies = dependencies;
+ });
+ }
+
+ /// <summary>Get a randomised basic manifest.</summary>
+ /// <param name="uniqueID">The mod's name and unique ID.</param>
+ private Mock<IModMetadata> GetMetadata(string uniqueID)
+ {
+ return this.GetMetadata(this.GetManifest(uniqueID, "1.0"));
+ }
+
+ /// <summary>Get a randomised basic manifest.</summary>
+ /// <param name="uniqueID">The mod's name and unique ID.</param>
+ /// <param name="dependencies">The dependencies this mod requires.</param>
+ /// <param name="allowStatusChange">Whether the code being tested is allowed to change the mod status.</param>
+ private Mock<IModMetadata> GetMetadata(string uniqueID, string[] dependencies, bool allowStatusChange = false)
+ {
+ IManifest manifest = this.GetManifest(uniqueID, "1.0", dependencies?.Select(dependencyID => (IManifestDependency)new ManifestDependency(dependencyID, null)).ToArray());
+ return this.GetMetadata(manifest, allowStatusChange);
+ }
+
+ /// <summary>Get a randomised basic manifest.</summary>
+ /// <param name="manifest">The mod manifest.</param>
/// <param name="allowStatusChange">Whether the code being tested is allowed to change the mod status.</param>
- private Mock<IModMetadata> GetMetadataForDependencyTest(string uniqueID, string[] dependencies = null, bool allowStatusChange = false)
+ private Mock<IModMetadata> GetMetadata(IManifest manifest, bool allowStatusChange = false)
{
Mock<IModMetadata> mod = new Mock<IModMetadata>(MockBehavior.Strict);
mod.Setup(p => p.Status).Returns(ModMetadataStatus.Found);
- mod.Setup(p => p.DisplayName).Returns(uniqueID);
- mod.Setup(p => p.Manifest).Returns(
- this.GetRandomManifest(manifest =>
- {
- manifest.Name = uniqueID;
- manifest.UniqueID = uniqueID;
- manifest.Dependencies = dependencies?.Select(dependencyID => (IManifestDependency)new ManifestDependency(dependencyID)).ToArray();
- })
- );
+ mod.Setup(p => p.DisplayName).Returns(manifest.UniqueID);
+ mod.Setup(p => p.Manifest).Returns(manifest);
if (allowStatusChange)
{
mod
.Setup(p => p.SetStatus(It.IsAny<ModMetadataStatus>(), It.IsAny<string>()))
- .Callback<ModMetadataStatus, string>((status, message) => Console.WriteLine($"<{uniqueID} changed status: [{status}] {message}"))
+ .Callback<ModMetadataStatus, string>((status, message) => Console.WriteLine($"<{manifest.UniqueID} changed status: [{status}] {message}"))
.Returns(mod.Object);
}
return mod;
diff --git a/src/StardewModdingAPI.Tests/TranslationTests.cs b/src/StardewModdingAPI.Tests/Core/TranslationTests.cs
index 157a08a2..8511e765 100644
--- a/src/StardewModdingAPI.Tests/TranslationTests.cs
+++ b/src/StardewModdingAPI.Tests/Core/TranslationTests.cs
@@ -3,9 +3,10 @@ using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using StardewModdingAPI.Framework;
+using StardewModdingAPI.Framework.ModHelpers;
using StardewValley;
-namespace StardewModdingAPI.Tests
+namespace StardewModdingAPI.Tests.Core
{
/// <summary>Unit tests for <see cref="TranslationHelper"/> and <see cref="Translation"/>.</summary>
[TestFixture]
@@ -31,7 +32,7 @@ namespace StardewModdingAPI.Tests
var data = new Dictionary<string, IDictionary<string, string>>();
// act
- ITranslationHelper helper = new TranslationHelper("ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
+ ITranslationHelper helper = new TranslationHelper("ModID", "ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
Translation translation = helper.Get("key");
Translation[] translationList = helper.GetTranslations()?.ToArray();
@@ -54,7 +55,7 @@ namespace StardewModdingAPI.Tests
// act
var actual = new Dictionary<string, Translation[]>();
- TranslationHelper helper = new TranslationHelper("ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
+ TranslationHelper helper = new TranslationHelper("ModID", "ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
foreach (string locale in expected.Keys)
{
this.AssertSetLocale(helper, locale, LocalizedContentManager.LanguageCode.en);
@@ -78,7 +79,7 @@ namespace StardewModdingAPI.Tests
// act
var actual = new Dictionary<string, Translation[]>();
- TranslationHelper helper = new TranslationHelper("ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
+ TranslationHelper helper = new TranslationHelper("ModID", "ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
foreach (string locale in expected.Keys)
{
this.AssertSetLocale(helper, locale, LocalizedContentManager.LanguageCode.en);
diff --git a/src/StardewModdingAPI.Tests/Framework/Sample.cs b/src/StardewModdingAPI.Tests/Sample.cs
index 10006f1e..99835d92 100644
--- a/src/StardewModdingAPI.Tests/Framework/Sample.cs
+++ b/src/StardewModdingAPI.Tests/Sample.cs
@@ -1,6 +1,6 @@
using System;
-namespace StardewModdingAPI.Tests.Framework
+namespace StardewModdingAPI.Tests
{
/// <summary>Provides sample values for unit testing.</summary>
internal static class Sample
diff --git a/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj b/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj
index 3818ec9c..9bfd7567 100644
--- a/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj
+++ b/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj
@@ -48,10 +48,12 @@
<Compile Include="..\GlobalAssemblyInfo.cs">
<Link>Properties\GlobalAssemblyInfo.cs</Link>
</Compile>
- <Compile Include="TranslationTests.cs" />
- <Compile Include="ModResolverTests.cs" />
+ <Compile Include="Utilities\SemanticVersionTests.cs" />
+ <Compile Include="Utilities\SDateTests.cs" />
+ <Compile Include="Core\TranslationTests.cs" />
+ <Compile Include="Core\ModResolverTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="Framework\Sample.cs" />
+ <Compile Include="Sample.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
diff --git a/src/StardewModdingAPI.Tests/Utilities/SDateTests.cs b/src/StardewModdingAPI.Tests/Utilities/SDateTests.cs
new file mode 100644
index 00000000..714756e0
--- /dev/null
+++ b/src/StardewModdingAPI.Tests/Utilities/SDateTests.cs
@@ -0,0 +1,253 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Text.RegularExpressions;
+using NUnit.Framework;
+using StardewModdingAPI.Utilities;
+
+namespace StardewModdingAPI.Tests.Utilities
+{
+ /// <summary>Unit tests for <see cref="SDate"/>.</summary>
+ [TestFixture]
+ internal class SDateTests
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>All valid seasons.</summary>
+ private static readonly string[] ValidSeasons = { "spring", "summer", "fall", "winter" };
+
+ /// <summary>All valid days of a month.</summary>
+ private static readonly int[] ValidDays = Enumerable.Range(1, 28).ToArray();
+
+ /// <summary>Sample relative dates for test cases.</summary>
+ private static class Dates
+ {
+ /// <summary>The base date to which other dates are relative.</summary>
+ public const string Now = "02 summer Y2";
+
+ /// <summary>The day before <see cref="Now"/>.</summary>
+ public const string PrevDay = "01 summer Y2";
+
+ /// <summary>The month before <see cref="Now"/>.</summary>
+ public const string PrevMonth = "02 spring Y2";
+
+ /// <summary>The year before <see cref="Now"/>.</summary>
+ public const string PrevYear = "02 summer Y1";
+
+ /// <summary>The day after <see cref="Now"/>.</summary>
+ public const string NextDay = "03 summer Y2";
+
+ /// <summary>The month after <see cref="Now"/>.</summary>
+ public const string NextMonth = "02 fall Y2";
+
+ /// <summary>The year after <see cref="Now"/>.</summary>
+ public const string NextYear = "02 summer Y3";
+ }
+
+
+ /*********
+ ** Unit tests
+ *********/
+ /****
+ ** Constructor
+ ****/
+ [Test(Description = "Assert that the constructor sets the expected values for all valid dates.")]
+ public void Constructor_SetsExpectedValues([ValueSource(nameof(SDateTests.ValidSeasons))] string season, [ValueSource(nameof(SDateTests.ValidDays))] int day, [Values(1, 2, 100)] int year)
+ {
+ // act
+ SDate date = new SDate(day, season, year);
+
+ // assert
+ Assert.AreEqual(day, date.Day);
+ Assert.AreEqual(season, date.Season);
+ Assert.AreEqual(year, date.Year);
+ }
+
+ [Test(Description = "Assert that the constructor throws an exception if the values are invalid.")]
+ [TestCase(01, "Spring", 1)] // seasons are case-sensitive
+ [TestCase(01, "springs", 1)] // invalid season name
+ [TestCase(-1, "spring", 1)] // day < 0
+ [TestCase(29, "spring", 1)] // day > 28
+ [TestCase(01, "spring", -1)] // year < 1
+ [TestCase(01, "spring", 0)] // year < 1
+ [SuppressMessage("ReSharper", "AssignmentIsFullyDiscarded", Justification = "Deliberate for unit test.")]
+ public void Constructor_RejectsInvalidValues(int day, string season, int year)
+ {
+ // act & assert
+ Assert.Throws<ArgumentException>(() => _ = new SDate(day, season, year), "Constructing the invalid date didn't throw the expected exception.");
+ }
+
+ /****
+ ** ToString
+ ****/
+ [Test(Description = "Assert that ToString returns the expected string.")]
+ [TestCase("14 spring Y1", ExpectedResult = "14 spring Y1")]
+ [TestCase("01 summer Y16", ExpectedResult = "01 summer Y16")]
+ [TestCase("28 fall Y10", ExpectedResult = "28 fall Y10")]
+ [TestCase("01 winter Y1", ExpectedResult = "01 winter Y1")]
+ public string ToString(string dateStr)
+ {
+ return this.GetDate(dateStr).ToString();
+ }
+
+ /****
+ ** AddDays
+ ****/
+ [Test(Description = "Assert that AddDays returns the expected date.")]
+ [TestCase("01 spring Y1", 15, ExpectedResult = "16 spring Y1")] // day transition
+ [TestCase("01 spring Y1", 28, ExpectedResult = "01 summer Y1")] // season transition
+ [TestCase("01 spring Y1", 28 * 4, ExpectedResult = "01 spring Y2")] // year transition
+ [TestCase("01 spring Y1", 28 * 7 + 17, ExpectedResult = "18 winter Y2")] // year transition
+ [TestCase("15 spring Y1", -14, ExpectedResult = "01 spring Y1")] // negative day transition
+ [TestCase("15 summer Y1", -28, ExpectedResult = "15 spring Y1")] // negative season transition
+ [TestCase("15 summer Y2", -28 * 4, ExpectedResult = "15 summer Y1")] // negative year transition
+ [TestCase("01 spring Y3", -(28 * 7 + 17), ExpectedResult = "12 spring Y1")] // negative year transition
+ public string AddDays(string dateStr, int addDays)
+ {
+ return this.GetDate(dateStr).AddDays(addDays).ToString();
+ }
+
+ /****
+ ** GetHashCode
+ ****/
+ [Test(Description = "Assert that GetHashCode returns a unique ordered value for every date.")]
+ public void GetHashCode_ReturnsUniqueOrderedValue()
+ {
+ IDictionary<int, SDate> hashes = new Dictionary<int, SDate>();
+ int lastHash = int.MinValue;
+ for (int year = 1; year <= 4; year++)
+ {
+ foreach (string season in SDateTests.ValidSeasons)
+ {
+ foreach (int day in SDateTests.ValidDays)
+ {
+ SDate date = new SDate(day, season, year);
+ int hash = date.GetHashCode();
+ if (hashes.TryGetValue(hash, out SDate otherDate))
+ Assert.Fail($"Received identical hash code {hash} for dates {otherDate} and {date}.");
+ if (hash < lastHash)
+ Assert.Fail($"Received smaller hash code for date {date} ({hash}) relative to {hashes[lastHash]} ({lastHash}).");
+
+ lastHash = hash;
+ hashes[hash] = date;
+ }
+ }
+ }
+ }
+
+ [Test(Description = "Assert that the == operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = false)]
+ public bool Operators_Equals(string now, string other)
+ {
+ return this.GetDate(now) == this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the != operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = true)]
+ public bool Operators_NotEquals(string now, string other)
+ {
+ return this.GetDate(now) != this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the < operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = true)]
+ public bool Operators_LessThan(string now, string other)
+ {
+ return this.GetDate(now) < this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the <= operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = true)]
+ public bool Operators_LessThanOrEqual(string now, string other)
+ {
+ return this.GetDate(now) <= this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the > operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = false)]
+ public bool Operators_MoreThan(string now, string other)
+ {
+ return this.GetDate(now) > this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the > operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = false)]
+ public bool Operators_MoreThanOrEqual(string now, string other)
+ {
+ return this.GetDate(now) > this.GetDate(other);
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Convert a string date into a game date, to make unit tests easier to read.</summary>
+ /// <param name="dateStr">The date string like "dd MMMM yy".</param>
+ private SDate GetDate(string dateStr)
+ {
+ if (dateStr == null)
+ return null;
+
+ void Fail(string reason) => throw new AssertionException($"Couldn't parse date '{dateStr}' because {reason}.");
+
+ // parse
+ Match match = Regex.Match(dateStr, @"^(?<day>\d+) (?<season>\w+) Y(?<year>\d+)$");
+ if (!match.Success)
+ Fail("it doesn't match expected pattern (should be like 28 spring Y1)");
+
+ // extract parts
+ string season = match.Groups["season"].Value;
+ if (!int.TryParse(match.Groups["day"].Value, out int day))
+ Fail($"'{match.Groups["day"].Value}' couldn't be parsed as a day.");
+ if (!int.TryParse(match.Groups["year"].Value, out int year))
+ Fail($"'{match.Groups["year"].Value}' couldn't be parsed as a year.");
+
+ // build date
+ return new SDate(day, season, year);
+ }
+ }
+}
diff --git a/src/StardewModdingAPI.Tests/Utilities/SemanticVersionTests.cs b/src/StardewModdingAPI.Tests/Utilities/SemanticVersionTests.cs
new file mode 100644
index 00000000..95d0d74f
--- /dev/null
+++ b/src/StardewModdingAPI.Tests/Utilities/SemanticVersionTests.cs
@@ -0,0 +1,255 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using NUnit.Framework;
+
+namespace StardewModdingAPI.Tests.Utilities
+{
+ /// <summary>Unit tests for <see cref="SemanticVersion"/>.</summary>
+ [TestFixture]
+ internal class SemanticVersionTests
+ {
+ /*********
+ ** Unit tests
+ *********/
+ /****
+ ** Constructor
+ ****/
+ [Test(Description = "Assert that the constructor sets the expected values for all valid versions.")]
+ [TestCase("1.0", ExpectedResult = "1.0")]
+ [TestCase("1.0.0", ExpectedResult = "1.0")]
+ [TestCase("3000.4000.5000", ExpectedResult = "3000.4000.5000")]
+ [TestCase("1.2-some-tag.4", ExpectedResult = "1.2-some-tag.4")]
+ [TestCase("1.2.3-some-tag.4", ExpectedResult = "1.2.3-some-tag.4")]
+ [TestCase("1.2.3-some-tag.4 ", ExpectedResult = "1.2.3-some-tag.4")]
+ public string Constructor_FromString(string input)
+ {
+ return new SemanticVersion(input).ToString();
+ }
+
+ [Test(Description = "Assert that the constructor sets the expected values for all valid versions.")]
+ [TestCase(1, 0, 0, null, ExpectedResult = "1.0")]
+ [TestCase(3000, 4000, 5000, null, ExpectedResult = "3000.4000.5000")]
+ [TestCase(1, 2, 3, "", ExpectedResult = "1.2.3")]
+ [TestCase(1, 2, 3, " ", ExpectedResult = "1.2.3")]
+ [TestCase(1, 2, 3, "some-tag.4", ExpectedResult = "1.2.3-some-tag.4")]
+ [TestCase(1, 2, 3, "some-tag.4 ", ExpectedResult = "1.2.3-some-tag.4")]
+ public string Constructor_FromParts(int major, int minor, int patch, string tag)
+ {
+ // act
+ ISemanticVersion version = new SemanticVersion(major, minor, patch, tag);
+
+ // assert
+ Assert.AreEqual(major, version.MajorVersion, "The major version doesn't match the given value.");
+ Assert.AreEqual(minor, version.MinorVersion, "The minor version doesn't match the given value.");
+ Assert.AreEqual(patch, version.PatchVersion, "The patch version doesn't match the given value.");
+ Assert.AreEqual(string.IsNullOrWhiteSpace(tag) ? null : tag.Trim(), version.Build, "The tag doesn't match the given value.");
+ return version.ToString();
+ }
+
+ [Test(Description = "Assert that the constructor throws the expected exception for invalid versions.")]
+ [TestCase(null)]
+ [TestCase("")]
+ [TestCase(" ")]
+ [TestCase("1")]
+ [TestCase("01.0")]
+ [TestCase("1.05")]
+ [TestCase("1.5.06")] // leading zeros specifically prohibited by spec
+ [TestCase("1.2.3.4")]
+ [TestCase("1.apple")]
+ [TestCase("1.2.apple")]
+ [TestCase("1.2.3.apple")]
+ [TestCase("1..2..3")]
+ [TestCase("1.2.3-")]
+ [TestCase("1.2.3-some-tag...")]
+ [TestCase("1.2.3-some-tag...4")]
+ [TestCase("apple")]
+ [TestCase("-apple")]
+ [TestCase("-5")]
+ public void Constructor_FromString_WithInvalidValues(string input)
+ {
+ if (input == null)
+ this.AssertAndLogException<ArgumentNullException>(() => new SemanticVersion(input));
+ else
+ this.AssertAndLogException<FormatException>(() => new SemanticVersion(input));
+ }
+
+ /****
+ ** CompareTo
+ ****/
+ [Test(Description = "Assert that version.CompareTo returns the expected value.")]
+ // equal
+ [TestCase("0.5.7", "0.5.7", ExpectedResult = 0)]
+ [TestCase("1.0", "1.0", ExpectedResult = 0)]
+ [TestCase("1.0-beta", "1.0-beta", ExpectedResult = 0)]
+ [TestCase("1.0-beta.10", "1.0-beta.10", ExpectedResult = 0)]
+ [TestCase("1.0-beta", "1.0-beta ", ExpectedResult = 0)]
+
+ // less than
+ [TestCase("0.5.7", "0.5.8", ExpectedResult = -1)]
+ [TestCase("1.0", "1.1", ExpectedResult = -1)]
+ [TestCase("1.0-beta", "1.0", ExpectedResult = -1)]
+ [TestCase("1.0-beta", "1.0-beta.2", ExpectedResult = -1)]
+ [TestCase("1.0-beta.1", "1.0-beta.2", ExpectedResult = -1)]
+ [TestCase("1.0-beta.2", "1.0-beta.10", ExpectedResult = -1)]
+ [TestCase("1.0-beta-2", "1.0-beta-10", ExpectedResult = -1)]
+
+ // more than
+ [TestCase("0.5.8", "0.5.7", ExpectedResult = 1)]
+ [TestCase("1.1", "1.0", ExpectedResult = 1)]
+ [TestCase("1.0", "1.0-beta", ExpectedResult = 1)]
+ [TestCase("1.0-beta.2", "1.0-beta", ExpectedResult = 1)]
+ [TestCase("1.0-beta.2", "1.0-beta.1", ExpectedResult = 1)]
+ [TestCase("1.0-beta.10", "1.0-beta.2", ExpectedResult = 1)]
+ [TestCase("1.0-beta-10", "1.0-beta-2", ExpectedResult = 1)]
+ public int CompareTo(string versionStrA, string versionStrB)
+ {
+ ISemanticVersion versionA = new SemanticVersion(versionStrA);
+ ISemanticVersion versionB = new SemanticVersion(versionStrB);
+ return versionA.CompareTo(versionB);
+ }
+
+ /****
+ ** IsOlderThan
+ ****/
+ [Test(Description = "Assert that version.IsOlderThan returns the expected value.")]
+ // keep test cases in sync with CompareTo for simplicity.
+ // equal
+ [TestCase("0.5.7", "0.5.7", ExpectedResult = false)]
+ [TestCase("1.0", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta", ExpectedResult = false)]
+ [TestCase("1.0-beta.10", "1.0-beta.10", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta ", ExpectedResult = false)]
+
+ // less than
+ [TestCase("0.5.7", "0.5.8", ExpectedResult = true)]
+ [TestCase("1.0", "1.1", ExpectedResult = true)]
+ [TestCase("1.0-beta", "1.0", ExpectedResult = true)]
+ [TestCase("1.0-beta", "1.0-beta.2", ExpectedResult = true)]
+ [TestCase("1.0-beta.1", "1.0-beta.2", ExpectedResult = true)]
+ [TestCase("1.0-beta.2", "1.0-beta.10", ExpectedResult = true)]
+ [TestCase("1.0-beta-2", "1.0-beta-10", ExpectedResult = true)]
+
+ // more than
+ [TestCase("0.5.8", "0.5.7", ExpectedResult = false)]
+ [TestCase("1.1", "1.0", ExpectedResult = false)]
+ [TestCase("1.0", "1.0-beta", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.0-beta", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.0-beta.1", ExpectedResult = false)]
+ [TestCase("1.0-beta.10", "1.0-beta.2", ExpectedResult = false)]
+ [TestCase("1.0-beta-10", "1.0-beta-2", ExpectedResult = false)]
+ public bool IsOlderThan(string versionStrA, string versionStrB)
+ {
+ ISemanticVersion versionA = new SemanticVersion(versionStrA);
+ ISemanticVersion versionB = new SemanticVersion(versionStrB);
+ return versionA.IsOlderThan(versionB);
+ }
+
+ /****
+ ** IsNewerThan
+ ****/
+ [Test(Description = "Assert that version.IsNewerThan returns the expected value.")]
+ // keep test cases in sync with CompareTo for simplicity.
+ // equal
+ [TestCase("0.5.7", "0.5.7", ExpectedResult = false)]
+ [TestCase("1.0", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta", ExpectedResult = false)]
+ [TestCase("1.0-beta.10", "1.0-beta.10", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta ", ExpectedResult = false)]
+
+ // less than
+ [TestCase("0.5.7", "0.5.8", ExpectedResult = false)]
+ [TestCase("1.0", "1.1", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta.2", ExpectedResult = false)]
+ [TestCase("1.0-beta.1", "1.0-beta.2", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.0-beta.10", ExpectedResult = false)]
+ [TestCase("1.0-beta-2", "1.0-beta-10", ExpectedResult = false)]
+
+ // more than
+ [TestCase("0.5.8", "0.5.7", ExpectedResult = true)]
+ [TestCase("1.1", "1.0", ExpectedResult = true)]
+ [TestCase("1.0", "1.0-beta", ExpectedResult = true)]
+ [TestCase("1.0-beta.2", "1.0-beta", ExpectedResult = true)]
+ [TestCase("1.0-beta.2", "1.0-beta.1", ExpectedResult = true)]
+ [TestCase("1.0-beta.10", "1.0-beta.2", ExpectedResult = true)]
+ [TestCase("1.0-beta-10", "1.0-beta-2", ExpectedResult = true)]
+ public bool IsNewerThan(string versionStrA, string versionStrB)
+ {
+ ISemanticVersion versionA = new SemanticVersion(versionStrA);
+ ISemanticVersion versionB = new SemanticVersion(versionStrB);
+ return versionA.IsNewerThan(versionB);
+ }
+
+ /****
+ ** IsBetween
+ ****/
+ [Test(Description = "Assert that version.IsNewerThan returns the expected value.")]
+ // is between
+ [TestCase("0.5.7-beta.3", "0.5.7-beta.3", "0.5.7-beta.3", ExpectedResult = true)]
+ [TestCase("1.0", "1.0", "1.1", ExpectedResult = true)]
+ [TestCase("1.0", "1.0-beta", "1.1", ExpectedResult = true)]
+ [TestCase("1.0", "0.5", "1.1", ExpectedResult = true)]
+ [TestCase("1.0-beta.2", "1.0-beta.1", "1.0-beta.3", ExpectedResult = true)]
+ [TestCase("1.0-beta-2", "1.0-beta-1", "1.0-beta-3", ExpectedResult = true)]
+
+ // is not between
+ [TestCase("1.0-beta", "1.0", "1.1", ExpectedResult = false)]
+ [TestCase("1.0", "1.1", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.1", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.0-beta.10", "1.0-beta.3", ExpectedResult = false)]
+ [TestCase("1.0-beta-2", "1.0-beta-10", "1.0-beta-3", ExpectedResult = false)]
+ public bool IsBetween(string versionStr, string lowerStr, string upperStr)
+ {
+ ISemanticVersion lower = new SemanticVersion(lowerStr);
+ ISemanticVersion upper = new SemanticVersion(upperStr);
+ ISemanticVersion version = new SemanticVersion(versionStr);
+ return version.IsBetween(lower, upper);
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Assert that the expected exception type is thrown, and log the action output and thrown exception.</summary>
+ /// <typeparam name="T">The expected exception type.</typeparam>
+ /// <param name="action">The action which may throw the exception.</param>
+ /// <param name="message">The message to log if the expected exception isn't thrown.</param>
+ [SuppressMessage("ReSharper", "UnusedParameter.Local", Justification = "The message argument is deliberately only used in precondition checks since this is an assertion method.")]
+ private void AssertAndLogException<T>(Func<object> action, string message = null)
+ where T : Exception
+ {
+ this.AssertAndLogException<T>(() =>
+ {
+ object result = action();
+ TestContext.WriteLine($"Func result: {result}");
+ });
+ }
+
+ /// <summary>Assert that the expected exception type is thrown, and log the thrown exception.</summary>
+ /// <typeparam name="T">The expected exception type.</typeparam>
+ /// <param name="action">The action which may throw the exception.</param>
+ /// <param name="message">The message to log if the expected exception isn't thrown.</param>
+ [SuppressMessage("ReSharper", "UnusedParameter.Local", Justification = "The message argument is deliberately only used in precondition checks since this is an assertion method.")]
+ private void AssertAndLogException<T>(Action action, string message = null)
+ where T : Exception
+ {
+ try
+ {
+ action();
+ }
+ catch (T ex)
+ {
+ TestContext.WriteLine($"Exception thrown:\n{ex}");
+ return;
+ }
+ catch (Exception ex) when (!(ex is AssertionException))
+ {
+ TestContext.WriteLine($"Exception thrown:\n{ex}");
+ Assert.Fail(message ?? $"Didn't throw the expected exception; expected {typeof(T).FullName}, got {ex.GetType().FullName}.");
+ }
+
+ // no exception thrown
+ Assert.Fail(message ?? "Didn't throw an exception.");
+ }
+ }
+}