summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJesse Plamondon-Willard <github@jplamondonw.com>2017-06-02 18:25:34 -0400
committerJesse Plamondon-Willard <github@jplamondonw.com>2017-06-02 18:25:34 -0400
commit559203922bcad4071f8be53b1a61b0026da14396 (patch)
tree2ed664798183d77779beb68b61bd7622140413df
parent933e889c24e565d9028d3719ba2d65d512890564 (diff)
parent3a8e77a3098572fa413a27f41f832563daec3453 (diff)
downloadSMAPI-559203922bcad4071f8be53b1a61b0026da14396.tar.gz
SMAPI-559203922bcad4071f8be53b1a61b0026da14396.tar.bz2
SMAPI-559203922bcad4071f8be53b1a61b0026da14396.zip
Merge branch 'develop' into stable
-rw-r--r--lib/libgdiplus.dylibbin1202796 -> 0 bytes
-rw-r--r--release-notes.md32
-rw-r--r--src/GlobalAssemblyInfo.cs4
-rw-r--r--src/StardewModdingAPI.Installer/InteractiveInstaller.cs6
-rw-r--r--src/StardewModdingAPI.Installer/readme.txt10
-rw-r--r--src/StardewModdingAPI.Tests/ModResolverTests.cs45
-rw-r--r--src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj2
-rw-r--r--src/StardewModdingAPI.Tests/TranslationTests.cs348
-rw-r--r--src/StardewModdingAPI/Constants.cs4
-rw-r--r--src/StardewModdingAPI/Context.cs12
-rw-r--r--src/StardewModdingAPI/Events/ContentEvents.cs37
-rw-r--r--src/StardewModdingAPI/Events/GameEvents.cs98
-rw-r--r--src/StardewModdingAPI/Events/PlayerEvents.cs48
-rw-r--r--src/StardewModdingAPI/Events/TimeEvents.cs75
-rw-r--r--src/StardewModdingAPI/Framework/CommandHelper.cs2
-rw-r--r--src/StardewModdingAPI/Framework/ContentHelper.cs113
-rw-r--r--src/StardewModdingAPI/Framework/Exceptions/SContentLoadException.cs18
-rw-r--r--src/StardewModdingAPI/Framework/InternalExtensions.cs38
-rw-r--r--src/StardewModdingAPI/Framework/Logging/LogFileManager.cs11
-rw-r--r--src/StardewModdingAPI/Framework/ModHelper.cs8
-rw-r--r--src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs10
-rw-r--r--src/StardewModdingAPI/Framework/ModRegistry.cs10
-rw-r--r--src/StardewModdingAPI/Framework/Models/Manifest.cs2
-rw-r--r--src/StardewModdingAPI/Framework/SContentManager.cs6
-rw-r--r--src/StardewModdingAPI/Framework/SGame.cs83
-rw-r--r--src/StardewModdingAPI/Framework/TranslationHelper.cs137
-rw-r--r--src/StardewModdingAPI/IManifest.cs2
-rw-r--r--src/StardewModdingAPI/IModHelper.cs3
-rw-r--r--src/StardewModdingAPI/ITranslationHelper.cs34
-rw-r--r--src/StardewModdingAPI/Program.cs165
-rw-r--r--src/StardewModdingAPI/StardewModdingAPI.config.json12
-rw-r--r--src/StardewModdingAPI/StardewModdingAPI.csproj4
-rw-r--r--src/StardewModdingAPI/Translation.cs150
-rw-r--r--src/StardewModdingAPI/unix-launcher.sh119
-rw-r--r--src/TrainerMod/TrainerMod.cs8
-rw-r--r--src/TrainerMod/manifest.json2
-rw-r--r--src/crossplatform.targets1
-rw-r--r--src/prepare-install-package.targets3
38 files changed, 1330 insertions, 332 deletions
diff --git a/lib/libgdiplus.dylib b/lib/libgdiplus.dylib
deleted file mode 100644
index 8a9676c8..00000000
--- a/lib/libgdiplus.dylib
+++ /dev/null
Binary files differ
diff --git a/release-notes.md b/release-notes.md
index b7f5f1f7..39d2fed5 100644
--- a/release-notes.md
+++ b/release-notes.md
@@ -10,6 +10,34 @@ For mod developers:
images).
-->
+## 1.14
+See [log](https://github.com/Pathoschild/SMAPI/compare/1.13.1...1.14).
+
+For players:
+* SMAPI now shows friendly errors when...
+ * it can't detect the game;
+ * a mod dependency is missing (if it's listed in the mod manifest);
+ * you have Stardew Valley 1.11 or earlier (which aren't compatible);
+ * you run `install.exe` from within the downloaded zip file.
+* Fixed "unknown mod" deprecation warnings by improving how SMAPI detects the mod using the event.
+* Fixed `libgdiplus.dylib` errors for some players on Mac.
+* Fixed rare crash when window loses focus for a few players.
+* Bumped minimum game version to 1.2.30.
+* Updated mod compatibility list.
+
+For modders:
+* You can now add dependencies to `manifest.json`.
+ <small>_SMAPI will make sure your dependencies are loaded before your mod, and will show a friendly error if a dependency is missing._</small>
+* You can now load unpacked `.tbin` files from your mod folder through the content API.
+* SMAPI now automatically fixes tilesheet references for maps loaded from the mod folder.
+ <small>_When loading a map from the mod folder, SMAPI will automatically use tilesheets relative to the map file if they exists. Otherwise it will default to tilesheets in the game content._</small>
+* Added `Context.IsPlayerFree` for mods that need to check if the player can act (i.e. save is loaded, no menu is displayed, no cutscene is in progress, etc).
+* Added `Context.IsInDrawLoop` for specialised mods.
+* Fixed `smapi-crash.txt` being copied from the default log even if a different path is specified with `--log-path`.
+* Fixed the content API not matching XNB filenames with two dots (like `a.b.xnb`) if you don't specify the `.xnb` extension.
+* Fixed `debug` command output not printed to console.
+* Deprecated `TimeEvents.DayOfMonthChanged`, `SeasonOfYearChanged`, and `YearOfGameChanged`. These don't do what most modders think they do and aren't very reliable, since they depend on the SMAPI/game lifecycle which can change. You should use `TimeEvents.AfterDayStarted` or `SaveEvents.BeforeSave` instead.
+
## 1.13.1
See [log](https://github.com/Pathoschild/SMAPI/compare/1.13...1.13.1).
@@ -31,7 +59,7 @@ For players:
For mod developers:
* Added a `Context.IsWorldReady` flag for mods to use.
- _<small>This indicates whether a save is loaded and the world is finished initialising, which starts at the same point that `SaveEvents.AfterLoad` and `TimeEvents.AfterDayStarted` are raised. This is mainly useful for events which can be raised before the world is loaded (like update tick).</small>_
+ <small>_This indicates whether a save is loaded and the world is finished initialising, which starts at the same point that `SaveEvents.AfterLoad` and `TimeEvents.AfterDayStarted` are raised. This is mainly useful for events which can be raised before the world is loaded (like update tick)._</small>
* Added a `debug` console command which lets you run the game's debug commands (e.g. `debug warp FarmHouse 1 1` warps you to the farmhouse).
* Added basic context info to logs to simplify troubleshooting.
* Added a `Mod.Dispose` method which can be overriden to clean up before exit. This method isn't guaranteed to be called on every exit.
@@ -47,7 +75,7 @@ For players:
* The installer now lets you choose the install path if you have multiple copies of the game, instead of using the first path found.
* Fixed mod draw errors breaking the game.
* Fixed mods on Linux/Mac no longer working after the game saves.
-* Fixed libgdiplus DLL-not-found errors on Linux/Mac when mods read PNG files.
+* Fixed `libgdiplus.dylib` errors on Mac when mods read PNG files.
* Adopted pufferchick.
For mod developers:
diff --git a/src/GlobalAssemblyInfo.cs b/src/GlobalAssemblyInfo.cs
index 93ff68ec..4344dbce 100644
--- a/src/GlobalAssemblyInfo.cs
+++ b/src/GlobalAssemblyInfo.cs
@@ -2,5 +2,5 @@
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
-[assembly: AssemblyVersion("1.13.1.0")]
-[assembly: AssemblyFileVersion("1.13.1.0")] \ No newline at end of file
+[assembly: AssemblyVersion("1.14.0.0")]
+[assembly: AssemblyFileVersion("1.14.0.0")] \ No newline at end of file
diff --git a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs
index 01f7a01f..efad0a3e 100644
--- a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs
+++ b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs
@@ -85,6 +85,7 @@ namespace StardewModdingApi.Installer
yield return GetInstallPath("steam_appid.txt");
// Linux/Mac only
+ yield return GetInstallPath("libgdiplus.dylib");
yield return GetInstallPath("StardewModdingAPI");
yield return GetInstallPath("StardewModdingAPI.exe.mdb");
yield return GetInstallPath("System.Numerics.dll");
@@ -158,7 +159,10 @@ namespace StardewModdingApi.Installer
****/
if (!packageDir.Exists)
{
- this.PrintError($"The 'internal/{platform}' package folder is missing (should be at {packageDir}).");
+ this.PrintError(platform == Platform.Windows && packageDir.FullName.Contains(Path.GetTempPath()) && packageDir.FullName.Contains(".zip")
+ ? "The installer is missing some files. It looks like you're running the installer from inside the downloaded zip; make sure you unzip the downloaded file first, then run the installer from the unzipped folder."
+ : $"The 'internal/{platform}' package folder is missing (should be at {packageDir})."
+ );
Console.ReadLine();
return;
}
diff --git a/src/StardewModdingAPI.Installer/readme.txt b/src/StardewModdingAPI.Installer/readme.txt
index 4756099e..cf6090c4 100644
--- a/src/StardewModdingAPI.Installer/readme.txt
+++ b/src/StardewModdingAPI.Installer/readme.txt
@@ -13,13 +13,7 @@
SMAPI lets you run Stardew Valley with mods. Don't forget to download mods separately.
-
-To install:
- - Windows: double-click install.exe.
- - Linux or Mac: open a terminal and run `mono install.exe`.
-
-
Need help? See:
- - Install guide: http://canimod.com/guides/using-mods#installing-smapi
- - Troubleshooting: http://canimod.com/guides/smapi-faq#troubleshooting
+ - Install guide: http://canimod.com/for-players/install-smapi
+ - Troubleshooting: http://canimod.com/for-players/faqs#troubleshooting
- Ask for help: https://discord.gg/kH55QXP
diff --git a/src/StardewModdingAPI.Tests/ModResolverTests.cs b/src/StardewModdingAPI.Tests/ModResolverTests.cs
index 8cf5a29e..23aeba64 100644
--- a/src/StardewModdingAPI.Tests/ModResolverTests.cs
+++ b/src/StardewModdingAPI.Tests/ModResolverTests.cs
@@ -13,6 +13,7 @@ using StardewModdingAPI.Tests.Framework;
namespace StardewModdingAPI.Tests
{
+ /// <summary>Unit tests for <see cref="ModResolver"/>.</summary>
[TestFixture]
public class ModResolverTests
{
@@ -71,9 +72,7 @@ namespace StardewModdingAPI.Tests
[nameof(IManifest.UniqueID)] = $"{Sample.String()}.{Sample.String()}",
[nameof(IManifest.EntryDll)] = $"{Sample.String()}.dll",
[nameof(IManifest.MinimumApiVersion)] = $"{Sample.Int()}.{Sample.Int()}-{Sample.String()}",
-#if EXPERIMENTAL
[nameof(IManifest.Dependencies)] = new[] { originalDependency },
-#endif
["ExtraString"] = Sample.String(),
["ExtraInt"] = Sample.Int()
};
@@ -110,11 +109,9 @@ namespace StardewModdingAPI.Tests
Assert.AreEqual(original["ExtraString"], mod.Manifest.ExtraFields["ExtraString"], "The manifest's extra fields should contain an 'ExtraString' value.");
Assert.AreEqual(original["ExtraInt"], mod.Manifest.ExtraFields["ExtraInt"], "The manifest's extra fields should contain an 'ExtraInt' value.");
-#if EXPERIMENTAL
Assert.IsNotNull(mod.Manifest.Dependencies, "The dependencies field should not be null.");
Assert.AreEqual(1, mod.Manifest.Dependencies.Length, "The dependencies field should contain one value.");
Assert.AreEqual(originalDependency[nameof(IManifestDependency.UniqueID)], mod.Manifest.Dependencies[0].UniqueID, "The first dependency's unique ID doesn't match.");
-#endif
}
/****
@@ -216,7 +213,6 @@ namespace StardewModdingAPI.Tests
// if Moq doesn't throw a method-not-setup exception, the validation didn't override the status.
}
-#if EXPERIMENTAL
/****
** ProcessDependencies
****/
@@ -249,6 +245,20 @@ namespace StardewModdingAPI.Tests
Assert.AreSame(modC.Object, mods[2], "The load order unexpectedly changed with no dependencies.");
}
+ [Test(Description = "Assert that processing dependencies skips mods that have already failed without calling any other properties.")]
+ public void ProcessDependencies_Skips_Failed()
+ {
+ // arrange
+ Mock<IModMetadata> mock = new Mock<IModMetadata>(MockBehavior.Strict);
+ mock.Setup(p => p.Status).Returns(ModMetadataStatus.Failed);
+
+ // act
+ new ModResolver().ProcessDependencies(new[] { mock.Object });
+
+ // assert
+ mock.VerifyGet(p => p.Status, Times.Once, "The validation did not check the manifest status.");
+ }
+
[Test(Description = "Assert that simple dependencies are reordered correctly.")]
public void ProcessDependencies_Reorders_SimpleDependencies()
{
@@ -345,8 +355,29 @@ namespace StardewModdingAPI.Tests
modD.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<string>()), Times.Once, "Mod D was expected to fail since it's part of a dependency loop.");
modE.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<string>()), Times.Once, "Mod E was expected to fail since it's part of a dependency loop.");
}
-#endif
+ [Test(Description = "Assert that dependencies are sorted correctly even if some of the mods failed during metadata loading.")]
+ public void ProcessDependencies_WithSomeFailedMods_Succeeds()
+ {
+ // 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> modD = new Mock<IModMetadata>(MockBehavior.Strict);
+ modD.Setup(p => p.Manifest).Returns<IManifest>(null);
+ modD.Setup(p => p.Status).Returns(ModMetadataStatus.Failed);
+
+ // act
+ IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modC.Object, modA.Object, modB.Object, modD.Object }).ToArray();
+
+ // assert
+ Assert.AreEqual(4, mods.Length, 0, "Expected to get the same number of mods input.");
+ Assert.AreSame(modD.Object, mods[0], "The load order is incorrect: mod D should be first since it was already failed.");
+ Assert.AreSame(modA.Object, mods[1], "The load order is incorrect: mod A should be second since it's needed by mod B.");
+ Assert.AreSame(modB.Object, mods[2], "The load order is incorrect: mod B should be third since it needs mod A, and is needed by mod C.");
+ 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.");
+ }
/*********
** Private methods
@@ -368,7 +399,6 @@ namespace StardewModdingAPI.Tests
return manifest;
}
-#if EXPERIMENTAL
/// <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>
@@ -395,6 +425,5 @@ namespace StardewModdingAPI.Tests
}
return mod;
}
-#endif
}
}
diff --git a/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj b/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj
index c84adbd7..3818ec9c 100644
--- a/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj
+++ b/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj
@@ -48,6 +48,7 @@
<Compile Include="..\GlobalAssemblyInfo.cs">
<Link>Properties\GlobalAssemblyInfo.cs</Link>
</Compile>
+ <Compile Include="TranslationTests.cs" />
<Compile Include="ModResolverTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Framework\Sample.cs" />
@@ -61,5 +62,6 @@
<Name>StardewModdingAPI</Name>
</ProjectReference>
</ItemGroup>
+ <Import Project="$(SolutionDir)\crossplatform.targets" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> \ No newline at end of file
diff --git a/src/StardewModdingAPI.Tests/TranslationTests.cs b/src/StardewModdingAPI.Tests/TranslationTests.cs
new file mode 100644
index 00000000..6a430aa7
--- /dev/null
+++ b/src/StardewModdingAPI.Tests/TranslationTests.cs
@@ -0,0 +1,348 @@
+using System;
+using System.Collections.Generic;
+using NUnit.Framework;
+using StardewModdingAPI.Framework;
+using StardewValley;
+
+namespace StardewModdingAPI.Tests
+{
+ /// <summary>Unit tests for <see cref="TranslationHelper"/> and <see cref="Translation"/>.</summary>
+ [TestFixture]
+ public class TranslationTests
+ {
+ /*********
+ ** Data
+ *********/
+ /// <summary>Sample translation text for unit tests.</summary>
+ public static string[] Samples = { null, "", " ", "boop", " boop " };
+
+
+ /*********
+ ** Unit tests
+ *********/
+ /****
+ ** Translation helper
+ ****/
+ [Test(Description = "Assert that the translation helper correctly handles no translations.")]
+ public void Helper_HandlesNoTranslations()
+ {
+ // arrange
+ var data = new Dictionary<string, IDictionary<string, string>>();
+
+ // act
+ ITranslationHelper helper = new TranslationHelper("ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
+ Translation translation = helper.Get("key");
+
+ // assert
+ Assert.AreEqual("en", helper.Locale, "The locale doesn't match the input value.");
+ Assert.AreEqual(LocalizedContentManager.LanguageCode.en, helper.LocaleEnum, "The locale enum doesn't match the input value.");
+ Assert.IsNotNull(helper.GetTranslations(), "The full list of translations is unexpectedly null.");
+ Assert.AreEqual(0, helper.GetTranslations().Count, "The full list of translations is unexpectedly not empty.");
+
+ Assert.IsNotNull(translation, "The translation helper unexpectedly returned a null translation.");
+ Assert.AreEqual(this.GetPlaceholderText("key"), translation.ToString(), "The translation returned an unexpected value.");
+ }
+
+ [Test(Description = "Assert that the translation helper returns the expected translations correctly.")]
+ public void Helper_GetTranslations_ReturnsExpectedText()
+ {
+ // arrange
+ var data = this.GetSampleData();
+ var expected = this.GetExpectedTranslations();
+
+ // act
+ var actual = new Dictionary<string, IDictionary<string, string>>();
+ TranslationHelper helper = new TranslationHelper("ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
+ foreach (string locale in expected.Keys)
+ {
+ this.AssertSetLocale(helper, locale, LocalizedContentManager.LanguageCode.en);
+ actual[locale] = helper.GetTranslations();
+ }
+
+ // assert
+ foreach (string locale in expected.Keys)
+ {
+ Assert.IsNotNull(actual[locale], $"The translations for {locale} is unexpectedly null.");
+ Assert.That(actual[locale], Is.EquivalentTo(expected[locale]), $"The translations for {locale} don't match the expected values.");
+ }
+ }
+
+ [Test(Description = "Assert that the translations returned by the helper has the expected text.")]
+ public void Helper_Get_ReturnsExpectedText()
+ {
+ // arrange
+ var data = this.GetSampleData();
+ var expected = this.GetExpectedTranslations();
+
+ // act
+ var actual = new Dictionary<string, IDictionary<string, string>>();
+ TranslationHelper helper = new TranslationHelper("ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
+ foreach (string locale in expected.Keys)
+ {
+ this.AssertSetLocale(helper, locale, LocalizedContentManager.LanguageCode.en);
+ actual[locale] = new Dictionary<string, string>();
+ foreach (string key in expected[locale].Keys)
+ actual[locale][key] = helper.Get(key);
+ }
+
+ // assert
+ foreach (string locale in expected.Keys)
+ {
+ Assert.IsNotNull(actual[locale], $"The translations for {locale} is unexpectedly null.");
+ Assert.That(actual[locale], Is.EquivalentTo(expected[locale]), $"The translations for {locale} don't match the expected values.");
+ }
+ }
+
+ /****
+ ** Translation
+ ****/
+ [Test(Description = "Assert that HasValue returns the expected result for various inputs.")]
+ [TestCase(null, ExpectedResult = false)]
+ [TestCase("", ExpectedResult = false)]
+ [TestCase(" ", ExpectedResult = true)]
+ [TestCase("boop", ExpectedResult = true)]
+ [TestCase(" boop ", ExpectedResult = true)]
+ public bool Translation_HasValue(string text)
+ {
+ return new Translation("ModName", "pt-BR", "key", text).HasValue();
+ }
+
+ [Test(Description = "Assert that the translation's ToString method returns the expected text for various inputs.")]
+ public void Translation_ToString([ValueSource(nameof(TranslationTests.Samples))] string text)
+ {
+ // act
+ Translation translation = new Translation("ModName", "pt-BR", "key", text);
+
+ // assert
+ if (translation.HasValue())
+ Assert.AreEqual(text, translation.ToString(), "The translation returned an unexpected value given a valid input.");
+ else
+ Assert.AreEqual(this.GetPlaceholderText("key"), translation.ToString(), "The translation returned an unexpected value given a null or empty input.");
+ }
+
+ [Test(Description = "Assert that the translation's implicit string conversion returns the expected text for various inputs.")]
+ public void Translation_ImplicitStringConversion([ValueSource(nameof(TranslationTests.Samples))] string text)
+ {
+ // act
+ Translation translation = new Translation("ModName", "pt-BR", "key", text);
+
+ // assert
+ if (translation.HasValue())
+ Assert.AreEqual(text, (string)translation, "The translation returned an unexpected value given a valid input.");
+ else
+ Assert.AreEqual(this.GetPlaceholderText("key"), (string)translation, "The translation returned an unexpected value given a null or empty input.");
+ }
+
+ [Test(Description = "Assert that the translation returns the expected text given a use-placeholder setting.")]
+ public void Translation_UsePlaceholder([Values(true, false)] bool value, [ValueSource(nameof(TranslationTests.Samples))] string text)
+ {
+ // act
+ Translation translation = new Translation("ModName", "pt-BR", "key", text).UsePlaceholder(value);
+
+ // assert
+ if (translation.HasValue())
+ Assert.AreEqual(text, translation.ToString(), "The translation returned an unexpected value given a valid input.");
+ else if (!value)
+ Assert.AreEqual(text, translation.ToString(), "The translation returned an unexpected value given a null or empty input with the placeholder disabled.");
+ else
+ Assert.AreEqual(this.GetPlaceholderText("key"), translation.ToString(), "The translation returned an unexpected value given a null or empty input with the placeholder enabled.");
+ }
+
+ [Test(Description = "Assert that the translation's Assert method throws the expected exception.")]
+ public void Translation_Assert([ValueSource(nameof(TranslationTests.Samples))] string text)
+ {
+ // act
+ Translation translation = new Translation("ModName", "pt-BR", "key", text);
+
+ // assert
+ if (translation.HasValue())
+ Assert.That(() => translation.Assert(), Throws.Nothing, "The assert unexpected threw an exception for a valid input.");
+ else
+ Assert.That(() => translation.Assert(), Throws.Exception.TypeOf<KeyNotFoundException>(), "The assert didn't throw an exception for invalid input.");
+ }
+
+ [Test(Description = "Assert that the translation returns the expected text after setting the default.")]
+ public void Translation_Default([ValueSource(nameof(TranslationTests.Samples))] string text, [ValueSource(nameof(TranslationTests.Samples))] string @default)
+ {
+ // act
+ Translation translation = new Translation("ModName", "pt-BR", "key", text).Default(@default);
+
+ // assert
+ if (!string.IsNullOrEmpty(text))
+ Assert.AreEqual(text, translation.ToString(), "The translation returned an unexpected value given a valid base text.");
+ else if (!string.IsNullOrEmpty(@default))
+ Assert.AreEqual(@default, translation.ToString(), "The translation returned an unexpected value given a null or empty base text, but valid default.");
+ else
+ Assert.AreEqual(this.GetPlaceholderText("key"), translation.ToString(), "The translation returned an unexpected value given a null or empty base and default text.");
+ }
+
+ /****
+ ** Translation tokens
+ ****/
+ [Test(Description = "Assert that multiple translation tokens are replaced correctly regardless of the token structure.")]
+ public void Translation_Tokens([Values("anonymous object", "class", "IDictionary<string, object>", "IDictionary<string, string>")] string structure)
+ {
+ // arrange
+ string start = Guid.NewGuid().ToString("N");
+ string middle = Guid.NewGuid().ToString("N");
+ string end = Guid.NewGuid().ToString("N");
+ const string input = "{{start}} tokens are properly replaced (including {{middle}} {{ MIDdlE}}) {{end}}";
+ string expected = $"{start} tokens are properly replaced (including {middle} {middle}) {end}";
+
+ // act
+ Translation translation = new Translation("ModName", "pt-BR", "key", input);
+ switch (structure)
+ {
+ case "anonymous object":
+ translation = translation.Tokens(new { start, middle, end });
+ break;
+
+ case "class":
+ translation = translation.Tokens(new TokenModel { Start = start, Middle = middle, End = end });
+ break;
+
+ case "IDictionary<string, object>":
+ translation = translation.Tokens(new Dictionary<string, object> { ["start"] = start, ["middle"] = middle, ["end"] = end });
+ break;
+
+ case "IDictionary<string, string>":
+ translation = translation.Tokens(new Dictionary<string, string> { ["start"] = start, ["middle"] = middle, ["end"] = end });
+ break;
+
+ default:
+ throw new NotSupportedException($"Unknown structure '{structure}'.");
+ }
+
+ // assert
+ Assert.AreEqual(expected, translation.ToString(), "The translation returned an unexpected text.");
+ }
+
+ [Test(Description = "Assert that the translation can replace tokens in all valid formats.")]
+ [TestCase("{{value}}", "value")]
+ [TestCase("{{ value }}", "value")]
+ [TestCase("{{value }}", "value")]
+ [TestCase("{{ the_value }}", "the_value")]
+ [TestCase("{{ the.value_here }}", "the.value_here")]
+ [TestCase("{{ the_value-here.... }}", "the_value-here....")]
+ [TestCase("{{ tHe_vALuE-HEre.... }}", "tHe_vALuE-HEre....")]
+ public void Translation_Tokens_ValidFormats(string text, string key)
+ {
+ // arrange
+ string value = Guid.NewGuid().ToString("N");
+
+ // act
+ Translation translation = new Translation("ModName", "pt-BR", "key", text).Tokens(new Dictionary<string, object> { [key] = value });
+
+ // assert
+ Assert.AreEqual(value, translation.ToString(), "The translation returned an unexpected value given a valid base text.");
+ }
+
+ [Test(Description = "Assert that translation tokens are case-insensitive and surrounding-whitespace-insensitive.")]
+ [TestCase("{{value}}", "value")]
+ [TestCase("{{VaLuE}}", "vAlUe")]
+ [TestCase("{{VaLuE }}", " vAlUe")]
+ public void Translation_Tokens_KeysAreNormalised(string text, string key)
+ {
+ // arrange
+ string value = Guid.NewGuid().ToString("N");
+
+ // act
+ Translation translation = new Translation("ModName", "pt-BR", "key", text).Tokens(new Dictionary<string, object> { [key] = value });
+
+ // assert
+ Assert.AreEqual(value, translation.ToString(), "The translation returned an unexpected value given a valid base text.");
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Set a translation helper's locale and assert that it was set correctly.</summary>
+ /// <param name="helper">The translation helper to change.</param>
+ /// <param name="locale">The expected locale.</param>
+ /// <param name="localeEnum">The expected game language code.</param>
+ private void AssertSetLocale(TranslationHelper helper, string locale, LocalizedContentManager.LanguageCode localeEnum)
+ {
+ helper.SetLocale(locale, localeEnum);
+ Assert.AreEqual(locale, helper.Locale, "The locale doesn't match the input value.");
+ Assert.AreEqual(localeEnum, helper.LocaleEnum, "The locale enum doesn't match the input value.");
+ }
+
+ /// <summary>Get sample raw translations to input.</summary>
+ private IDictionary<string, IDictionary<string, string>> GetSampleData()
+ {
+ return new Dictionary<string, IDictionary<string, string>>
+ {
+ ["default"] = new Dictionary<string, string>
+ {
+ ["key A"] = "default A",
+ ["key C"] = "default C"
+ },
+ ["en"] = new Dictionary<string, string>
+ {
+ ["key A"] = "en A",
+ ["key B"] = "en B"
+ },
+ ["en-US"] = new Dictionary<string, string>(),
+ ["zzz"] = new Dictionary<string, string>
+ {
+ ["key A"] = "zzz A"
+ }
+ };
+ }
+
+ /// <summary&