diff --git a/Tests/CmdLine/InstallTests.cs b/Tests/CmdLine/InstallTests.cs index 4e19815204..e2a9d8efdd 100644 --- a/Tests/CmdLine/InstallTests.cs +++ b/Tests/CmdLine/InstallTests.cs @@ -76,8 +76,8 @@ public void RunCommand_IdentifierEqualsVersionSyntax_InstallsCorrectVersion( var regMgr = RegistryManager.Instance(inst.KSP, repoData.Manager); regMgr.registry.RepositoriesClear(); regMgr.registry.RepositoriesAdd(repo.repo); - var module = regMgr.registry.GetModuleByVersion(identifier, version); - manager.Cache.Store(module, TestData.DogeCoinFlagZip(), null); + var module = regMgr.registry.GetModuleByVersion(identifier, version)!; + manager.Cache?.Store(module, TestData.DogeCoinFlagZip(), null); var opts = new InstallOptions() { modules = new List { $"{identifier}={version}" }, diff --git a/Tests/CmdLine/UpgradeTests.cs b/Tests/CmdLine/UpgradeTests.cs index c54f5a807f..b6254b6368 100644 --- a/Tests/CmdLine/UpgradeTests.cs +++ b/Tests/CmdLine/UpgradeTests.cs @@ -77,10 +77,10 @@ public void RunCommand_IdentifierEqualsVersionSyntax_UpgradesToCorrectVersion( var regMgr = RegistryManager.Instance(inst.KSP, repoData.Manager); regMgr.registry.RepositoriesClear(); regMgr.registry.RepositoriesAdd(repo.repo); - var fromModule = regMgr.registry.GetModuleByVersion(identifier, fromVersion); - var toModule = regMgr.registry.GetModuleByVersion(identifier, toVersion); + var fromModule = regMgr.registry.GetModuleByVersion(identifier, fromVersion)!; + var toModule = regMgr.registry.GetModuleByVersion(identifier, toVersion)!; regMgr.registry.RegisterModule(fromModule, new List(), inst.KSP, false); - manager.Cache.Store(toModule, TestData.DogeCoinFlagZip(), null); + manager.Cache?.Store(toModule, TestData.DogeCoinFlagZip(), null); var opts = new UpgradeOptions() { modules = new List { $"{identifier}={toVersion}" }, @@ -632,7 +632,7 @@ public void RunCommand_VersionDependsUpgrade_UpgradesCorrectly(string descript // Pre-store mods that might be installed foreach (var toModule in addlModules.Select(CkanModule.FromJson)) { - manager.Cache.Store(toModule, TestData.DogeCoinFlagZip(), null); + manager.Cache?.Store(toModule, TestData.DogeCoinFlagZip(), null); } // Simulate passing `--all` var opts = upgradeIdentifiers != null @@ -652,10 +652,10 @@ public void RunCommand_VersionDependsUpgrade_UpgradesCorrectly(string descript // Assert CollectionAssert.AreEqual(versionsAfter, - instMods.Select(m => regMgr.registry - .GetInstalledVersion(m.identifier) - .version - .ToString()) + instMods.Select(m => regMgr?.registry + .GetInstalledVersion(m.identifier) + ?.version + .ToString()) .ToArray(), description); diff --git a/Tests/Core/Cache.cs b/Tests/Core/Cache.cs index 2ac98103ba..9a0c8120aa 100644 --- a/Tests/Core/Cache.cs +++ b/Tests/Core/Cache.cs @@ -13,10 +13,10 @@ namespace Tests.Core [TestFixture] public class Cache { - private string cache_dir; + private string? cache_dir; - private NetFileCache cache; - private NetModuleCache module_cache; + private NetFileCache? cache; + private NetModuleCache? module_cache; [SetUp] public void MakeCache() @@ -30,11 +30,14 @@ public void MakeCache() [TearDown] public void RemoveCache() { - cache.Dispose(); + cache?.Dispose(); cache = null; - module_cache.Dispose(); + module_cache?.Dispose(); module_cache = null; - Directory.Delete(cache_dir, true); + if (cache_dir != null) + { + Directory.Delete(cache_dir, true); + } } [Test] @@ -51,30 +54,32 @@ public void StoreRetrieve() string file = TestData.DogeCoinFlagZip(); // Our URL shouldn't be cached to begin with. - Assert.IsFalse(cache.IsCached(url)); + Assert.IsFalse(cache?.IsCached(url)); // Store our file. - cache.Store(url, file); + cache?.Store(url, file); // Now it should be cached. - Assert.IsTrue(cache.IsCached(url)); + Assert.IsTrue(cache?.IsCached(url)); // Check contents match. - string cached_file = cache.GetCachedFilename(url); + var cached_file = cache?.GetCachedFilename(url); FileAssert.AreEqual(file, cached_file); } - [Test, TestCase("cheesy.zip","cheesy.zip"), TestCase("Foo-1-2.3","Foo-1-2.3"), - TestCase("Foo-1-2-3","Foo-1-2-3"), TestCase("Foo-..-etc-passwd","Foo-..-etc-passwd")] + [Test, TestCase("cheesy.zip","cheesy.zip"), + TestCase("Foo-1-2.3","Foo-1-2.3"), + TestCase("Foo-1-2-3","Foo-1-2-3"), + TestCase("Foo-..-etc-passwd","Foo-..-etc-passwd")] public void NamingHints(string hint, string appendage) { Uri url = new Uri("http://example.com/"); string file = TestData.DogeCoinFlagZip(); - Assert.IsFalse(cache.IsCached(url)); - cache.Store(url, file, hint); + Assert.IsFalse(cache?.IsCached(url)); + cache?.Store(url, file, hint); - StringAssert.EndsWith(appendage, cache.GetCachedFilename(url)); + StringAssert.EndsWith(appendage, cache?.GetCachedFilename(url)); } [Test] @@ -83,13 +88,13 @@ public void StoreRemove() Uri url = new Uri("http://example.com/"); string file = TestData.DogeCoinFlagZip(); - Assert.IsFalse(cache.IsCached(url)); - cache.Store(url, file); - Assert.IsTrue(cache.IsCached(url)); + Assert.IsFalse(cache?.IsCached(url)); + cache?.Store(url, file); + Assert.IsTrue(cache?.IsCached(url)); - cache.Remove(url); + cache?.Remove(url); - Assert.IsFalse(cache.IsCached(url)); + Assert.IsFalse(cache?.IsCached(url)); } [Test] @@ -113,14 +118,14 @@ public void StoreInvalid() // Try to store a nonexistent zip into a NetModuleCache // and expect an FileNotFoundKraken Assert.Throws(() => - module_cache.Store( + module_cache?.Store( TestData.DogeCoinFlag_101_LZMA_module, "/DoesNotExist.zip", new Progress(percent => {}))); // Try to store the LZMA-format DogeCoin zip into a NetModuleCache // and expect an InvalidModuleFileKraken Assert.Throws(() => - module_cache.Store( + module_cache?.Store( TestData.DogeCoinFlag_101_LZMA_module, TestData.DogeCoinFlagZipLZMA, new Progress(percent => {}))); @@ -128,7 +133,7 @@ public void StoreInvalid() // using the WRONG metadata (file size and hashes) // and expect an InvalidModuleFileKraken Assert.Throws(() => - module_cache.Store( + module_cache?.Store( TestData.DogeCoinFlag_101_LZMA_module, TestData.DogeCoinFlagZip(), new Progress(percent => {}))); } @@ -140,19 +145,19 @@ public void DoubleCache() // the most recent file we store for any given URL. Uri url = new Uri("http://Double.Rainbow.What.Does.It.Mean/"); - Assert.IsFalse(cache.IsCached(url)); + Assert.IsFalse(cache?.IsCached(url)); string file1 = TestData.DogeCoinFlagZip(); string file2 = TestData.ModuleManagerZip(); - cache.Store(url, file1); - FileAssert.AreEqual(file1, cache.GetCachedFilename(url)); + cache?.Store(url, file1); + FileAssert.AreEqual(file1, cache?.GetCachedFilename(url)); - cache.Store(url, file2); - FileAssert.AreEqual(file2, cache.GetCachedFilename(url)); + cache?.Store(url, file2); + FileAssert.AreEqual(file2, cache?.GetCachedFilename(url)); - cache.Store(url, file1); - FileAssert.AreEqual(file1, cache.GetCachedFilename(url)); + cache?.Store(url, file1); + FileAssert.AreEqual(file1, cache?.GetCachedFilename(url)); } [Test] @@ -161,21 +166,22 @@ public void ZipValidation() // We could use any URL, but this one is awesome. <3 Uri url = new Uri("http://kitte.nz/"); - Assert.IsFalse(cache.IsCached(url)); + Assert.IsFalse(cache?.IsCached(url)); // Store a bad zip. - cache.Store(url, TestData.DogeCoinFlagZipCorrupt()); + cache?.Store(url, TestData.DogeCoinFlagZipCorrupt()); // Make sure it's stored - Assert.IsTrue(cache.IsCached(url)); + Assert.IsTrue(cache?.IsCached(url)); // Make sure it's not valid as a zip - Assert.IsFalse(NetModuleCache.ZipValid(cache.GetCachedFilename(url), out _, null)); + Assert.IsFalse(NetModuleCache.ZipValid(cache?.GetCachedFilename(url) ?? "", + out _, null)); // Store a good zip. - cache.Store(url, TestData.DogeCoinFlagZip()); + cache?.Store(url, TestData.DogeCoinFlagZip()); // Make sure it's stored, and valid. - Assert.IsTrue(cache.IsCached(url)); + Assert.IsTrue(cache?.IsCached(url)); } [Test] @@ -209,7 +215,7 @@ public void ZipValid_ContainsFilenameWithBadChars_NoException() public void ZipValid_ContainsFilenameWithUnicodeChars_Valid() { bool valid = false; - string reason = null; + string? reason = null; Assert.DoesNotThrow(() => valid = NetModuleCache.ZipValid(TestData.ZipWithUnicodeChars, out reason, null)); @@ -225,11 +231,11 @@ public void EnforceSizeLimit_UnderLimit_FileRetained() // Act Uri url = new Uri("http://kitte.nz/"); - cache.Store(url, TestData.DogeCoinFlagZip()); - cache.EnforceSizeLimit(fileSize + 100, registry); + cache?.Store(url, TestData.DogeCoinFlagZip()); + cache?.EnforceSizeLimit(fileSize + 100, registry); // Assert - Assert.IsTrue(cache.IsCached(url)); + Assert.IsTrue(cache?.IsCached(url)); } [Test] @@ -241,11 +247,11 @@ public void EnforceSizeLimit_OverLimit_FileRemoved() // Act Uri url = new Uri("http://kitte.nz/"); - cache.Store(url, TestData.DogeCoinFlagZip()); - cache.EnforceSizeLimit(fileSize - 100, registry); + cache?.Store(url, TestData.DogeCoinFlagZip()); + cache?.EnforceSizeLimit(fileSize - 100, registry); // Assert - Assert.IsFalse(cache.IsCached(url)); + Assert.IsFalse(cache?.IsCached(url)); } } diff --git a/Tests/Core/Configuration/FakeConfiguration.cs b/Tests/Core/Configuration/FakeConfiguration.cs index 5177552bd0..145bc28bd3 100644 --- a/Tests/Core/Configuration/FakeConfiguration.cs +++ b/Tests/Core/Configuration/FakeConfiguration.cs @@ -26,7 +26,7 @@ public FakeConfiguration(CKAN.GameInstance instance, string autostart) /// /// List of name/path pairs for the instances /// The auto start instance to use - public FakeConfiguration(List> instances, string auto_start_instance) + public FakeConfiguration(List> instances, string? auto_start_instance) { Instances = instances; AutoStartInstance = auto_start_instance; @@ -40,11 +40,11 @@ public FakeConfiguration(List> instances, string a /// /// Build map for the fake registry /// - public JBuilds BuildMap { get; set; } + public JBuilds? BuildMap { get; set; } /// /// Path to download cache folder for the fake registry /// - public string DownloadCacheDir { get; set; } + public string? DownloadCacheDir { get; set; } /// /// Maximum number of bytes of downloads to retain on disk /// @@ -60,12 +60,12 @@ public FakeConfiguration(List> instances, string a public int InstanceCount => Instances.Count; // In the Win32Registry it is not possible to get null in autostart. - private string _AutoStartInstance; + private string? _AutoStartInstance; /// /// The auto start instance for the fake registry /// - public string AutoStartInstance + public string? AutoStartInstance { get => _AutoStartInstance ?? string.Empty; #pragma warning disable IDE0027 @@ -107,7 +107,7 @@ public void SetRegistryToInstances(SortedList instanc /// /// The build map of the fake registry /// - public JBuilds GetKSPBuilds() => BuildMap; + public JBuilds? GetKSPBuilds() => BuildMap; /// /// Set the build map for the fake registry @@ -123,7 +123,7 @@ public IEnumerable GetAuthTokenHosts() throw new NotImplementedException(); } - public void SetAuthToken(string host, string token) + public void SetAuthToken(string host, string? token) { throw new NotImplementedException(); } @@ -133,8 +133,8 @@ public bool TryGetAuthToken(string host, out string token) throw new NotImplementedException(); } - private string _Language; - public string Language + private string? _Language; + public string? Language { get => _Language; @@ -149,13 +149,16 @@ public string Language public string[] GlobalInstallFilters { get; set; } = Array.Empty(); - public string[] PreferredHosts { get; set; } = Array.Empty(); + public string?[] PreferredHosts { get; set; } = Array.Empty(); public bool? DevBuilds { get; set; } public void Dispose() { - Directory.Delete(DownloadCacheDir, true); + if (DownloadCacheDir != null) + { + Directory.Delete(DownloadCacheDir, true); + } } } } diff --git a/Tests/Core/Configuration/JsonConfiguration.cs b/Tests/Core/Configuration/JsonConfiguration.cs index 2414db6007..0f8960e563 100644 --- a/Tests/Core/Configuration/JsonConfiguration.cs +++ b/Tests/Core/Configuration/JsonConfiguration.cs @@ -62,7 +62,7 @@ public void LoadsGoodConfig() "host3" }, reg.GetAuthTokenHosts()); - Assert.IsTrue(reg.TryGetAuthToken("host1", out string token)); + Assert.IsTrue(reg.TryGetAuthToken("host1", out string? token)); Assert.AreEqual("token1", token); Assert.IsTrue(reg.TryGetAuthToken("host2", out token)); Assert.AreEqual("token2", token); @@ -139,7 +139,7 @@ public void LoadsExtraConfig() "host3" }, reg.GetAuthTokenHosts()); - Assert.IsTrue(reg.TryGetAuthToken("host1", out string token)); + Assert.IsTrue(reg.TryGetAuthToken("host1", out string? token)); Assert.AreEqual("token1", token); Assert.IsTrue(reg.TryGetAuthToken("host2", out token)); Assert.AreEqual("token2", token); @@ -339,7 +339,7 @@ public void AuthTokensPersist() CollectionAssert.Contains(reg.GetAuthTokenHosts(), "test_host1"); CollectionAssert.Contains(reg.GetAuthTokenHosts(), "test_host2"); - Assert.IsTrue(reg.TryGetAuthToken("test_host1", out string token)); + Assert.IsTrue(reg.TryGetAuthToken("test_host1", out string? token)); Assert.AreEqual("hunter2", token); Assert.IsTrue(reg.TryGetAuthToken("test_host2", out token)); Assert.AreEqual("asdf", token); diff --git a/Tests/Core/GameInstance.cs b/Tests/Core/GameInstance.cs index 7bfea76e50..e0ce65f294 100644 --- a/Tests/Core/GameInstance.cs +++ b/Tests/Core/GameInstance.cs @@ -13,9 +13,9 @@ namespace Tests.Core [TestFixture] public class GameInstanceTests { - private GameInstance ksp; - private string ksp_dir; - private IUser nullUser; + private GameInstance? ksp; + private string? ksp_dir; + private IUser? nullUser; [SetUp] public void Setup() @@ -37,7 +37,10 @@ public void TearDown() RegistryManager.DisposeInstance(ksp); } - Directory.Delete(ksp_dir, true); + if (ksp_dir != null) + { + Directory.Delete(ksp_dir, true); + } } [Test] @@ -49,10 +52,10 @@ public void IsGameDir() Assert.IsTrue(game.GameInFolder(new DirectoryInfo(TestData.good_ksp_dir()))); // As should our copied folder. - Assert.IsTrue(game.GameInFolder(new DirectoryInfo(ksp_dir))); + Assert.IsTrue(game.GameInFolder(new DirectoryInfo(ksp_dir!))); // And the one from our KSP instance. - Assert.IsTrue(game.GameInFolder(new DirectoryInfo(ksp.GameDir()))); + Assert.IsTrue(game.GameInFolder(new DirectoryInfo(ksp?.GameDir()!))); // All these ones should be bad. foreach (string dir in TestData.bad_ksp_dirs()) @@ -65,13 +68,12 @@ public void IsGameDir() public void Tutorial() { //Use Uri to avoid issues with windows vs linux line separators. - var canonicalPath = new Uri(Path.Combine(ksp_dir, "saves", "training")).LocalPath; + var canonicalPath = new Uri(Path.Combine(ksp_dir!, "saves", "training")).LocalPath; var game = new KerbalSpaceProgram(); - Assert.IsTrue(game.AllowInstallationIn("Tutorial", out string dest)); + Assert.IsTrue(game.AllowInstallationIn("Tutorial", out string? dest)); Assert.AreEqual( - new DirectoryInfo(ksp.ToAbsoluteGameDir(dest)), - new DirectoryInfo(canonicalPath) - ); + new DirectoryInfo(ksp?.ToAbsoluteGameDir(dest ?? "")!), + new DirectoryInfo(canonicalPath)); } [Test] @@ -79,21 +81,18 @@ public void ToAbsolute() { Assert.AreEqual( CKANPathUtils.NormalizePath( - Path.Combine(ksp_dir, "GameData/HydrazinePrincess") - ), - ksp.ToAbsoluteGameDir("GameData/HydrazinePrincess") - ); + Path.Combine(ksp_dir!, "GameData/HydrazinePrincess")), + ksp?.ToAbsoluteGameDir("GameData/HydrazinePrincess")); } [Test] public void ToRelative() { - string absolute = Path.Combine(ksp_dir, "GameData/HydrazinePrincess"); + string absolute = Path.Combine(ksp_dir!, "GameData/HydrazinePrincess"); Assert.AreEqual( "GameData/HydrazinePrincess", - ksp.ToRelativeGameDir(absolute) - ); + ksp?.ToRelativeGameDir(absolute)); } [Test] diff --git a/Tests/Core/GameInstanceManager.cs b/Tests/Core/GameInstanceManager.cs index a41acfa8d5..267ba5de4e 100644 --- a/Tests/Core/GameInstanceManager.cs +++ b/Tests/Core/GameInstanceManager.cs @@ -17,10 +17,10 @@ namespace Tests.Core { [TestFixture] public class GameInstanceManagerTests { - private DisposableKSP tidy; private const string nameInReg = "testing"; - private FakeConfiguration cfg; - private GameInstanceManager manager; + private DisposableKSP? tidy; + private FakeConfiguration? cfg; + private GameInstanceManager? manager; [SetUp] public void SetUp() @@ -33,76 +33,76 @@ public void SetUp() [TearDown] public void TearDown() { - manager.Dispose(); - tidy.Dispose(); - cfg.Dispose(); + manager?.Dispose(); + tidy?.Dispose(); + cfg?.Dispose(); } [Test] public void HasInstance_ReturnsFalseIfNoInstanceByThatName() { const string anyNameNotInReg = "Games"; - Assert.That(manager.HasInstance(anyNameNotInReg), Is.EqualTo(false)); + Assert.That(manager?.HasInstance(anyNameNotInReg), Is.EqualTo(false)); } [Test] public void HasInstance_ReturnsTrueIfInstanceByThatName() { - Assert.That(manager.HasInstance(nameInReg), Is.EqualTo(true)); + Assert.That(manager?.HasInstance(nameInReg), Is.EqualTo(true)); } [Test] public void SetAutoStart_ValidName_SetsAutoStart() { - Assert.That(manager.AutoStartInstance, Is.EqualTo(null)); + Assert.That(manager?.AutoStartInstance, Is.EqualTo(null)); - manager.SetAutoStart(nameInReg); - Assert.That(manager.AutoStartInstance, Is.EqualTo(nameInReg)); + manager?.SetAutoStart(nameInReg); + Assert.That(manager?.AutoStartInstance, Is.EqualTo(nameInReg)); } [Test] public void SetAutoStart_InvalidName_DoesNotChangeAutoStart() { - manager.SetAutoStart(nameInReg); - Assert.Throws(() => manager.SetAutoStart("invalid")); - Assert.That(manager.AutoStartInstance, Is.EqualTo(nameInReg)); + manager?.SetAutoStart(nameInReg); + Assert.Throws(() => manager?.SetAutoStart("invalid")); + Assert.That(manager?.AutoStartInstance, Is.EqualTo(nameInReg)); } [Test] public void RemoveInstance_HasInstanceReturnsFalse() { - manager.RemoveInstance(nameInReg); - Assert.False(manager.HasInstance(nameInReg)); + manager?.RemoveInstance(nameInReg); + Assert.False(manager?.HasInstance(nameInReg)); } [Test] public void RenameInstance_HasInstanceOriginalName_ReturnsFalse() { - manager.RenameInstance(nameInReg,"newname"); - Assert.False(manager.HasInstance(nameInReg)); + manager?.RenameInstance(nameInReg,"newname"); + Assert.False(manager?.HasInstance(nameInReg)); } [Test] public void RenameInstance_HasInstanceNewName() { const string newname = "newname"; - manager.RenameInstance(nameInReg, newname); - Assert.True(manager.HasInstance(newname)); + manager?.RenameInstance(nameInReg, newname); + Assert.True(manager?.HasInstance(newname)); } [Test] public void ClearAutoStart_UpdatesValueInWin32Reg() { - Assert.That(cfg.AutoStartInstance, Is.Null.Or.Empty); + Assert.That(cfg?.AutoStartInstance, Is.Null.Or.Empty); } [Test] public void GetNextValidInstanceName_ManagerDoesNotHaveResult() { - var name = manager.GetNextValidInstanceName(nameInReg); - Assert.That(manager.HasInstance(name),Is.False); + var name = manager?.GetNextValidInstanceName(nameInReg)!; + Assert.That(manager?.HasInstance(name), Is.False); } @@ -113,9 +113,9 @@ public void AddInstance_ManagerHasInstance() { const string newInstance = "tidy2"; tidy2.KSP.Name = newInstance; - Assert.IsFalse(manager.HasInstance(newInstance)); - manager.AddInstance(tidy2.KSP); - Assert.IsTrue(manager.HasInstance(newInstance)); + Assert.IsFalse(manager?.HasInstance(newInstance)); + manager?.AddInstance(tidy2.KSP); + Assert.IsTrue(manager?.HasInstance(newInstance)); } } @@ -129,8 +129,8 @@ public void CloneInstance_BadInstance_ThrowsNotKSPDirKraken() GameInstance badKSP = new GameInstance(new KerbalSpaceProgram(), TestData.bad_ksp_dirs().First(), "badDir", new NullUser()); Assert.Throws(() => - manager.CloneInstance(badKSP, badName, tempdir)); - Assert.IsFalse(manager.HasInstance(badName)); + manager?.CloneInstance(badKSP, badName, tempdir)); + Assert.IsFalse(manager?.HasInstance(badName)); // Tidy up Directory.Delete(tempdir, true); @@ -146,8 +146,8 @@ public void CloneInstance_ToNotEmptyFolder_ThrowsPathErrorKraken() File.Create(Path.Combine(tempdir, "shouldntbehere.txt")).Close(); Assert.Throws(() => - manager.CloneInstance(KSP.KSP, instanceName, tempdir)); - Assert.IsFalse(manager.HasInstance(instanceName)); + manager?.CloneInstance(KSP.KSP, instanceName, tempdir)); + Assert.IsFalse(manager?.HasInstance(instanceName)); // Tidy up. Directory.Delete(tempdir, true); @@ -162,8 +162,8 @@ public void CloneInstance_GoodInstance_ManagerHasValidInstance() string instanceName = "newInstance"; string tempdir = TestData.NewTempDir(); - manager.CloneInstance(KSP.KSP, instanceName, tempdir); - Assert.IsTrue(manager.HasInstance(instanceName)); + manager?.CloneInstance(KSP.KSP, instanceName, tempdir); + Assert.IsTrue(manager?.HasInstance(instanceName)); // Tidy up. Directory.Delete(tempdir, true); @@ -180,8 +180,8 @@ public void FakeInstance_InvalidVersion_ThrowsBadGameVersionKraken() GameVersion version = GameVersion.Parse("1.1.99"); Assert.Throws(() => - manager.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version)); - Assert.IsFalse(manager.HasInstance(name)); + manager?.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version)); + Assert.IsFalse(manager?.HasInstance(name)); // Tidy up. Directory.Delete(tempdir, true); @@ -204,8 +204,8 @@ public void FakeInstance_DlcsWithWrongBaseVersion_ThrowsWrongGameVersionKraken(s }; Assert.Throws(() => - manager.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version, dlcs)); - Assert.IsFalse(manager.HasInstance(name)); + manager?.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version, dlcs)); + Assert.IsFalse(manager?.HasInstance(name)); // Tidy up. Directory.Delete(tempdir, true); @@ -220,8 +220,8 @@ public void FakeInstance_InNotEmptyFolder_ThrowsBadInstallLocationKraken() File.Create(Path.Combine(tempdir, "shouldntbehere.txt")).Close(); Assert.Throws(() => - manager.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version)); - Assert.IsFalse(manager.HasInstance(name)); + manager?.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version)); + Assert.IsFalse(manager?.HasInstance(name)); // Tidy up. Directory.Delete(tempdir, true); @@ -241,14 +241,14 @@ public void FakeInstance_ValidArgumentsWithDLCs_ManagerHasValidInstance() { new BreakingGroundDlcDetector(), bgVersion } }; - manager.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version, dlcs); + manager?.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version, dlcs); GameInstance newKSP = new GameInstance(new KerbalSpaceProgram(), tempdir, name, new NullUser()); MakingHistoryDlcDetector mhDetector = new MakingHistoryDlcDetector(); BreakingGroundDlcDetector bgDetector = new BreakingGroundDlcDetector(); - Assert.IsTrue(manager.HasInstance(name)); - Assert.IsTrue(mhDetector.IsInstalled(newKSP, out string _, out UnmanagedModuleVersion detectedMhVersion)); - Assert.IsTrue(bgDetector.IsInstalled(newKSP, out string _, out UnmanagedModuleVersion detectedBgVersion)); + Assert.IsTrue(manager?.HasInstance(name)); + Assert.IsTrue(mhDetector.IsInstalled(newKSP, out string? _, out UnmanagedModuleVersion? detectedMhVersion)); + Assert.IsTrue(bgDetector.IsInstalled(newKSP, out string? _, out UnmanagedModuleVersion? detectedBgVersion)); Assert.IsTrue(detectedMhVersion == new UnmanagedModuleVersion(mhVersion.ToString())); Assert.IsTrue(detectedBgVersion == new UnmanagedModuleVersion(bgVersion.ToString())); @@ -262,7 +262,7 @@ public void FakeInstance_ValidArgumentsWithDLCs_ManagerHasValidInstance() [Test] public void GetPreferredInstance_WithAutoStart_ReturnsAutoStart() { - Assert.That(manager.GetPreferredInstance(),Is.EqualTo(tidy.KSP)); + Assert.That(manager?.GetPreferredInstance(),Is.EqualTo(tidy?.KSP)); } [Test] @@ -270,7 +270,7 @@ public void GetPreferredInstance_WithEmptyAutoStartAndMultipleInstances_ReturnsN { using (var tidy2 = new DisposableKSP()) { - cfg.Instances.Add(new Tuple("tidy2", tidy2.KSP.GameDir(), "KSP")); + cfg?.Instances.Add(new Tuple("tidy2", tidy2.KSP.GameDir(), "KSP")); // Make a new manager with the updated config var multiMgr = new GameInstanceManager(new NullUser(), cfg); multiMgr.ClearAutoStart(); @@ -282,20 +282,20 @@ public void GetPreferredInstance_WithEmptyAutoStartAndMultipleInstances_ReturnsN [Test] public void GetPreferredInstance_OnlyOneAvailable_ReturnsAvailable() { - manager.ClearAutoStart(); - Assert.That(manager.GetPreferredInstance(), Is.EqualTo(tidy.KSP)); + manager?.ClearAutoStart(); + Assert.That(manager?.GetPreferredInstance(), Is.EqualTo(tidy?.KSP)); } [Test] public void SetCurrentInstance_NameNotInRepo_Throws() { - Assert.Throws(() => manager.SetCurrentInstance("invalid")); + Assert.Throws(() => manager?.SetCurrentInstance("invalid")); } [Test] //37a33 public void Ctor_InvalidAutoStart_DoesNotThrow() { - using (var config = new FakeConfiguration(tidy.KSP, "invalid")) + using (var config = new FakeConfiguration(tidy?.KSP!, "invalid")) { Assert.DoesNotThrow(() => new GameInstanceManager(new NullUser(), config)); } @@ -309,10 +309,9 @@ private FakeConfiguration GetTestCfg(string name) return new FakeConfiguration( new List> { - new Tuple(name, tidy.KSP.GameDir(), "KSP") + new Tuple(name, tidy?.KSP?.GameDir()!, "KSP") }, - null - ); + null); } } } diff --git a/Tests/Core/ModuleInstallerDirTest.cs b/Tests/Core/ModuleInstallerDirTest.cs index add41f587a..355f0dc86b 100644 --- a/Tests/Core/ModuleInstallerDirTest.cs +++ b/Tests/Core/ModuleInstallerDirTest.cs @@ -18,19 +18,19 @@ namespace Tests.Core [TestFixture] public class ModuleInstallerDirTest { - private GameInstanceManager _manager; - private DisposableKSP _instance; - private FakeConfiguration _config; - private RegistryManager _registryManager; - private CKAN.Registry _registry; - private ModuleInstaller _installer; - private CkanModule _testModule; - private string _gameDir; - private string _gameDataDir; - private IUser _nullUser; - - private TemporaryRepository repo; - private TemporaryRepositoryData repoData; + private GameInstanceManager? _manager; + private DisposableKSP? _instance; + private FakeConfiguration? _config; + private RegistryManager? _registryManager; + private CKAN.Registry? _registry; + private ModuleInstaller? _installer; + private CkanModule? _testModule; + private string? _gameDir; + private string? _gameDataDir; + private IUser? _nullUser; + + private TemporaryRepository? repo; + private TemporaryRepositoryData? repoData; /// /// Prep environment by setting up a single mod in @@ -53,15 +53,15 @@ public void SetUp() _testModule = _registry.GetModuleByVersion("DogeCoinFlag", "1.01"); Assert.IsNotNull(_testModule, "DogeCoinFlag 1.01 should exist"); - _installer = new ModuleInstaller(_instance.KSP, _manager.Cache, _nullUser); + _installer = new ModuleInstaller(_instance.KSP, _manager.Cache!, _nullUser); _gameDir = _instance.KSP.GameDir(); _gameDataDir = _instance.KSP.game.PrimaryModDirectory(_instance.KSP); var testModFile = TestData.DogeCoinFlagZip(); - _manager.Cache.Store(_testModule, testModFile, new Progress(percent => {})); - HashSet possibleConfigOnlyDirs = null; + _manager.Cache?.Store(_testModule!, testModFile, new Progress(percent => {})); + HashSet? possibleConfigOnlyDirs = null; _installer.InstallList( - new List() { _testModule }, + new List() { _testModule! }, new RelationshipResolverOptions(), _registryManager, ref possibleConfigOnlyDirs); @@ -70,11 +70,11 @@ public void SetUp() [OneTimeTearDown] public void TearDown() { - _manager.Dispose(); - _config.Dispose(); - _instance.Dispose(); - repo.Dispose(); - repoData.Dispose(); + _manager?.Dispose(); + _config?.Dispose(); + _instance?.Dispose(); + repo?.Dispose(); + repoData?.Dispose(); } /// @@ -83,9 +83,8 @@ public void TearDown() [Test] public void TestGameRoot() { - var result = _installer - .AddParentDirectories(new HashSet() { _gameDir }) - .ToList(); + var result = _installer?.AddParentDirectories(new HashSet() { _gameDir ?? "" }) + .ToList()!; Assert.IsEmpty(result); } @@ -96,9 +95,8 @@ public void TestGameRoot() [Test] public void TestGameData() { - var result = _installer - .AddParentDirectories(new HashSet() { _gameDataDir }) - .ToList(); + var result = _installer?.AddParentDirectories(new HashSet() { _gameDataDir ?? "" }) + .ToList()!; Assert.IsEmpty(result); } @@ -112,9 +110,9 @@ public void TestNullPath() { Assert.DoesNotThrow(delegate () { - _installer.AddParentDirectories(new HashSet()); - _installer.AddParentDirectories(new HashSet() { string.Empty }); - _installer.AddParentDirectories(new HashSet() { Path.GetPathRoot(Environment.CurrentDirectory) }); + _installer?.AddParentDirectories(new HashSet()); + _installer?.AddParentDirectories(new HashSet() { string.Empty }); + _installer?.AddParentDirectories(new HashSet() { Path.GetPathRoot(Environment.CurrentDirectory)! }); }); } @@ -125,13 +123,13 @@ public void TestNullPath() [Test] public void TestSlashVariants() { - var rawInstallDir = Path.Combine(_gameDataDir, _testModule.identifier); + var rawInstallDir = Path.Combine(_gameDataDir!, _testModule!.identifier); var normalizedInstallDir = CKANPathUtils.NormalizePath(rawInstallDir); var windowsInstallDir = normalizedInstallDir.Replace('/', '\\'); Assert.DoesNotThrow(delegate () { - var result = _installer.AddParentDirectories(new HashSet() + var result = _installer?.AddParentDirectories(new HashSet() { rawInstallDir, windowsInstallDir, @@ -139,7 +137,7 @@ public void TestSlashVariants() }).ToList(); // should only contain one path - Assert.AreEqual(1, result.Count); + Assert.AreEqual(1, result?.Count); Assert.Contains(normalizedInstallDir, result); }); } @@ -155,13 +153,13 @@ public void TestCaseSensitivity() var paths = new HashSet() { // add in all-uppercase and all-lowercase version - Path.Combine(_gameDataDir.ToUpper(), _testModule.identifier), - Path.Combine(_gameDataDir.ToLower(), _testModule.identifier), + Path.Combine(_gameDataDir!.ToUpper(), _testModule!.identifier), + Path.Combine(_gameDataDir!.ToLower(), _testModule!.identifier), }; // here we are looking for no PathErrorKraken Assert.DoesNotThrow(delegate() { - var size = _installer.AddParentDirectories(paths).Count; + var size = _installer?.AddParentDirectories(paths).Count; // each directory adds two directories to the result // two directories each set { GAMEDATA and gamedata } = 4 objects in result array if (size != 4) diff --git a/Tests/Core/ModuleInstallerTests.cs b/Tests/Core/ModuleInstallerTests.cs index 6939472418..7fdf30524c 100644 --- a/Tests/Core/ModuleInstallerTests.cs +++ b/Tests/Core/ModuleInstallerTests.cs @@ -38,8 +38,8 @@ public void Sanity() // Our _find mod should have a find section, but not a file section. CkanModule mod = TestData.DogeCoinFlag_101_module_find(); - Assert.IsNull(mod.install[0].file); - Assert.IsNotNull(mod.install[0].find); + Assert.IsNull(mod.install?[0].file); + Assert.IsNotNull(mod.install?[0].find); } [Test] @@ -104,9 +104,9 @@ public void FindInstallableFilesWithKSP(CkanModule mod) List contents = ModuleInstaller.FindInstallableFiles(mod, TestData.DogeCoinFlagZip(), tidy.KSP); // See if we can find an expected destination path in the right place. - string file = contents - .Select(x => x.destination).FirstOrDefault( - x => Regex.IsMatch(x, "GameData/DogeCoinFlag/Flags/dogecoin\\.png$")); + var file = contents + .Select(x => x.destination) + .FirstOrDefault(x => Regex.IsMatch(x, "GameData/DogeCoinFlag/Flags/dogecoin\\.png$")); Assert.IsNotNull(file); } @@ -130,16 +130,16 @@ public void FindInstallableFilesWithKSP(CkanModule mod) public void FindInstallableFilesWithBonusPath(string path) { var dogemod = TestData.DogeCoinFlag_101_module(); - dogemod.install[0].install_to = path; + dogemod.install![0].install_to = path; using (var tidy = new DisposableKSP()) { IEnumerable contents = ModuleInstaller.FindInstallableFiles( dogemod, TestData.DogeCoinFlagZip(), tidy.KSP ); - string file = contents - .Select(x => x.destination).FirstOrDefault( - x => Regex.IsMatch(x, "GameData/SuchTest/DogeCoinFlag/Flags/dogecoin\\.png$")); + var file = contents + .Select(x => x.destination) + .FirstOrDefault(x => Regex.IsMatch(x, "GameData/SuchTest/DogeCoinFlag/Flags/dogecoin\\.png$")); Assert.IsNotNull(file); } @@ -152,9 +152,9 @@ public void ModuleManagerInstall() { List contents = ModuleInstaller.FindInstallableFiles(TestData.ModuleManagerModule(), TestData.ModuleManagerZip(), tidy.KSP); - string file = contents - .Select(x => x.destination).FirstOrDefault( - x => Regex.IsMatch(x, @"ModuleManager\.2\.5\.1\.dll$")); + var file = contents + .Select(x => x.destination) + .FirstOrDefault(x => Regex.IsMatch(x, @"ModuleManager\.2\.5\.1\.dll$")); Assert.IsNotNull(file, "ModuleManager install"); } @@ -167,15 +167,15 @@ public void MissionInstall() { List contents = ModuleInstaller.FindInstallableFiles(TestData.MissionModule(), TestData.MissionZip(), tidy.KSP); - string failBanner = contents.Select(x => x.destination).FirstOrDefault( + var failBanner = contents.Select(x => x.destination).FirstOrDefault( x => Regex.IsMatch(x, "Missions/AwesomeMission/Banners/Fail/default\\.png$")); - string menuBanner = contents.Select(x => x.destination).FirstOrDefault( + var menuBanner = contents.Select(x => x.destination).FirstOrDefault( x => Regex.IsMatch(x, "Missions/AwesomeMission/Banners/Menu/default\\.png$")); - string successBanner = contents.Select(x => x.destination).FirstOrDefault( + var successBanner = contents.Select(x => x.destination).FirstOrDefault( x => Regex.IsMatch(x, "Missions/AwesomeMission/Banners/Success/default\\.png$")); - string metaFile = contents.Select(x => x.destination).FirstOrDefault( + var metaFile = contents.Select(x => x.destination).FirstOrDefault( x => Regex.IsMatch(x, "Missions/AwesomeMission/persistent\\.loadmeta$")); - string missionFile = contents.Select(x => x.destination).FirstOrDefault( + var missionFile = contents.Select(x => x.destination).FirstOrDefault( x => Regex.IsMatch(x, "Missions/AwesomeMission/persistent\\.mission$")); Assert.IsNotNull(failBanner, "There is no fail banner in MissionInstall"); @@ -233,8 +233,8 @@ public void No_Installable_Files() }); // Make sure our module information is attached. - Assert.IsNotNull(exc.module); - Assert.AreEqual(bugged_mod.identifier, exc.module.identifier); + Assert.IsNotNull(exc?.module); + Assert.AreEqual(bugged_mod.identifier, exc?.module?.identifier); } #pragma warning disable 0414 @@ -254,7 +254,7 @@ public void FindInstallableFilesWithBadTarget(string location) { // This install location? It shouldn't be valid. var dogemod = TestData.DogeCoinFlag_101_module(); - dogemod.install[0].install_to = location; + dogemod.install![0].install_to = location; Assert.Throws(delegate { @@ -338,7 +338,7 @@ public void CorruptZip_242() corrupt_dogezip, ksp.KSP); } }); - Assert.AreEqual("Cannot find central directory", exc.Message); + Assert.AreEqual("Cannot find central directory", exc?.Message); } private string CopyDogeFromZip() @@ -368,9 +368,9 @@ public void UninstallModNotFound() { Assert.Throws(delegate { - HashSet possibleConfigOnlyDirs = null; + HashSet? possibleConfigOnlyDirs = null; // This should throw, as our tidy KSP has no mods installed. - new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache!, nullUser) .UninstallList(new List {"Foo"}, ref possibleConfigOnlyDirs, RegistryManager.Instance(manager.CurrentInstance, repoData.Manager)); @@ -402,13 +402,13 @@ public void CanInstallMod() Assert.IsFalse(File.Exists(mod_file_path)); // Copy the zip file to the cache directory. - Assert.IsFalse(manager.Cache.IsCached(TestData.DogeCoinFlag_101_module())); + Assert.IsFalse(manager.Cache?.IsCached(TestData.DogeCoinFlag_101_module())); - string cache_path = manager.Cache.Store(TestData.DogeCoinFlag_101_module(), - TestData.DogeCoinFlagZip(), - new Progress(percent => {})); + var cache_path = manager.Cache?.Store(TestData.DogeCoinFlag_101_module(), + TestData.DogeCoinFlagZip(), + new Progress(percent => {})); - Assert.IsTrue(manager.Cache.IsCached(TestData.DogeCoinFlag_101_module())); + Assert.IsTrue(manager.Cache?.IsCached(TestData.DogeCoinFlag_101_module())); Assert.IsTrue(File.Exists(cache_path)); var registry = RegistryManager.Instance(manager.CurrentInstance, repoData.Manager).registry; @@ -420,8 +420,8 @@ public void CanInstallMod() // Attempt to install it. var modules = new List { TestData.DogeCoinFlag_101_module() }; - HashSet possibleConfigOnlyDirs = null; - new ModuleInstaller(ksp.KSP, manager.Cache, nullUser) + HashSet? possibleConfigOnlyDirs = null; + new ModuleInstaller(ksp.KSP, manager.Cache!, nullUser) .InstallList(modules, new RelationshipResolverOptions(), RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), @@ -453,14 +453,14 @@ public void CanUninstallMod() var registry = RegistryManager.Instance(ksp.KSP, repoData.Manager).registry; registry.RepositoriesClear(); registry.RepositoriesAdd(repo.repo); - manager.Cache.Store(TestData.DogeCoinFlag_101_module(), - TestData.DogeCoinFlagZip(), - new Progress(percent => {})); + manager.Cache?.Store(TestData.DogeCoinFlag_101_module(), + TestData.DogeCoinFlagZip(), + new Progress(percent => {})); var modules = new List { TestData.DogeCoinFlag_101_module() }; - HashSet possibleConfigOnlyDirs = null; - new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + HashSet? possibleConfigOnlyDirs = null; + new ModuleInstaller(manager.CurrentInstance, manager.Cache!, nullUser) .InstallList(modules, new RelationshipResolverOptions(), RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), ref possibleConfigOnlyDirs); @@ -469,7 +469,7 @@ public void CanUninstallMod() Assert.IsTrue(File.Exists(mod_file_path)); // Attempt to uninstall it. - new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache!, nullUser) .UninstallList(modules.Select(m => m.identifier), ref possibleConfigOnlyDirs, RegistryManager.Instance(manager.CurrentInstance, repoData.Manager)); @@ -501,14 +501,14 @@ public void UninstallEmptyDirs() var registry = RegistryManager.Instance(ksp.KSP, repoData.Manager).registry; registry.RepositoriesClear(); registry.RepositoriesAdd(repo.repo); - manager.Cache.Store(TestData.DogeCoinFlag_101_module(), - TestData.DogeCoinFlagZip(), - new Progress(percent => {})); + manager.Cache?.Store(TestData.DogeCoinFlag_101_module(), + TestData.DogeCoinFlagZip(), + new Progress(percent => {})); var modules = new List { TestData.DogeCoinFlag_101_module() }; - HashSet possibleConfigOnlyDirs = null; - new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + HashSet? possibleConfigOnlyDirs = null; + new ModuleInstaller(manager.CurrentInstance, manager.Cache!, nullUser) .InstallList(modules, new RelationshipResolverOptions(), RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), @@ -517,13 +517,13 @@ public void UninstallEmptyDirs() modules.Clear(); // Install the plugin test mod. - manager.Cache.Store(TestData.DogeCoinPlugin_module(), - TestData.DogeCoinPluginZip(), - new Progress(percent => {})); + manager.Cache?.Store(TestData.DogeCoinPlugin_module(), + TestData.DogeCoinPluginZip(), + new Progress(percent => {})); modules.Add(TestData.DogeCoinPlugin_module()); - new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache!, nullUser) .InstallList(modules, new RelationshipResolverOptions(), RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), @@ -539,7 +539,7 @@ public void UninstallEmptyDirs() modules.Add(TestData.DogeCoinFlag_101_module()); modules.Add(TestData.DogeCoinPlugin_module()); - new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache!, nullUser) .UninstallList(modules.Select(m => m.identifier), ref possibleConfigOnlyDirs, RegistryManager.Instance(manager.CurrentInstance, repoData.Manager)); @@ -658,7 +658,7 @@ public void GroupFilesByRemovable_WithFiles_CorrectOutput(string relRoot, .ToList(); foreach (var absPath in absFiles) { - Directory.CreateDirectory(Path.GetDirectoryName(absPath)); + Directory.CreateDirectory(Path.GetDirectoryName(absPath)!); File.Create(absPath).Dispose(); } // Register the other mod @@ -709,15 +709,15 @@ public void ModuleManagerInstancesAreDecoupled() registry.RepositoriesAdd(repo.repo); // Copy the zip file to the cache directory. - manager.Cache.Store(TestData.DogeCoinFlag_101_module(), - TestData.DogeCoinFlagZip(), - new Progress(percent => {})); + manager.Cache?.Store(TestData.DogeCoinFlag_101_module(), + TestData.DogeCoinFlagZip(), + new Progress(percent => {})); // Attempt to install it. var modules = new List { TestData.DogeCoinFlag_101_module() }; - HashSet possibleConfigOnlyDirs = null; - new ModuleInstaller(ksp.KSP, manager.Cache, nullUser) + HashSet? possibleConfigOnlyDirs = null; + new ModuleInstaller(ksp.KSP, manager.Cache!, nullUser) .InstallList(modules, new RelationshipResolverOptions(), RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), @@ -766,7 +766,7 @@ public void AllowsInstallsToShipsDirectories(string directory) List results; using (var ksp = new DisposableKSP()) { - results = mod.install.First().FindInstallableFiles(zip, ksp.KSP); + results = mod.install!.First().FindInstallableFiles(zip, ksp.KSP); } // Assert @@ -806,7 +806,7 @@ public void AllowInstallsToScenarios() using (var ksp = new DisposableKSP()) { - var results = mod.install.First().FindInstallableFiles(zip, ksp.KSP); + var results = mod.install!.First().FindInstallableFiles(zip, ksp.KSP); Assert.AreEqual( CKANPathUtils.NormalizePath( @@ -867,9 +867,9 @@ public void InstallList_RealZipSlip_Throws() registry.RepositoriesAdd(repo.repo); // Copy the zip file to the cache directory. - manager.Cache.Store(TestData.DogeCoinFlag_101ZipSlip_module(), - TestData.DogeCoinFlagZipSlipZip(), - new Progress(percent => {})); + manager.Cache?.Store(TestData.DogeCoinFlag_101ZipSlip_module(), + TestData.DogeCoinFlagZipSlipZip(), + new Progress(percent => {})); // Attempt to install it. var modules = new List { TestData.DogeCoinFlag_101ZipSlip_module() }; @@ -878,8 +878,8 @@ public void InstallList_RealZipSlip_Throws() Assert.Throws( delegate { - HashSet possibleConfigOnlyDirs = null; - new ModuleInstaller(ksp.KSP, manager.Cache, nullUser) + HashSet? possibleConfigOnlyDirs = null; + new ModuleInstaller(ksp.KSP, manager.Cache!, nullUser) .InstallList(modules, new RelationshipResolverOptions(), RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), @@ -909,16 +909,16 @@ public void InstallList_RealZipBomb_DoesNotThrow() registry.RepositoriesAdd(repo.repo); // Copy the zip file to the cache directory. - manager.Cache.Store(TestData.DogeCoinFlag_101ZipBomb_module(), - TestData.DogeCoinFlagZipBombZip(), - new Progress(percent => {})); + manager.Cache?.Store(TestData.DogeCoinFlag_101ZipBomb_module(), + TestData.DogeCoinFlagZipBombZip(), + new Progress(percent => {})); // Attempt to install it. var modules = new List { TestData.DogeCoinFlag_101ZipBomb_module() }; // Act / Assert - HashSet possibleConfigOnlyDirs = null; - new ModuleInstaller(ksp.KSP, manager.Cache, nullUser) + HashSet? possibleConfigOnlyDirs = null; + new ModuleInstaller(ksp.KSP, manager.Cache!, nullUser) .InstallList(modules, new RelationshipResolverOptions(), RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), @@ -970,19 +970,19 @@ public void Replace_WithCompatibleModule_Succeeds() var registry = regMgr.registry; IRegistryQuerier querier = registry; registry.RepositoriesAdd(repo.repo); - var replaced = registry.GetModuleByVersion("replaced", "1.0"); + var replaced = registry.GetModuleByVersion("replaced", "1.0")!; Assert.IsNotNull(replaced, "Replaced module should exist"); var replacer = registry.GetModuleByVersion("replacer", "1.0"); Assert.IsNotNull(replacer, "Replacer module should exist"); - var installer = new ModuleInstaller(inst.KSP, manager.Cache, nullUser); - HashSet possibleConfigOnlyDirs = null; - var downloader = new NetAsyncModulesDownloader(nullUser, manager.Cache); + var installer = new ModuleInstaller(inst.KSP, manager.Cache!, nullUser); + HashSet? possibleConfigOnlyDirs = null; + var downloader = new NetAsyncModulesDownloader(nullUser, manager.Cache!); // Act registry.RegisterModule(replaced, new List(), inst.KSP, false); - manager.Cache.Store(replaced, TestData.DogeCoinFlagZip(), new Progress(percent => {})); + manager.Cache?.Store(replaced, TestData.DogeCoinFlagZip(), new Progress(percent => {})); var replacement = querier.GetReplacement(replaced.identifier, - new GameVersionCriteria(new GameVersion(1, 12))); + new GameVersionCriteria(new GameVersion(1, 12)))!; installer.Replace(Enumerable.Repeat(replacement, 1), new RelationshipResolverOptions(), downloader, ref possibleConfigOnlyDirs, regMgr, @@ -1039,16 +1039,16 @@ public void Replace_WithIncompatibleModule_Fails() var registry = regMgr.registry; IRegistryQuerier querier = registry; registry.RepositoriesAdd(repo.repo); - var replaced = registry.GetModuleByVersion("replaced", "1.0"); + var replaced = registry.GetModuleByVersion("replaced", "1.0")!; Assert.IsNotNull(replaced, "Replaced module should exist"); var replacer = registry.GetModuleByVersion("replacer", "1.0"); Assert.IsNotNull(replacer, "Replacer module should exist"); - var installer = new ModuleInstaller(inst.KSP, manager.Cache, nullUser); - var downloader = new NetAsyncModulesDownloader(nullUser, manager.Cache); + var installer = new ModuleInstaller(inst.KSP, manager.Cache!, nullUser); + var downloader = new NetAsyncModulesDownloader(nullUser, manager.Cache!); // Act registry.RegisterModule(replaced, new List(), inst.KSP, false); - manager.Cache.Store(replaced, TestData.DogeCoinFlagZip(), new Progress(percent => {})); + manager.Cache?.Store(replaced, TestData.DogeCoinFlagZip(), new Progress(percent => {})); var replacement = querier.GetReplacement(replaced.identifier, new GameVersionCriteria(new GameVersion(1, 11))); @@ -1108,7 +1108,7 @@ public void UninstallList_WithAutoInst_RemovesAutoRemovable(string[] regularMods using (var repo = new TemporaryRepository(regularMods.Concat(autoInstMods).ToArray())) using (var repoData = new TemporaryRepositoryData(nullUser, repo.repo)) { - var installer = new ModuleInstaller(inst.KSP, manager.Cache, nullUser); + var installer = new ModuleInstaller(inst.KSP, manager.Cache!, nullUser); var regMgr = RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); var registry = regMgr.registry; var possibleConfigOnlyDirs = new HashSet(); @@ -1191,8 +1191,8 @@ public void Upgrade_WithAutoInst_RemovesAutoRemovable(string[] regularMods, using (var repo = new TemporaryRepository(regularMods.Concat(autoInstMods).ToArray())) using (var repoData = new TemporaryRepositoryData(nullUser, repo.repo)) { - var installer = new ModuleInstaller(inst.KSP, manager.Cache, nullUser); - var downloader = new NetAsyncModulesDownloader(nullUser, manager.Cache); + var installer = new ModuleInstaller(inst.KSP, manager.Cache!, nullUser); + var downloader = new NetAsyncModulesDownloader(nullUser, manager.Cache!); var regMgr = RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); var registry = regMgr.registry; registry.RepositoriesSet(new SortedDictionary() @@ -1204,9 +1204,9 @@ public void Upgrade_WithAutoInst_RemovesAutoRemovable(string[] regularMods, foreach (var m in regularMods) { var module = CkanModule.FromJson(m); - manager.Cache.Store(module, - TestData.DogeCoinFlagZip(), - new Progress(percent => {})); + manager.Cache?.Store(module, + TestData.DogeCoinFlagZip(), + new Progress(percent => {})); if (!querier.IsInstalled(module.identifier, false)) { registry.RegisterModule(module, @@ -1225,7 +1225,8 @@ public void Upgrade_WithAutoInst_RemovesAutoRemovable(string[] regularMods, // Act installer.Upgrade(upgradeIdentifiers.Select(ident => - registry.LatestAvailable(ident, inst.KSP.VersionCriteria())), + registry.LatestAvailable(ident, inst.KSP.VersionCriteria())) + .OfType(), downloader, ref possibleConfigOnlyDirs, regMgr, false); // Assert @@ -1242,7 +1243,7 @@ public void Install_WithMatchedUnmanagedDll_Throws() installTestPlugin(unmanaged, TestData.DogeCoinPlugin(), TestData.DogeCoinPluginZip())); - Assert.AreEqual(unmanaged, kraken.path); + Assert.AreEqual(unmanaged, kraken?.path); } [TestCase] @@ -1274,15 +1275,15 @@ private void installTestPlugin(string unmanaged, string moduleJson, string zipPa repoData.Manager); var module = CkanModule.FromJson(moduleJson); var modules = new List { module }; - var installer = new ModuleInstaller(inst.KSP, manager.Cache, nullUser); + var installer = new ModuleInstaller(inst.KSP, manager.Cache!, nullUser); File.WriteAllText(inst.KSP.ToAbsoluteGameDir(unmanaged), "Not really a DLL, are we?"); regMgr.ScanUnmanagedFiles(); - manager.Cache.Store(module, zipPath, new Progress(percent => {})); + manager.Cache?.Store(module, zipPath, new Progress(percent => {})); // Act - HashSet possibleConfigOnlyDirs = null; - new ModuleInstaller(inst.KSP, manager.Cache, nullUser) + HashSet? possibleConfigOnlyDirs = null; + new ModuleInstaller(inst.KSP, manager.Cache!, nullUser) .InstallList(modules, new RelationshipResolverOptions(), regMgr, diff --git a/Tests/Core/Net/AutoUpdateTests.cs b/Tests/Core/Net/AutoUpdateTests.cs index 5f2d52b259..80eedc6911 100644 --- a/Tests/Core/Net/AutoUpdateTests.cs +++ b/Tests/Core/Net/AutoUpdateTests.cs @@ -74,8 +74,8 @@ public void GitHubReleaseCkanUpdate_NormalUpdate_ParsedCorrectly() var upd = new GitHubReleaseCkanUpdate(relInfo); // Assert - Assert.AreEqual("v1.25.0", relInfo.tag_name); - Assert.AreEqual("Wallops", relInfo.name); + Assert.AreEqual("v1.25.0", relInfo?.tag_name); + Assert.AreEqual("Wallops", relInfo?.name); CollectionAssert.AreEqual( new Uri[] { @@ -102,7 +102,7 @@ public void S3BuildCkanUpdate_Constructor_ParsedCorrectly() }, upd.Targets.SelectMany(t => t.urls)); Assert.AreEqual("v1.34.5.24015 aka dev", - upd.Version.ToString()); + upd.Version?.ToString()); Assert.AreEqual("### Internal\n\n- [Policy] Fix #3518 rewrite de-indexing policy (#3993 by: JonnyOThan; reviewed: HebaruSan)", upd.ReleaseNotes); } diff --git a/Tests/Core/Net/NetAsyncDownloaderTests.cs b/Tests/Core/Net/NetAsyncDownloaderTests.cs index 0b4ddfd1a9..d359c908fc 100644 --- a/Tests/Core/Net/NetAsyncDownloaderTests.cs +++ b/Tests/Core/Net/NetAsyncDownloaderTests.cs @@ -202,11 +202,11 @@ public void DownloadAndWait_WithSomeInvalidUrls_ThrowsDownloadErrorsKraken( }); Assert.Multiple(() => { - CollectionAssert.AreEquivalent(badIndices, exception.Exceptions.Select(kvp => kvp.Key).ToArray()); - foreach (var kvp in exception.Exceptions) + CollectionAssert.AreEquivalent(badIndices, exception?.Exceptions.Select(kvp => kvp.Key).ToArray()); + foreach (var kvp in exception?.Exceptions!) { var baseExc = kvp.Value.GetBaseException() as FileNotFoundException; - Assert.AreEqual(fromPaths[kvp.Key], baseExc.FileName); + Assert.AreEqual(fromPaths[kvp.Key], baseExc?.FileName); } foreach (var t in validTargets) { diff --git a/Tests/Core/Net/NetAsyncModulesDownloaderTests.cs b/Tests/Core/Net/NetAsyncModulesDownloaderTests.cs index de3d07837a..63504ac3cb 100644 --- a/Tests/Core/Net/NetAsyncModulesDownloaderTests.cs +++ b/Tests/Core/Net/NetAsyncModulesDownloaderTests.cs @@ -16,12 +16,12 @@ namespace Tests.Core.Net [TestFixture] public class NetAsyncModulesDownloaderTests { - private GameInstanceManager manager; - private RegistryManager registry_manager; - private CKAN.Registry registry; - private DisposableKSP ksp; - private NetModuleCache cache; - private TemporaryRepositoryData repoData; + private GameInstanceManager? manager; + private RegistryManager? registry_manager; + private CKAN.Registry? registry; + private DisposableKSP? ksp; + private NetModuleCache? cache; + private TemporaryRepositoryData? repoData; [SetUp] public void Setup() @@ -54,9 +54,9 @@ public void Setup() [TearDown] public void TearDown() { - manager.Dispose(); - ksp.Dispose(); - repoData.Dispose(); + manager?.Dispose(); + ksp?.Dispose(); + repoData?.Dispose(); } [Test, @@ -108,7 +108,7 @@ public void TearDown() ""download_hash"": { ""sha1"": ""DEADBEEFDEADBEEF""} }", }, - new string[] { "github.com", null }, + new string?[] { "github.com", null }, new string[] { "https://github.com/", @@ -118,12 +118,14 @@ public void TearDown() "https://archive.org/download/ModC-1.0/DEADBEEF-ModC-1.0.zip" }), ] - public void TargetFromModuleGroup_WithModules_ExpectedTarget(string[] moduleJsons, string[] preferredHosts, string[] correctURLs) + public void TargetFromModuleGroup_WithModules_ExpectedTarget(string[] moduleJsons, + string?[] preferredHosts, + string[] correctURLs) { // Arrange var group = moduleJsons.Select(CkanModule.FromJson) .ToHashSet(); - var downloader = new NetAsyncModulesDownloader(new NullUser(), cache); + var downloader = new NetAsyncModulesDownloader(new NullUser(), cache!); if (correctURLs == null) { diff --git a/Tests/Core/Net/PreferredHostUriComparerTests.cs b/Tests/Core/Net/PreferredHostUriComparerTests.cs index 22b03b16f6..991faacdf6 100644 --- a/Tests/Core/Net/PreferredHostUriComparerTests.cs +++ b/Tests/Core/Net/PreferredHostUriComparerTests.cs @@ -40,7 +40,7 @@ public sealed class PreferredHostUriComparerTests "https://archive.org/", }), // Irrelevant settings - TestCase(new string[] { "api.github.com", "curseforge.com", null, "www.dropbox.com", "drive.google.com" }, + TestCase(new string?[] { "api.github.com", "curseforge.com", null, "www.dropbox.com", "drive.google.com" }, new string[] { "https://taniwha.org/", @@ -49,7 +49,7 @@ public sealed class PreferredHostUriComparerTests "https://archive.org/", }), // Prioritize one - TestCase(new string[] { "github.com", null }, + TestCase(new string?[] { "github.com", null }, new string[] { "https://github.com/", @@ -58,7 +58,7 @@ public sealed class PreferredHostUriComparerTests "https://archive.org/", }), // De-prioritize one - TestCase(new string[] { null, "spacedock.info" }, + TestCase(new string?[] { null, "spacedock.info" }, new string[] { "https://taniwha.org/", @@ -67,7 +67,7 @@ public sealed class PreferredHostUriComparerTests "https://spacedock.info/", }), // Prioritize one, de-prioritize another - TestCase(new string[] { "github.com", null, "spacedock.info" }, + TestCase(new string?[] { "github.com", null, "spacedock.info" }, new string[] { "https://github.com/", diff --git a/Tests/Core/Registry/CompatibilitySorter.cs b/Tests/Core/Registry/CompatibilitySorter.cs index 49490db012..68e1780de6 100644 --- a/Tests/Core/Registry/CompatibilitySorter.cs +++ b/Tests/Core/Registry/CompatibilitySorter.cs @@ -97,7 +97,7 @@ public void Constructor_OverlappingModules_HigherPriorityOverrides(string[] modu // Assert Assert.AreEqual(0, sorter.LatestIncompatible.Count); Assert.AreEqual(2, sorter.LatestCompatible.Count); - Assert.AreEqual(CkanModule.ToJson(highPrio), + Assert.AreEqual(CkanModule.ToJson(highPrio!), CkanModule.ToJson(sorter.LatestCompatible.First(m => m.identifier == identifier))); } } diff --git a/Tests/Core/Registry/Registry.cs b/Tests/Core/Registry/Registry.cs index ae285314b2..277f76352b 100644 --- a/Tests/Core/Registry/Registry.cs +++ b/Tests/Core/Registry/Registry.cs @@ -15,7 +15,7 @@ namespace Tests.Core.Registry [TestFixture] public class RegistryTests { - private string repoDataDir; + private string? repoDataDir; private static readonly GameVersionCriteria v0_24_2 = new GameVersionCriteria(GameVersion.Parse("0.24.2")); private static readonly GameVersionCriteria v0_25_0 = new GameVersionCriteria(GameVersion.Parse("0.25.0")); @@ -29,7 +29,10 @@ public void Setup() [TearDown] public void TearDown() { - Directory.Delete(repoDataDir, true); + if (repoDataDir != null) + { + Directory.Delete(repoDataDir, true); + } } [Test] @@ -52,7 +55,7 @@ public void LatestAvailable() var module = registry.GetModuleByVersion(identifier, "0.14"); // Make sure it's there for 0.24.2 - Assert.AreEqual(module.ToString(), registry.LatestAvailable(identifier, v0_24_2).ToString()); + Assert.AreEqual(module?.ToString(), registry.LatestAvailable(identifier, v0_24_2)?.ToString()); // But not for 0.25.0 Assert.IsNull(registry.LatestAvailable(identifier, v0_25_0)); @@ -86,7 +89,7 @@ public void CompatibleModules_NoDLCInstalled_ExcludesModulesDependingOnMH() var DLCDepender = registry.GetModuleByVersion("DLC-Depender", "1.0.0"); // Act - List avail = registry.CompatibleModules(v0_24_2).ToList(); + var avail = registry.CompatibleModules(v0_24_2).OfType().ToList(); // Assert Assert.IsFalse(avail.Contains(DLCDepender)); @@ -118,7 +121,7 @@ public void CompatibleModules_MHInstalled_IncludesModulesDependingOnMH() var DLCDepender = registry.GetModuleByVersion("DLC-Depender", "1.0.0"); // Act - List avail = registry.CompatibleModules(v0_24_2).ToList(); + var avail = registry.CompatibleModules(v0_24_2).OfType().ToList(); // Assert Assert.IsTrue(avail.Contains(DLCDepender)); @@ -151,7 +154,7 @@ public void CompatibleModules_MH110Installed_IncludesModulesDependingOnMH110() var DLCDepender = registry.GetModuleByVersion("DLC-Depender", "1.0.0"); // Act - List avail = registry.CompatibleModules(v0_24_2).ToList(); + var avail = registry.CompatibleModules(v0_24_2).OfType().ToList(); // Assert Assert.IsTrue(avail.Contains(DLCDepender)); @@ -184,26 +187,13 @@ public void CompatibleModules_MH100Installed_ExcludesModulesDependingOnMH110() var DLCDepender = registry.GetModuleByVersion("DLC-Depender", "1.0.0"); // Act - List avail = registry.CompatibleModules(v0_24_2).ToList(); + var avail = registry.CompatibleModules(v0_24_2).OfType().ToList(); // Assert Assert.IsFalse(avail.Contains(DLCDepender)); } } - [Test] - public void SetDLCs_NullVersion_DoesNotThrow() - { - var registry = CKAN.Registry.Empty(); - Assert.DoesNotThrow(() => - { - registry.SetDlcs(new Dictionary - { - { "MissingVersion", null }, - }); - }, "Missing readme.txt in a DLC shouldn't trigger an exception"); - } - [Test] public void CompatibleModules_PastAndFutureCompatibility_ReturnsCurrentOnly() { @@ -242,7 +232,7 @@ public void CompatibleModules_PastAndFutureCompatibility_ReturnsCurrentOnly() // Act GameVersionCriteria v173 = new GameVersionCriteria(GameVersion.Parse("1.7.3")); - List compat = registry.CompatibleModules(v173).ToList(); + var compat = registry.CompatibleModules(v173).OfType().ToList(); // Assert Assert.IsFalse(compat.Contains(modFor161)); @@ -270,13 +260,13 @@ public void HasUpdate_WithUpgradeableManuallyInstalledMod_ReturnsTrue() var mod = registry.GetModuleByVersion("AutoDetectedMod", "1.0"); GameInstance gameInst = gameInstWrapper.KSP; - gameInst.SetCompatibleVersions(new List { mod.ksp_version }); + gameInst.SetCompatibleVersions(new List { mod?.ksp_version! }); registry.SetDlls(new Dictionary() { { - mod.identifier, + mod!.identifier, gameInst.ToRelativeGameDir(Path.Combine(gameInst.GameDir(), - "GameData", $"{mod.identifier}.dll")) + "GameData", $"{mod!.identifier}.dll")) } }); @@ -327,17 +317,17 @@ public void HasUpdate_OtherModDependsOnCurrent_ReturnsFalse() using (var repoData = new TemporaryRepositoryData(user, repo.repo)) { var registry = new CKAN.Registry(repoData.Manager, repo.repo); - CkanModule olderDepMod = registry.GetModuleByVersion("DependencyMod", "1.0"); - CkanModule newerDepMod = registry.GetModuleByVersion("DependencyMod", "2.0"); - CkanModule dependingMod = registry.GetModuleByVersion("DependingMod", "1.0"); + var olderDepMod = registry.GetModuleByVersion("DependencyMod", "1.0"); + var newerDepMod = registry.GetModuleByVersion("DependencyMod", "2.0"); + var dependingMod = registry.GetModuleByVersion("DependingMod", "1.0"); GameInstance gameInst = gameInstWrapper.KSP; - registry.RegisterModule(olderDepMod, new List(), gameInst, false); - registry.RegisterModule(dependingMod, new List(), gameInst, false); - GameVersionCriteria crit = new GameVersionCriteria(olderDepMod.ksp_version); + registry.RegisterModule(olderDepMod!, new List(), gameInst, false); + registry.RegisterModule(dependingMod!, new List(), gameInst, false); + GameVersionCriteria crit = new GameVersionCriteria(olderDepMod?.ksp_version); // Act - bool has = registry.HasUpdate(olderDepMod.identifier, gameInst, out _, + bool has = registry.HasUpdate(olderDepMod?.identifier!, gameInst, out _, registry.InstalledModules .Select(im => im.Module) .ToList()); diff --git a/Tests/Core/Registry/RegistryLive.cs b/Tests/Core/Registry/RegistryLive.cs index ffbe7c9073..6626a1746f 100644 --- a/Tests/Core/Registry/RegistryLive.cs +++ b/Tests/Core/Registry/RegistryLive.cs @@ -24,18 +24,18 @@ public void LatestAvailable() using (var temp_ksp = new DisposableKSP()) using (var repoData = new TemporaryRepositoryData(user, new Dictionary { - { repo, RepositoryData.FromJson(TestData.TestRepository(), null) }, + { repo, RepositoryData.FromJson(TestData.TestRepository(), null)! }, })) { var registry = RegistryManager.Instance(temp_ksp.KSP, repoData.Manager).registry; registry.RepositoriesClear(); registry.RepositoriesAdd(repo); - CkanModule module = + var module = registry.LatestAvailable("AGExt", new GameVersionCriteria(temp_ksp.KSP.Version())); - Assert.AreEqual("AGExt", module.identifier); - Assert.AreEqual("1.24a", module.version.ToString()); + Assert.AreEqual("AGExt", module?.identifier); + Assert.AreEqual("1.24a", module?.version.ToString()); } } } diff --git a/Tests/Core/Registry/RegistryManager.cs b/Tests/Core/Registry/RegistryManager.cs index 7fae3ee995..7716b89d69 100644 --- a/Tests/Core/Registry/RegistryManager.cs +++ b/Tests/Core/Registry/RegistryManager.cs @@ -46,7 +46,7 @@ public void Locking() /// private bool TestLock(string path) { - FileStream lockfileStream = null; + FileStream? lockfileStream = null; try { diff --git a/Tests/Core/Relationships/RelationshipResolver.cs b/Tests/Core/Relationships/RelationshipResolver.cs index ffd6b62866..39ab8b70b7 100644 --- a/Tests/Core/Relationships/RelationshipResolver.cs +++ b/Tests/Core/Relationships/RelationshipResolver.cs @@ -16,8 +16,8 @@ namespace Tests.Core.Relationships [TestFixture] public class RelationshipResolverTests { - private RelationshipResolverOptions options; - private RandomModuleGenerator generator; + private RelationshipResolverOptions? options; + private RandomModuleGenerator? generator; [SetUp] public void Setup() @@ -40,7 +40,7 @@ public void Constructor_WithoutModules_AlwaysReturns() [Test] public void Constructor_WithConflictingModules() { - var mod_a = generator.GeneratorRandomModule(); + var mod_a = generator!.GeneratorRandomModule(); var mod_b = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor { name = mod_a.identifier } @@ -55,9 +55,9 @@ public void Constructor_WithConflictingModules() var list = new List { mod_a, mod_b }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); - options.proceed_with_inconsistencies = true; + options!.proceed_with_inconsistencies = true; var resolver = new RelationshipResolver(list, null, options, registry, null); Assert.That(resolver.ConflictList.Any(s => Equals(s.Key, mod_a))); @@ -70,7 +70,7 @@ public void Constructor_WithConflictingModules() [Category("Version")] public void Constructor_WithConflictingModulesVersion_Throws() { - var mod_a = generator.GeneratorRandomModule(); + var mod_a = generator!.GeneratorRandomModule(); var mod_b = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor {name=mod_a.identifier, version=mod_a.version} @@ -85,7 +85,7 @@ public void Constructor_WithConflictingModulesVersion_Throws() var list = new List { mod_a, mod_b }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -95,7 +95,7 @@ public void Constructor_WithConflictingModulesVersion_Throws() [TestCase("1.0", "1.0")] public void Constructor_WithConflictingModulesVersionMin_Throws(string ver, string conf_min) { - var mod_a = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var mod_a = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var mod_b = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor {name=mod_a.identifier, min_version=new ModuleVersion(conf_min)} @@ -110,7 +110,7 @@ public void Constructor_WithConflictingModulesVersionMin_Throws(string ver, stri var list = new List { mod_a, mod_b }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -120,7 +120,7 @@ public void Constructor_WithConflictingModulesVersionMin_Throws(string ver, stri [TestCase("1.0", "1.0")] public void Constructor_WithConflictingModulesVersionMax_Throws(string ver, string conf_max) { - var mod_a = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var mod_a = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var mod_b = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor {name=mod_a.identifier, max_version=new ModuleVersion(conf_max)} @@ -135,7 +135,7 @@ public void Constructor_WithConflictingModulesVersionMax_Throws(string ver, stri var list = new List { mod_a, mod_b }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -146,7 +146,7 @@ public void Constructor_WithConflictingModulesVersionMax_Throws(string ver, stri [TestCase("1.0", "0.5", "1.0")] public void Constructor_WithConflictingModulesVersionMinMax_Throws(string ver, string conf_min, string conf_max) { - var mod_a = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var mod_a = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var mod_b = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor @@ -166,7 +166,7 @@ public void Constructor_WithConflictingModulesVersionMinMax_Throws(string ver, s var list = new List { mod_a, mod_b }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -176,7 +176,7 @@ public void Constructor_WithConflictingModulesVersionMinMax_Throws(string ver, s [TestCase("1.0", "2.0")] public void Constructor_WithNonConflictingModulesVersion_DoesNotThrow(string ver, string conf) { - var mod_a = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var mod_a = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var mod_b = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor {name=mod_a.identifier, version=new ModuleVersion(conf)} @@ -191,7 +191,7 @@ public void Constructor_WithNonConflictingModulesVersion_DoesNotThrow(string ver var list = new List { mod_a, mod_b }; Assert.DoesNotThrow(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -200,7 +200,7 @@ public void Constructor_WithNonConflictingModulesVersion_DoesNotThrow(string ver [TestCase("1.0", "2.0")] public void Constructor_WithConflictingModulesVersionMin_DoesNotThrow(string ver, string conf_min) { - var mod_a = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var mod_a = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var mod_b = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor {name=mod_a.identifier, min_version=new ModuleVersion(conf_min)} @@ -215,7 +215,7 @@ public void Constructor_WithConflictingModulesVersionMin_DoesNotThrow(string ver var list = new List { mod_a, mod_b }; Assert.DoesNotThrow(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -224,7 +224,7 @@ public void Constructor_WithConflictingModulesVersionMin_DoesNotThrow(string ver [TestCase("2.0", "1.0")] public void Constructor_WithConflictingModulesVersionMax_DoesNotThrow(string ver, string conf_max) { - var mod_a = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var mod_a = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var mod_b = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor {name=mod_a.identifier, max_version=new ModuleVersion(conf_max)} @@ -239,7 +239,7 @@ public void Constructor_WithConflictingModulesVersionMax_DoesNotThrow(string ver var list = new List { mod_a, mod_b }; Assert.DoesNotThrow(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -249,7 +249,7 @@ public void Constructor_WithConflictingModulesVersionMax_DoesNotThrow(string ver [TestCase("4.0", "2.0", "3.0")] public void Constructor_WithConflictingModulesVersionMinMax_DoesNotThrow(string ver, string conf_min, string conf_max) { - var mod_a = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var mod_a = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var mod_b = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor {name=mod_a.identifier, min_version=new ModuleVersion(conf_min), max_version=new ModuleVersion(conf_max)} @@ -264,16 +264,16 @@ public void Constructor_WithConflictingModulesVersionMinMax_DoesNotThrow(string var list = new List { mod_a, mod_b }; Assert.DoesNotThrow(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } [Test] public void Constructor_WithMultipleModulesProviding_Throws() { - options.without_toomanyprovides_kraken = false; + options!.without_toomanyprovides_kraken = false; - var mod_a = generator.GeneratorRandomModule(); + var mod_a = generator!.GeneratorRandomModule(); var mod_b = generator.GeneratorRandomModule(provides: new List { mod_a.identifier @@ -305,17 +305,18 @@ public void Constructor_WithMultipleModulesProviding_Throws() public void ModList_WithInstalledModules_ContainsThemWithReasonInstalled() { var user = new NullUser(); - var mod_a = generator.GeneratorRandomModule(); + var mod_a = generator!.GeneratorRandomModule(); + using (var ksp = new DisposableKSP()) using (var repo = new TemporaryRepository(CkanModule.ToJson(mod_a))) using (var repoData = new TemporaryRepositoryData(user, repo.repo)) { var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { mod_a }; - registry.RegisterModule(mod_a, new List(), null, false); + registry.RegisterModule(mod_a, new List(), ksp.KSP, false); var relationship_resolver = new RelationshipResolver( - list, null, options, registry, null); + list, null, options!, registry, null); CollectionAssert.Contains(relationship_resolver.ModList(), mod_a); CollectionAssert.AreEquivalent(new List { @@ -329,8 +330,8 @@ public void ModList_WithInstalledModules_ContainsThemWithReasonInstalled() [Test] public void ModList_WithInstalledModulesSuggested_DoesNotContainThem() { - options.with_all_suggests = true; - var suggested = generator.GeneratorRandomModule(); + options!.with_all_suggests = true; + var suggested = generator!.GeneratorRandomModule(); var suggester = generator.GeneratorRandomModule(suggests: new List { new ModuleRelationshipDescriptor {name = suggested.identifier} @@ -353,8 +354,8 @@ public void ModList_WithInstalledModulesSuggested_DoesNotContainThem() [Test] public void ModList_WithSuggestedModulesThatWouldConflict_DoesNotContainThem() { - options.with_all_suggests = true; - var suggested = generator.GeneratorRandomModule(); + options!.with_all_suggests = true; + var suggested = generator!.GeneratorRandomModule(); var mod = generator.GeneratorRandomModule(conflicts: new List { new ModuleRelationshipDescriptor {name = suggested.identifier} @@ -381,7 +382,7 @@ public void ModList_WithSuggestedModulesThatWouldConflict_DoesNotContainThem() [Test] public void Constructor_WithConflictingModulesInDependencies_ThrowUnderDefaultSettings() { - var dependant = generator.GeneratorRandomModule(); + var dependant = generator!.GeneratorRandomModule(); var depender = generator.GeneratorRandomModule(depends: new List { new ModuleRelationshipDescriptor {name = dependant.identifier} @@ -401,15 +402,15 @@ public void Constructor_WithConflictingModulesInDependencies_ThrowUnderDefaultSe var list = new List { depender, conflicts_with_dependant }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } [Test] public void Constructor_WithSuggests_HasSuggestedInModlist() { - options.with_all_suggests = true; - var suggested = generator.GeneratorRandomModule(); + options!.with_all_suggests = true; + var suggested = generator!.GeneratorRandomModule(); var suggester = generator.GeneratorRandomModule(suggests: new List { new ModuleRelationshipDescriptor {name = suggested.identifier} @@ -431,7 +432,7 @@ public void Constructor_WithSuggests_HasSuggestedInModlist() [Test] public void Constructor_ContainsSugestedOfSuggested_When_With_all_suggests() { - var suggested2 = generator.GeneratorRandomModule(); + var suggested2 = generator!.GeneratorRandomModule(); var suggested = generator.GeneratorRandomModule( suggests: new List { @@ -454,7 +455,7 @@ public void Constructor_ContainsSugestedOfSuggested_When_With_all_suggests() var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { suggester }; - options.with_all_suggests = true; + options!.with_all_suggests = true; var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); CollectionAssert.Contains(relationship_resolver.ModList(), suggested2); @@ -468,7 +469,7 @@ public void Constructor_ContainsSugestedOfSuggested_When_With_all_suggests() [Test] public void Constructor_ProvidesSatisfyDependencies() { - var mod_a = generator.GeneratorRandomModule(); + var mod_a = generator!.GeneratorRandomModule(); var mod_b = generator.GeneratorRandomModule(provides: new List { mod_a.identifier @@ -485,7 +486,7 @@ public void Constructor_ProvidesSatisfyDependencies() { var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { depender }; - var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); + var relationship_resolver = new RelationshipResolver(list, null, options!, registry, null); CollectionAssert.AreEquivalent(relationship_resolver.ModList(), new List { @@ -498,7 +499,7 @@ public void Constructor_ProvidesSatisfyDependencies() [Test] public void Constructor_WithMissingDependants_Throws() { - var dependant = generator.GeneratorRandomModule(); + var dependant = generator!.GeneratorRandomModule(); var depender = generator.GeneratorRandomModule(depends: new List { new ModuleRelationshipDescriptor {name = dependant.identifier} @@ -512,7 +513,7 @@ public void Constructor_WithMissingDependants_Throws() Assert.Throws(() => new RelationshipResolver(new List { depender }, - null, options, registry, null)); + null, options!, registry, null)); } } @@ -524,7 +525,7 @@ public void Constructor_WithMissingDependants_Throws() [TestCase("1.0", "0")] public void Constructor_WithMissingDependantsVersion_Throws(string ver, string dep) { - var dependant = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var dependant = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var depender = generator.GeneratorRandomModule(depends: new List { new ModuleRelationshipDescriptor {name = dependant.identifier, version = new ModuleVersion(dep)} @@ -540,7 +541,7 @@ public void Constructor_WithMissingDependantsVersion_Throws(string ver, string d var list = new List { depender }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -549,7 +550,7 @@ public void Constructor_WithMissingDependantsVersion_Throws(string ver, string d [TestCase("1.0", "2.0")] public void Constructor_WithMissingDependantsVersionMin_Throws(string ver, string dep_min) { - var dependant = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var dependant = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var depender = generator.GeneratorRandomModule(depends: new List { new ModuleRelationshipDescriptor {name = dependant.identifier, min_version = new ModuleVersion(dep_min)} @@ -564,10 +565,10 @@ public void Constructor_WithMissingDependantsVersionMin_Throws(string ver, strin var list = new List() { depender }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); list.Add(dependant); Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -576,7 +577,7 @@ public void Constructor_WithMissingDependantsVersionMin_Throws(string ver, strin [TestCase("1.0", "0.5")] public void Constructor_WithMissingDependantsVersionMax_Throws(string ver, string dep_max) { - var dependant = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var dependant = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var depender = generator.GeneratorRandomModule(depends: new List { new ModuleRelationshipDescriptor {name = dependant.identifier, max_version = new ModuleVersion(dep_max)} @@ -591,7 +592,7 @@ public void Constructor_WithMissingDependantsVersionMax_Throws(string ver, strin var list = new List { depender, dependant }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -601,7 +602,7 @@ public void Constructor_WithMissingDependantsVersionMax_Throws(string ver, strin [TestCase("4.0", "2.0", "3.0")] public void Constructor_WithMissingDependantsVersionMinMax_Throws(string ver, string dep_min, string dep_max) { - var dependant = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var dependant = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var depender = generator.GeneratorRandomModule(depends: new List { new ModuleRelationshipDescriptor @@ -621,7 +622,7 @@ public void Constructor_WithMissingDependantsVersionMinMax_Throws(string ver, st var list = new List { depender, dependant }; Assert.Throws(() => new RelationshipResolver( - list, null, options, registry, null)); + list, null, options!, registry, null)); } } @@ -631,7 +632,7 @@ public void Constructor_WithMissingDependantsVersionMinMax_Throws(string ver, st [TestCase("1.0", "1.0", "0.5")]//what to do if a mod is present twice with the same version ? public void Constructor_WithDependantVersion_ChooseCorrectly(string ver, string dep, string other) { - var dependant = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var dependant = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var other_dependant = generator.GeneratorRandomModule(identifier: dependant.identifier, version: new ModuleVersion(other)); var depender = generator.GeneratorRandomModule(depends: new List @@ -648,7 +649,7 @@ public void Constructor_WithDependantVersion_ChooseCorrectly(string ver, string var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { depender }; - var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); + var relationship_resolver = new RelationshipResolver(list, null, options!, registry, null); CollectionAssert.AreEquivalent(relationship_resolver.ModList(), new List { dependant, @@ -664,7 +665,7 @@ public void Constructor_WithDependantVersion_ChooseCorrectly(string ver, string [TestCase("2.0", "2.0", "0.5")] public void Constructor_WithDependantVersionMin_ChooseCorrectly(string ver, string dep_min, string other) { - var dependant = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var dependant = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var other_dependant = generator.GeneratorRandomModule(identifier: dependant.identifier, version: new ModuleVersion(other)); var depender = generator.GeneratorRandomModule(depends: new List @@ -681,7 +682,7 @@ public void Constructor_WithDependantVersionMin_ChooseCorrectly(string ver, stri var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { depender }; - var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); + var relationship_resolver = new RelationshipResolver(list, null, options!, registry, null); CollectionAssert.AreEquivalent(relationship_resolver.ModList(), new List { dependant, @@ -697,7 +698,7 @@ public void Constructor_WithDependantVersionMin_ChooseCorrectly(string ver, stri [TestCase("2.0", "3.0", "4.0")] public void Constructor_WithDependantVersionMax_ChooseCorrectly(string ver, string dep_max, string other) { - var dependant = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var dependant = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var other_dependant = generator.GeneratorRandomModule(identifier: dependant.identifier, version: new ModuleVersion(other)); var depender = generator.GeneratorRandomModule(depends: new List @@ -714,7 +715,7 @@ public void Constructor_WithDependantVersionMax_ChooseCorrectly(string ver, stri var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { depender }; - var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); + var relationship_resolver = new RelationshipResolver(list, null, options!, registry, null); CollectionAssert.AreEquivalent(relationship_resolver.ModList(), new List { dependant, @@ -730,7 +731,7 @@ public void Constructor_WithDependantVersionMax_ChooseCorrectly(string ver, stri [TestCase("2.0", "1.0", "3.0", "3.5")] public void Constructor_WithDependantVersionMinMax_ChooseCorrectly(string ver, string dep_min, string dep_max, string other) { - var dependant = generator.GeneratorRandomModule(version: new ModuleVersion(ver)); + var dependant = generator!.GeneratorRandomModule(version: new ModuleVersion(ver)); var other_dependant = generator.GeneratorRandomModule(identifier: dependant.identifier, version: new ModuleVersion(other)); var depender = generator.GeneratorRandomModule(depends: new List @@ -752,7 +753,7 @@ public void Constructor_WithDependantVersionMinMax_ChooseCorrectly(string ver, s var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { depender }; - var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); + var relationship_resolver = new RelationshipResolver(list, null, options!, registry, null); CollectionAssert.AreEquivalent(relationship_resolver.ModList(), new List { dependant, @@ -809,7 +810,7 @@ public void Constructor_ReverseDependencyDoesntMatchLatest_ChoosesOlderVersion() // Act RelationshipResolver rr = new RelationshipResolver( new CkanModule[] { depender }, null, - options, registry, null); + options!, registry, null); // Assert CollectionAssert.Contains( rr.ModList(), olderDependency); @@ -860,7 +861,7 @@ public void Constructor_ReverseDependencyConflictsLatest_ChoosesOlderVersion() // Act RelationshipResolver rr = new RelationshipResolver( new CkanModule[] { depender }, null, - options, registry, null); + options!, registry, null); // Assert CollectionAssert.Contains( rr.ModList(), olderDependency); @@ -871,7 +872,7 @@ public void Constructor_ReverseDependencyConflictsLatest_ChoosesOlderVersion() [Test] public void ReasonFor_WithModsNotInList_Empty() { - var mod = generator.GeneratorRandomModule(); + var mod = generator!.GeneratorRandomModule(); var user = new NullUser(); using (var repo = new TemporaryRepository(CkanModule.ToJson(mod))) @@ -879,7 +880,7 @@ public void ReasonFor_WithModsNotInList_Empty() { var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { mod }; - var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); + var relationship_resolver = new RelationshipResolver(list, null, options!, registry, null); var mod_not_in_resolver_list = generator.GeneratorRandomModule(); CollectionAssert.DoesNotContain(relationship_resolver.ModList(), mod_not_in_resolver_list); @@ -890,7 +891,7 @@ public void ReasonFor_WithModsNotInList_Empty() [Test] public void ReasonFor_WithUserAddedMods_GivesReasonUserAdded() { - var mod = generator.GeneratorRandomModule(); + var mod = generator!.GeneratorRandomModule(); var user = new NullUser(); using (var repo = new TemporaryRepository(CkanModule.ToJson(mod))) @@ -899,7 +900,7 @@ public void ReasonFor_WithUserAddedMods_GivesReasonUserAdded() var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { mod }; - var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); + var relationship_resolver = new RelationshipResolver(list, null, options!, registry, null); var reasons = relationship_resolver.ReasonsFor(mod); Assert.That(reasons[0], Is.AssignableTo()); } @@ -908,7 +909,7 @@ public void ReasonFor_WithUserAddedMods_GivesReasonUserAdded() [Test] public void ReasonFor_WithSuggestedMods_GivesCorrectParent() { - var suggested = generator.GeneratorRandomModule(); + var suggested = generator!.GeneratorRandomModule(); var mod = generator.GeneratorRandomModule(suggests: new List {new ModuleRelationshipDescriptor {name = suggested.identifier}}); @@ -921,7 +922,7 @@ public void ReasonFor_WithSuggestedMods_GivesCorrectParent() var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { mod }; - options.with_all_suggests = true; + options!.with_all_suggests = true; var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); var reasons = relationship_resolver.ReasonsFor(suggested); @@ -933,7 +934,7 @@ public void ReasonFor_WithSuggestedMods_GivesCorrectParent() [Test] public void ReasonFor_WithTreeOfMods_GivesCorrectParents() { - var suggested = generator.GeneratorRandomModule(); + var suggested = generator!.GeneratorRandomModule(); var recommendedA = generator.GeneratorRandomModule(); var recommendedB = generator.GeneratorRandomModule(); var mod = generator.GeneratorRandomModule( @@ -958,7 +959,7 @@ public void ReasonFor_WithTreeOfMods_GivesCorrectParents() var registry = new CKAN.Registry(repoData.Manager, repo.repo); var list = new List { mod }; - options.with_all_suggests = true; + options!.with_all_suggests = true; options.with_recommends = true; var relationship_resolver = new RelationshipResolver(list, null, options, registry, null); var reasons = relationship_resolver.ReasonsFor(recommendedA); @@ -993,7 +994,7 @@ public void AutodetectedCanSatisfyRelationships() new ModuleRelationshipDescriptor { name = "ModuleManager" } }; - CkanModule mod = generator.GeneratorRandomModule(depends: depends); + CkanModule mod = generator!.GeneratorRandomModule(depends: depends); new RelationshipResolver( new CkanModule[] { mod }, null, RelationshipResolverOptions.DefaultOpts(), @@ -1006,7 +1007,7 @@ public void AutodetectedCanSatisfyRelationships() public void UninstallingConflictingModule_InstallingRecursiveDependencies_ResolvesSuccessfully() { // Arrange: create dummy modules that resemble the relationship entanglement, and make them available - var eve = generator.GeneratorRandomModule( + var eve = generator!.GeneratorRandomModule( identifier: "EnvironmentalVisualEnhancements", depends: new List {new ModuleRelationshipDescriptor {name = "EnvironmentalVisualEnhancements-Config"}} @@ -1054,7 +1055,7 @@ public void UninstallingConflictingModule_InstallingRecursiveDependencies_Resolv List modulesToInstall; List modulesToRemove; - RelationshipResolver resolver; + RelationshipResolver? resolver; // Act and assert: play through different possible user interactions // Scenario 1 - Try installing AVP, expect an exception for proceed_with_inconsistencies=false @@ -1062,13 +1063,13 @@ public void UninstallingConflictingModule_InstallingRecursiveDependencies_Resolv modulesToInstall = new List { avp }; modulesToRemove = new List(); - options.proceed_with_inconsistencies = false; + options!.proceed_with_inconsistencies = false; var exception = Assert.Throws(() => { resolver = new RelationshipResolver(modulesToInstall, modulesToRemove, options, registry, null); }); Assert.AreEqual($"{avp} conflicts with {eveDefaultConfig}", - exception.ShortDescription); + exception?.ShortDescription); // Scenario 2 - Try installing AVP, expect no exception for proceed_with_inconsistencies=true, but a conflict list @@ -1079,9 +1080,9 @@ public void UninstallingConflictingModule_InstallingRecursiveDependencies_Resolv resolver = new RelationshipResolver(modulesToInstall, modulesToRemove, options, registry, null); }); CollectionAssert.AreEquivalent(modulesToInstall, - resolver.ConflictList.Keys); + resolver?.ConflictList.Keys); CollectionAssert.AreEquivalent(new List {$"{avp} conflicts with {eveDefaultConfig}"}, - resolver.ConflictList.Values); + resolver?.ConflictList.Values); // Scenario 3 - Try uninstalling eveDefaultConfig and installing avp, should work and result in no conflicts @@ -1094,7 +1095,7 @@ public void UninstallingConflictingModule_InstallingRecursiveDependencies_Resolv { resolver = new RelationshipResolver(modulesToInstall, modulesToRemove, options, registry, null); }); - Assert.IsEmpty(resolver.ConflictList); + Assert.IsEmpty(resolver!.ConflictList); CollectionAssert.AreEquivalent(new List {avp, avp2kTextures}, resolver.ModList()); } } diff --git a/Tests/Core/Relationships/SanityChecker.cs b/Tests/Core/Relationships/SanityChecker.cs index d0f39d9009..2132225fa9 100644 --- a/Tests/Core/Relationships/SanityChecker.cs +++ b/Tests/Core/Relationships/SanityChecker.cs @@ -16,10 +16,10 @@ namespace Tests.Core.Relationships [TestFixture] public class SanityChecker { - private RegistryManager manager; - private CKAN.Registry registry; - private DisposableKSP ksp; - private TemporaryRepositoryData repoData; + private RegistryManager? manager; + private CKAN.Registry? registry; + private DisposableKSP? ksp; + private TemporaryRepositoryData? repoData; [OneTimeSetUp] public void Setup() @@ -45,9 +45,9 @@ public void Setup() [OneTimeTearDown] public void TearDown() { - manager.Dispose(); - ksp.Dispose(); - repoData.Dispose(); + manager?.Dispose(); + ksp?.Dispose(); + repoData?.Dispose(); } [Test] @@ -60,7 +60,7 @@ public void Empty() public void DogeCoin() { // Test with a module that depends and conflicts with nothing. - var mods = new List {registry.LatestAvailable("DogeCoinFlag",null)}; + var mods = new List { registry?.LatestAvailable("DogeCoinFlag", null) }.OfType(); Assert.IsTrue(CKAN.SanityChecker.IsConsistent(mods), "DogeCoinFlag"); } @@ -68,14 +68,14 @@ public void DogeCoin() [Test] public void CustomBiomes() { - var mods = new List {registry.LatestAvailable("CustomBiomes", null)}; + var mods = Enumerable.Repeat(registry?.LatestAvailable("CustomBiomes", null), 1).OfType().ToList(); Assert.IsFalse(CKAN.SanityChecker.IsConsistent(mods), "CustomBiomes without data"); - mods.Add(registry.LatestAvailable("CustomBiomesKerbal",null)); + mods.Add(registry?.LatestAvailable("CustomBiomesKerbal", null)!); Assert.IsTrue(CKAN.SanityChecker.IsConsistent(mods), "CustomBiomes with stock data"); - mods.Add(registry.LatestAvailable("CustomBiomesRSS",null)); + mods.Add(registry?.LatestAvailable("CustomBiomesRSS", null)!); Assert.IsFalse(CKAN.SanityChecker.IsConsistent(mods), "CustomBiomes with conflicting data"); } @@ -83,23 +83,23 @@ public void CustomBiomes() public void CustomBiomesWithDlls() { var mods = new List(); - var dlls = new List {"CustomBiomes"}; + var dlls = new List { "CustomBiomes" }; Assert.IsTrue(CKAN.SanityChecker.IsConsistent(mods, dlls), "CustomBiomes dll by itself"); // This would actually be a terrible thing for users to have, but it tests the // relationship we want. - mods.Add(registry.LatestAvailable("CustomBiomesKerbal", null)); + mods.Add(registry?.LatestAvailable("CustomBiomesKerbal", null)!); Assert.IsTrue(CKAN.SanityChecker.IsConsistent(mods, dlls), "CustomBiomes DLL, with config added"); - mods.Add(registry.LatestAvailable("CustomBiomesRSS", null)); + mods.Add(registry?.LatestAvailable("CustomBiomesRSS", null)!); Assert.IsFalse(CKAN.SanityChecker.IsConsistent(mods, dlls), "CustomBiomes with conflicting data"); } [Test] public void ConflictWithDll() { - var mods = new List { registry.LatestAvailable("SRL", null) }; + var mods = new List { registry?.LatestAvailable("SRL", null)! }; var dlls = new List { "QuickRevert" }; Assert.IsTrue(CKAN.SanityChecker.IsConsistent(mods), "SRL can be installed by itself"); @@ -115,17 +115,17 @@ public void FindUnsatisfiedDepends() Assert.IsEmpty(CKAN.SanityChecker.FindUnsatisfiedDepends(mods, dlls, dlc), "Empty list"); - mods.Add(registry.LatestAvailable("DogeCoinFlag", null)); + mods.Add(registry?.LatestAvailable("DogeCoinFlag", null)!); Assert.IsEmpty(CKAN.SanityChecker.FindUnsatisfiedDepends(mods, dlls, dlc), "DogeCoinFlag"); - mods.Add(registry.LatestAvailable("CustomBiomes", null)); + mods.Add(registry?.LatestAvailable("CustomBiomes", null)!); Assert.Contains( "CustomBiomesData", CKAN.SanityChecker.FindUnsatisfiedDepends(mods, dlls, dlc).Select(kvp => kvp.Item2.ToString()).ToList(), "Missing CustomBiomesData" ); - mods.Add(registry.LatestAvailable("CustomBiomesKerbal", null)); + mods.Add(registry?.LatestAvailable("CustomBiomesKerbal", null)!); Assert.IsEmpty(CKAN.SanityChecker.FindUnsatisfiedDepends(mods, dlls, dlc), "CBD+CBK"); mods.RemoveAll(x => x.identifier == "CustomBiomes"); @@ -141,16 +141,16 @@ public void FindUnsatisfiedDepends() [Test] public void ReverseDepends() { - var mods = new HashSet() + var mods = new CkanModule?[] { - registry.LatestAvailable("CustomBiomes", null), - registry.LatestAvailable("CustomBiomesKerbal", null), - registry.LatestAvailable("DogeCoinFlag", null) - }; + registry?.LatestAvailable("CustomBiomes", null), + registry?.LatestAvailable("CustomBiomesKerbal", null), + registry?.LatestAvailable("DogeCoinFlag", null) + }.OfType().ToHashSet(); // Make sure some of our expectations regarding dependencies are correct. - Assert.Contains("CustomBiomes", registry.LatestAvailable("CustomBiomesKerbal",null).depends.Select(x => x.ToString()).ToList()); - Assert.Contains("CustomBiomesData", registry.LatestAvailable("CustomBiomes",null).depends.Select(x => x.ToString()).ToList()); + Assert.Contains("CustomBiomes", registry?.LatestAvailable("CustomBiomesKerbal", null)?.depends?.Select(x => x.ToString()).ToList()); + Assert.Contains("CustomBiomesData", registry?.LatestAvailable("CustomBiomes", null)?.depends?.Select(x => x.ToString()).ToList()); // Removing DCF should only remove itself. var to_remove = new List {"DogeCoinFlag"}; @@ -363,14 +363,14 @@ public void IsConsistent_MultipleVersionsOfSelfProvidesConflictingModule_Consist Assert.IsTrue(CKAN.SanityChecker.IsConsistent(modules)); } - private static void TestDepends(List to_remove, - HashSet mods, - HashSet dlls, - Dictionary dlc, - List expected, - string message) + private static void TestDepends(List to_remove, + HashSet mods, + HashSet? dlls, + Dictionary? dlc, + List expected, + string message) { - dlls = dlls ?? new HashSet(); + dlls ??= new HashSet(); var remove_count = to_remove.Count; var dll_count = dlls.Count; diff --git a/Tests/Core/Repositories/RepositoryDataManagerTests.cs b/Tests/Core/Repositories/RepositoryDataManagerTests.cs index b51e058884..1e9a2988ac 100644 --- a/Tests/Core/Repositories/RepositoryDataManagerTests.cs +++ b/Tests/Core/Repositories/RepositoryDataManagerTests.cs @@ -25,7 +25,7 @@ public void UpdateRegistryTarGz() // Act var versions = repoData.Manager.GetAvailableModules(Enumerable.Repeat(testRepo, 1), "FerramAerospaceResearch") - .Select(am => am.Latest(crit).version.ToString()) + .Select(am => am.Latest(crit)?.version.ToString()) .ToArray(); // Assert @@ -47,7 +47,7 @@ public void UpdateRegistryZip() // Act var versions = repoData.Manager.GetAvailableModules(Enumerable.Repeat(testRepo, 1), "FerramAerospaceResearch") - .Select(am => am.Latest(crit).version.ToString()) + .Select(am => am.Latest(crit)?.version.ToString()) .ToArray(); // Assert diff --git a/Tests/Core/Types/CkanModuleTests.cs b/Tests/Core/Types/CkanModuleTests.cs index 16fa0209e5..32f5fb4aff 100644 --- a/Tests/Core/Types/CkanModuleTests.cs +++ b/Tests/Core/Types/CkanModuleTests.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Newtonsoft.Json.Linq; @@ -40,21 +39,21 @@ public void MetaData() Assert.AreEqual("kOS - Kerbal OS", module.name); Assert.AreEqual("kOS", module.identifier); Assert.AreEqual("A programming and automation environment for KSP craft.", module.@abstract); - Assert.AreEqual("https://github.com/KSP-KOS/KOS/releases/download/v0.14/kOS.v14.zip", module.download[0].ToString()); + Assert.AreEqual("https://github.com/KSP-KOS/KOS/releases/download/v0.14/kOS.v14.zip", module.download?[0].ToString()); Assert.AreEqual("GPL-3.0", module.license.First().ToString()); Assert.AreEqual("0.14", module.version.ToString()); - Assert.AreEqual("stable", module.release_status.ToString()); - Assert.AreEqual("0.24.2", module.ksp_version.ToString()); + Assert.AreEqual("stable", module.release_status?.ToString()); + Assert.AreEqual("0.24.2", module.ksp_version?.ToString()); - Assert.That(module.install.First().file, Is.EqualTo("GameData/kOS")); - Assert.That(module.install.First().install_to, Is.EqualTo("GameData")); + Assert.That(module.install?.First().file, Is.EqualTo("GameData/kOS")); + Assert.That(module.install?.First().install_to, Is.EqualTo("GameData")); - Assert.AreEqual("http://forum.kerbalspaceprogram.com/threads/68089-0-23-kOS-Scriptable-Autopilot-System-v0-11-2-13", module.resources.homepage.ToString()); - Assert.AreEqual("https://github.com/KSP-KOS/KOS/issues", module.resources.bugtracker.ToString()); - Assert.AreEqual("https://github.com/KSP-KOS/KOS", module.resources.repository.ToString()); + Assert.AreEqual("http://forum.kerbalspaceprogram.com/threads/68089-0-23-kOS-Scriptable-Autopilot-System-v0-11-2-13", module.resources?.homepage?.ToString()); + Assert.AreEqual("https://github.com/KSP-KOS/KOS/issues", module.resources?.bugtracker?.ToString()); + Assert.AreEqual("https://github.com/KSP-KOS/KOS", module.resources?.repository?.ToString()); - Assert.AreEqual("C5A224AC4397770C0B19B4A6417F6C5052191608", module.download_hash.sha1.ToString()); - Assert.AreEqual("E0FB79C81D8FCDA8DB6E38B104106C3B7D078FDC06ACA2BC7834973B43D789CB", module.download_hash.sha256.ToString()); + Assert.AreEqual("C5A224AC4397770C0B19B4A6417F6C5052191608", module.download_hash?.sha1?.ToString()); + Assert.AreEqual("E0FB79C81D8FCDA8DB6E38B104106C3B7D078FDC06ACA2BC7834973B43D789CB", module.download_hash?.sha256?.ToString()); } /// @@ -67,7 +66,7 @@ public void MetaData() public void SpacesPreservedInDownload() { CkanModule module = CkanModule.FromJson(TestData.DogeCoinFlag_101()); - Assert.AreEqual("https://kerbalstuff.com/mod/269/Dogecoin%20Flag/download/1.01", module.download[0].OriginalString); + Assert.AreEqual("https://kerbalstuff.com/mod/269/Dogecoin%20Flag/download/1.01", module.download?[0].OriginalString); } [Test] @@ -76,10 +75,10 @@ public void FilterRead() CkanModule module = CkanModule.FromJson(TestData.DogeCoinFlag_101()); // Assert known things about this mod. - Assert.IsNotNull(module.install[0].filter); - Assert.IsNotNull(module.install[0].filter_regexp); + Assert.IsNotNull(module.install?[0].filter); + Assert.IsNotNull(module.install?[0].filter_regexp); - Assert.AreEqual(2, module.install[0].filter.Count); + Assert.AreEqual(2, module.install?[0].filter?.Count); } [Test] @@ -164,12 +163,12 @@ public void bad_resource_1208() JObject metadata = JObject.Parse(TestData.kOS_014()); // Guess which string totally isn't a valid Url? This one. - metadata["resources"]["homepage"] = "https://included%in%the%download"; + metadata["resources"]!["homepage"] = "https://included%in%the%download"; CkanModule mod = CkanModule.FromJson(metadata.ToString()); Assert.IsNotNull(mod); - Assert.IsNull(mod.resources.homepage); + Assert.IsNull(mod.resources?.homepage); } [Test] @@ -179,7 +178,7 @@ public void good_resource_1208() Assert.AreEqual( "http://forum.kerbalspaceprogram.com/threads/68089-0-23-kOS-Scriptable-Autopilot-System-v0-11-2-13", - mod.resources.homepage.ToString() + mod.resources?.homepage?.ToString() ); } @@ -189,10 +188,10 @@ public void InternetArchiveDownload_RedistributableLicense_CorrectURL() // Arrange CkanModule module = TestData.kOS_014_module(); // Act - Uri uri = module.InternetArchiveDownload; + var uri = module.InternetArchiveDownload; // Assert Assert.IsNotNull(uri); - Assert.AreEqual("https://archive.org/download/kOS-0.14/C5A224AC-kOS-0.14.zip", uri.ToString()); + Assert.AreEqual("https://archive.org/download/kOS-0.14/C5A224AC-kOS-0.14.zip", uri?.ToString()); } [Test] @@ -201,7 +200,7 @@ public void InternetArchiveDownload_RestrictedLicense_NullURL() // Arrange CkanModule module = TestData.FireSpitterModule(); // Act - Uri uri = module.InternetArchiveDownload; + var uri = module.InternetArchiveDownload; // Assert Assert.IsNull(uri); } @@ -212,10 +211,10 @@ public void InternetArchiveDownload_EpochVersion_CorrectURL() // Arrange CkanModule module = TestData.kOS_014_epoch_module(); // Act - Uri uri = module.InternetArchiveDownload; + var uri = module.InternetArchiveDownload; // Assert Assert.IsNotNull(uri); - Assert.AreEqual("https://archive.org/download/kOS-3-0.14/C5A224AC-kOS-3-0.14.zip", uri.ToString()); + Assert.AreEqual("https://archive.org/download/kOS-3-0.14/C5A224AC-kOS-3-0.14.zip", uri?.ToString()); } [Test] @@ -224,7 +223,7 @@ public void InternetArchiveDownload_NoHash_NullURL() // Arrange CkanModule module = TestData.RandSCapsuleDyneModule(); // Act - Uri uri = module.InternetArchiveDownload; + var uri = module.InternetArchiveDownload; // Assert Assert.IsNull(uri); } @@ -553,10 +552,10 @@ public void GetMinMaxVersions_WithModules_GetsCorrectVersions(string[] moduleJso // Act CkanModule.GetMinMaxVersions(modules, - out ModuleVersion minMod, - out ModuleVersion maxMod, - out GameVersion minGame, - out GameVersion maxGame); + out ModuleVersion? minMod, + out ModuleVersion? maxMod, + out GameVersion? minGame, + out GameVersion? maxGame); // Assert Assert.AreEqual(correctMinModVer, minMod); diff --git a/Tests/Core/Types/GameComparator.cs b/Tests/Core/Types/GameComparator.cs index 725eeffc7e..d05ec18de0 100644 --- a/Tests/Core/Types/GameComparator.cs +++ b/Tests/Core/Types/GameComparator.cs @@ -12,7 +12,7 @@ namespace Tests.Core.Types public class GameComparator { private static readonly GameVersion gameVersion = GameVersion.Parse("1.0.4"); - private CkanModule gameMod; + private CkanModule? gameMod; [SetUp] public void Setup() @@ -24,51 +24,51 @@ public void Setup() [Test, TestCase(typeof(StrictGameComparator), true)] public void TotallyCompatible(Type type, bool expected) { - var comparator = (IGameComparator) Activator.CreateInstance(type); + var comparator = (IGameComparator?)Activator.CreateInstance(type); // Mark the mod as being for 1.0.4 - gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max + gameMod!.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max = GameVersion.Parse("1.0.4"); // Now test! - Assert.AreEqual(expected, comparator.Compatible(new GameVersionCriteria (gameVersion), gameMod)); + Assert.AreEqual(expected, comparator?.Compatible(new GameVersionCriteria (gameVersion), gameMod)); } [Test, TestCase(typeof(StrictGameComparator), false)] public void GenerallySafeLax(Type type, bool expected) { - var comparator = (IGameComparator) Activator.CreateInstance(type); + var comparator = (IGameComparator?)Activator.CreateInstance(type); // We're going to tweak compatibly to mark the mod as being for 1.0.3 - gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max + gameMod!.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max = GameVersion.Parse("1.0.3"); // Now test! - Assert.AreEqual(expected, comparator.Compatible(new GameVersionCriteria (gameVersion), gameMod)); + Assert.AreEqual(expected, comparator?.Compatible(new GameVersionCriteria (gameVersion), gameMod)); } [Test, TestCase(typeof(StrictGameComparator), false)] public void GenerallySafeStrict(Type type, bool expected) { - var comparator = (IGameComparator) Activator.CreateInstance(type); + var comparator = (IGameComparator?)Activator.CreateInstance(type); // We're going to tweak compatibly to mark the mod as being for 1.0.3 ONLY - gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max + gameMod!.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max = GameVersion.Parse("1.0.3"); gameMod.ksp_version_strict = true; // Now test! - Assert.AreEqual(expected, comparator.Compatible(new GameVersionCriteria (gameVersion), gameMod)); + Assert.AreEqual(expected, comparator?.Compatible(new GameVersionCriteria (gameVersion), gameMod)); } [Test, TestCase(typeof(StrictGameComparator), false)] public void Incompatible(Type type, bool expected) { - var comparator = (IGameComparator) Activator.CreateInstance(type); + var comparator = (IGameComparator?)Activator.CreateInstance(type); // The mod already starts off being incompatible, so just do the test. :) - Assert.AreEqual(expected, comparator.Compatible(new GameVersionCriteria (gameVersion), gameMod)); + Assert.AreEqual(expected, comparator?.Compatible(new GameVersionCriteria (gameVersion), gameMod!)); } public static readonly object[] TestStrictGameComparatorCases = @@ -113,7 +113,7 @@ public void TestStrictGameComparator(string modVersion, string gameVersion, bool var comparator = new StrictGameComparator(); // We're going to tweak compatibly of the mod - gameMod.ksp_version = GameVersion.Parse(modVersion); + gameMod!.ksp_version = GameVersion.Parse(modVersion); // Now test! Assert.AreEqual(expectedResult, comparator.Compatible(new GameVersionCriteria(GameVersion.Parse(gameVersion)), gameMod)); @@ -122,35 +122,35 @@ public void TestStrictGameComparator(string modVersion, string gameVersion, bool public static readonly object[] TestStrictGameComparatorMinMaxCases = { // Min comapat Max comapat KSP expected - new object[] { "1.0.4", null, "1.0.3", false }, - new object[] { "1.0.4", null, "1.0.4", true }, - new object[] { "1.0.4", null, "1.0.5", true }, - new object[] { "1.0.4", null, "1.1", true }, - - new object[] { "1.0", null, "0.9", false }, - new object[] { "1.0", null, "1.0", true }, - new object[] { "1.0", null, "1.0.4", true }, - new object[] { "1.0", null, "1.1", true }, - - new object[] { "1.1", null, "1.0.4", false }, - new object[] { "1.1", null, "1.1", true }, - new object[] { "1.1", null, "1.1.1", true }, - new object[] { "1.1", null, "1.2", true }, - - new object[] { null, "1.0.4", "1.0.5", false }, - new object[] { null, "1.0.4", "1.0.4", true }, - new object[] { null, "1.0.4", "1.0.3", true }, - new object[] { null, "1.0.4", "1.0", true }, - - new object[] { null, "1.0", "0.9", true }, - new object[] { null, "1.0", "1.0", true }, - new object[] { null, "1.0", "1.0.4", true }, - new object[] { null, "1.0", "1.1", false }, - - new object[] { null, "1.1", "1.0", true }, - new object[] { null, "1.1", "1.1", true }, - new object[] { null, "1.1", "1.1.1", true }, - new object[] { null, "1.1", "1.2", false }, + new object?[] { "1.0.4", null, "1.0.3", false }, + new object?[] { "1.0.4", null, "1.0.4", true }, + new object?[] { "1.0.4", null, "1.0.5", true }, + new object?[] { "1.0.4", null, "1.1", true }, + + new object?[] { "1.0", null, "0.9", false }, + new object?[] { "1.0", null, "1.0", true }, + new object?[] { "1.0", null, "1.0.4", true }, + new object?[] { "1.0", null, "1.1", true }, + + new object?[] { "1.1", null, "1.0.4", false }, + new object?[] { "1.1", null, "1.1", true }, + new object?[] { "1.1", null, "1.1.1", true }, + new object?[] { "1.1", null, "1.2", true }, + + new object?[] { null, "1.0.4", "1.0.5", false }, + new object?[] { null, "1.0.4", "1.0.4", true }, + new object?[] { null, "1.0.4", "1.0.3", true }, + new object?[] { null, "1.0.4", "1.0", true }, + + new object?[] { null, "1.0", "0.9", true }, + new object?[] { null, "1.0", "1.0", true }, + new object?[] { null, "1.0", "1.0.4", true }, + new object?[] { null, "1.0", "1.1", false }, + + new object?[] { null, "1.1", "1.0", true }, + new object?[] { null, "1.1", "1.1", true }, + new object?[] { null, "1.1", "1.1.1", true }, + new object?[] { null, "1.1", "1.2", false }, }; [TestCaseSource("TestStrictGameComparatorMinMaxCases")] @@ -158,7 +158,7 @@ public void TestStrictGameComparatorMinMax(string modMinVersion, string modMaxVe { var comparator = new StrictGameComparator(); - gameMod.ksp_version = null; + gameMod!.ksp_version = null; gameMod.ksp_version_min = modMinVersion == null ? null : GameVersion.Parse(modMinVersion); gameMod.ksp_version_max = modMaxVersion == null ? null : GameVersion.Parse(modMaxVersion); diff --git a/Tests/Core/Types/ModuleInstallDescriptorTests.cs b/Tests/Core/Types/ModuleInstallDescriptorTests.cs index 7a9c1f5521..6446e2c0d9 100644 --- a/Tests/Core/Types/ModuleInstallDescriptorTests.cs +++ b/Tests/Core/Types/ModuleInstallDescriptorTests.cs @@ -1,52 +1,14 @@ -using System.Collections.Generic; - using NUnit.Framework; using Newtonsoft.Json; using CKAN; using CKAN.Games.KerbalSpaceProgram; -using Tests.Data; - namespace Tests.Core.Types { [TestFixture] public class ModuleInstallDescriptorTests { - [Test] - // NOTE: I've *never* got these to fail. The problem I'm trying to reproduce - // seems to involve saving to the registry and back. It's now fixed in - // JsonSingleOrArrayConverter.cs, but these tests remain, because tests are good. - public void Null_Filters() - { - // We had a bug whereby we could end up with a filter list of a single null. - // Make sure that doesn't happen ever again. - - // We want a module that doesn't specify filters. - CkanModule mod = TestData.kOS_014_module(); - - test_filter(mod.install[0].filter, "kOS/filter"); - test_filter(mod.install[0].filter_regexp, "kOS/filter_regexp"); - - // And Firespitter seems to trigger it. - - CkanModule firespitter = TestData.FireSpitterModule(); - - foreach (var stanza in firespitter.install) - { - test_filter(stanza.filter, "Firespitter/filter"); - test_filter(stanza.filter_regexp, "Firespitter/filter_regexp"); - } - } - - private static void test_filter(List filter, string message) - { - if (filter != null) - { - Assert.IsFalse(filter.Contains(null), message); - } - } - [TestCase("GameData/kOS", "GameData/kOS/Plugins/kOS.dll", "GameData", null, "GameData/kOS/Plugins/kOS.dll")] [TestCase("kOS-1.1/GameData/kOS", "kOS-1.1/GameData/kOS/Plugins/kOS.dll", "GameData", null, "GameData/kOS/Plugins/kOS.dll")] [TestCase("ModuleManager.2.5.1.dll", "ModuleManager.2.5.1.dll", "GameData", null, "GameData/ModuleManager.2.5.1.dll")] @@ -67,7 +29,7 @@ public void TransformOutputName(string file, string outputName, string installDi $"{{\"file\": \"{file}\"}}"); // Act - var result = stanza.TransformOutputName(new KerbalSpaceProgram(), outputName, installDir, @as); + var result = stanza?.TransformOutputName(new KerbalSpaceProgram(), outputName, installDir, @as); // Assert Assert.That(result, Is.EqualTo(expected)); @@ -83,7 +45,7 @@ public void TransformOutputNameThrowsOnInvalidParameters(string file, string out $"{{\"file\": \"{file}\"}}"); // Act - TestDelegate act = () => stanza.TransformOutputName(new KerbalSpaceProgram(), outputName, installDir, @as); + TestDelegate act = () => stanza?.TransformOutputName(new KerbalSpaceProgram(), outputName, installDir, @as); // Assert Assert.That(act, Throws.Exception); diff --git a/Tests/Core/Utilities.cs b/Tests/Core/Utilities.cs index 03984b2c87..51ec0579f1 100644 --- a/Tests/Core/Utilities.cs +++ b/Tests/Core/Utilities.cs @@ -10,7 +10,7 @@ namespace Tests.Core { [TestFixture] public class Utilities { - private string tempDir; + private string? tempDir; private readonly string goodKspDir = TestData.good_ksp_dir(); [SetUp] @@ -22,43 +22,46 @@ public void CreateTempDir() [TearDown] public void EmptyTempDir() { - Directory.Delete(tempDir, true); + if (tempDir != null) + { + Directory.Delete(tempDir, true); + } } [Test] public void CopyDirectory_Recursive_DestHasAllContents() { - CKAN.Utilities.CopyDirectory(goodKspDir, tempDir, Array.Empty(), Array.Empty()); + CKAN.Utilities.CopyDirectory(goodKspDir, tempDir!, Array.Empty(), Array.Empty()); - var fi = new FileInfo(Path.Combine(tempDir, "GameData")); + var fi = new FileInfo(Path.Combine(tempDir!, "GameData")); Assert.IsFalse(fi.Attributes.HasFlag(FileAttributes.ReparsePoint), "GameData should not be a symlink"); Assert.IsTrue(UtilStatic.CompareFiles( Path.Combine(goodKspDir, "GameData", "README.md"), - Path.Combine(tempDir, "GameData", "README.md"))); + Path.Combine(tempDir!, "GameData", "README.md"))); Assert.IsTrue(UtilStatic.CompareFiles( Path.Combine(goodKspDir, "buildID.txt"), - Path.Combine(tempDir, "buildID.txt"))); + Path.Combine(tempDir!, "buildID.txt"))); Assert.IsTrue(UtilStatic.CompareFiles( Path.Combine(goodKspDir, "readme.txt"), - Path.Combine(tempDir, "readme.txt"))); + Path.Combine(tempDir!, "readme.txt"))); } [Test] public void CopyDirectory_WithSymlinks_MakesSymlinks() { // Arrange / Act - CKAN.Utilities.CopyDirectory(Path.Combine(TestData.DataDir(), "KSP"), tempDir, + CKAN.Utilities.CopyDirectory(Path.Combine(TestData.DataDir(), "KSP"), tempDir!, new string[] { "KSP-0.25/GameData" }, Array.Empty()); // Assert - var fi1 = new FileInfo(Path.Combine(tempDir, "KSP-0.25")); + var fi1 = new FileInfo(Path.Combine(tempDir!, "KSP-0.25")); Assert.IsFalse(fi1.Attributes.HasFlag(FileAttributes.ReparsePoint), "KSP-0.25 should not be a symlink"); - var fi2 = new FileInfo(Path.Combine(tempDir, "KSP-0.25", "GameData")); + var fi2 = new FileInfo(Path.Combine(tempDir!, "KSP-0.25", "GameData")); Assert.IsTrue(fi2.Attributes.HasFlag(FileAttributes.ReparsePoint), "KSP-0.25/GameData should be a symlink"); - var fi3 = new FileInfo(Path.Combine(tempDir, "KSP-0.25", "GameData", "README.md")); + var fi3 = new FileInfo(Path.Combine(tempDir!, "KSP-0.25", "GameData", "README.md")); Assert.IsFalse(fi3.Attributes.HasFlag(FileAttributes.ReparsePoint), "KSP-0.25/GameData/README.md should not be a symlink"); @@ -71,15 +74,15 @@ public void CopyDirectory_SourceNotExisting_ThrowsDirectoryNotFoundKraken() var sourceDir = "/gibberish/DOESNTEXIST/hopefully"; // Act and Assert - Assert.Throws(() => CKAN.Utilities.CopyDirectory(sourceDir, tempDir, Array.Empty(), Array.Empty())); + Assert.Throws(() => CKAN.Utilities.CopyDirectory(sourceDir, tempDir!, Array.Empty(), Array.Empty())); } [Test] public void CopyDirectory_DestNotEmpty_ThrowsException() { - File.WriteAllText(Path.Combine(tempDir, "thatsafile"), "not empty"); + File.WriteAllText(Path.Combine(tempDir!, "thatsafile"), "not empty"); - Assert.Throws(() => CKAN.Utilities.CopyDirectory(goodKspDir, tempDir, Array.Empty(), Array.Empty())); + Assert.Throws(() => CKAN.Utilities.CopyDirectory(goodKspDir, tempDir!, Array.Empty(), Array.Empty())); } } } diff --git a/Tests/Core/Versioning/GameVersionBoundTests.cs b/Tests/Core/Versioning/GameVersionBoundTests.cs index b337f39799..c1b524e432 100644 --- a/Tests/Core/Versioning/GameVersionBoundTests.cs +++ b/Tests/Core/Versioning/GameVersionBoundTests.cs @@ -100,7 +100,7 @@ public void NullEqualityWorksCorrectly() // Act // ReSharper disable ConditionIsAlwaysTrueOrFalse var genericEquals = new GameVersionBound().Equals(null); - var nonGenericEquals = new GameVersionBound().Equals((object)null); + var nonGenericEquals = new GameVersionBound().Equals((object?)null); var equalsOperatorNullLeft = null == new GameVersionBound(); var equalsOperatorNullRight = new GameVersionBound() == null; var notEqualsOperatorNullLeft = null != new GameVersionBound(); diff --git a/Tests/Core/Versioning/GameVersionJsonConverterTests.cs b/Tests/Core/Versioning/GameVersionJsonConverterTests.cs index 9af0a59852..2d91050970 100644 --- a/Tests/Core/Versioning/GameVersionJsonConverterTests.cs +++ b/Tests/Core/Versioning/GameVersionJsonConverterTests.cs @@ -21,7 +21,7 @@ public sealed class GameVersionJsonConverterTests private static readonly object[] ReadJsonCases = { - new object[] { @"{ ""GameVersion"": null }", null }, + new object?[] { @"{ ""GameVersion"": null }", null }, new object[] { @"{ ""GameVersion"": ""any"" }", GameVersion.Any }, new object[] { @"{ ""GameVersion"": ""1""} ", new GameVersion(1) }, new object[] { @"{ ""GameVersion"": ""1.2""} ", new GameVersion(1, 2) }, @@ -43,10 +43,10 @@ public void WriteJsonWorksCorrectly(GameVersion version, string expected) var poco = new TestPoco { GameVersion = version }; // Act - dynamic result = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(poco)); + dynamic? result = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(poco)); // Assert - Assert.That((string)result.GameVersion, Is.EqualTo(expected)); + Assert.That((string?)result?.GameVersion, Is.EqualTo(expected)); } [TestCaseSource("ReadJsonCases")] @@ -56,7 +56,7 @@ public void ReadJsonWorksCorrectly(string json, GameVersion expected) var result = JsonConvert.DeserializeObject(json); // Assert - Assert.That(result.GameVersion, Is.EqualTo(expected)); + Assert.That(result?.GameVersion, Is.EqualTo(expected)); } [TestCaseSource("ReadJsonFailureCases")] @@ -89,7 +89,7 @@ public void CanConvertWorksCorrectly(Type objectType, bool expected) private sealed class TestPoco { - public GameVersion GameVersion { get; set; } + public GameVersion? GameVersion { get; set; } } } } diff --git a/Tests/Core/Versioning/GameVersionRangeTests.cs b/Tests/Core/Versioning/GameVersionRangeTests.cs index fd42545f3f..f3c4bb9acd 100644 --- a/Tests/Core/Versioning/GameVersionRangeTests.cs +++ b/Tests/Core/Versioning/GameVersionRangeTests.cs @@ -98,7 +98,7 @@ public sealed class GameVersionRangeTests new GameVersionBound(new GameVersion(1, 2, 3, 4), true) ), }, - new object[] + new object?[] { new GameVersionRange( new GameVersionBound(new GameVersion(1, 2, 3, 4), false), @@ -110,7 +110,7 @@ public sealed class GameVersionRangeTests ), null }, - new object[] + new object?[] { new GameVersionRange( new GameVersionBound(new GameVersion(1, 2, 3, 4), false), @@ -137,7 +137,7 @@ public sealed class GameVersionRangeTests new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ), }, - new object[] + new object?[] { new GameVersionRange( new GameVersionBound(new GameVersion(1, 1, 0, 0), true), @@ -164,7 +164,7 @@ public sealed class GameVersionRangeTests new GameVersionBound(new GameVersion(1, 0, 4, 1234), true) ), }, - new object[] + new object?[] { new GameVersionRange( new GameVersionBound(new GameVersion(1, 0, 4, 1235), true), @@ -251,7 +251,7 @@ public sealed class GameVersionRangeTests new GameVersionBound(new GameVersion(1, 2, 0, 0), false) ), }, - new object[] + new object?[] { new GameVersionRange( new GameVersionBound(new GameVersion(1, 1, 0, 0), true), @@ -263,7 +263,7 @@ public sealed class GameVersionRangeTests ), null }, - new object[] + new object?[] { new GameVersionRange( new GameVersionBound(new GameVersion(1, 0, 0, 0), true), @@ -538,12 +538,12 @@ public void EqualityWorksCorrectly(GameVersionRange vr1, GameVersionRange vr2, b public void NullEqualityWorksCorrectly() { // Arrange - var sut = new GameVersionRange(new GameVersionBound(), new GameVersionBound()); + GameVersionRange sut = new GameVersionRange(new GameVersionBound(), new GameVersionBound()); // Act // ReSharper disable ConditionIsAlwaysTrueOrFalse var genericEquals = sut.Equals(null); - var nonGenericEquals = sut.Equals((object)null); + var nonGenericEquals = sut!.Equals((object?)null); var equalsOperatorNullLeft = null == sut; var equalsOperatorNullRight = sut == null; var notEqualsOperatorNullLeft = null != sut; diff --git a/Tests/Core/Versioning/GameVersionTests.cs b/Tests/Core/Versioning/GameVersionTests.cs index 2db97e0c6f..ea164d26d0 100644 --- a/Tests/Core/Versioning/GameVersionTests.cs +++ b/Tests/Core/Versioning/GameVersionTests.cs @@ -22,7 +22,7 @@ public class GameVersionTests private static readonly object[] ParseFailureCases = { - new object[] { null }, + new object?[] { null }, new object[] { "" }, new object[] { "1.2.3.4.5" }, new object[] { "1.2.3.A" }, @@ -35,7 +35,7 @@ public class GameVersionTests private static readonly object[] EqualityCases = { - new object[] { new GameVersion(), null, false }, + new object?[] { new GameVersion(), null, false }, new object[] { new GameVersion(), new GameVersion(), true }, new object[] { new GameVersion(1), new GameVersion(1), true }, new object[] { new GameVersion(1, 2), new GameVersion(1, 2), true}, @@ -305,12 +305,12 @@ public void ToVersionRangeWorksCorrectly(GameVersion version, GameVersionRange e public void TryParseWorksCorrectly(string s, GameVersion version) { // Act - var success = GameVersion.TryParse(s, out GameVersion result); + var success = GameVersion.TryParse(s, out GameVersion? result); // Assert Assert.IsTrue(success); Assert.AreEqual(version, result); - Assert.AreEqual(s, result.ToString()); + Assert.AreEqual(s, result?.ToString()); } [TestCaseSource("ParseFailureCases")] @@ -383,29 +383,13 @@ public void CompareToThrowsOnNullParameters() // ReSharper disable ReturnValueOfPureMethodIsNotUsed // ReSharper disable UnusedVariable TestDelegate actGenericCompareTo = () => new GameVersion().CompareTo(null); - TestDelegate actNonGenericCompareTo = () => new GameVersion().CompareTo((object)null); - TestDelegate lessThanOperatorNullLeft = () => { var _ = null < new GameVersion(); }; - TestDelegate lessThanOperatorNullRight = () => { var _ = new GameVersion() < null; }; - TestDelegate lessThanOrEqualOperatorNullLeft = () => { var _ = null <= new GameVersion(); }; - TestDelegate lessThanOrEqualOperatorNullRight = () => { var _ = new GameVersion() <= null; }; - TestDelegate greaterThanOperatorNullLeft = () => { var _ = null > new GameVersion(); }; - TestDelegate greaterThanOperatorNullRight = () => { var _ = new GameVersion() > null; }; - TestDelegate greaterThanOrEqualOperatorNullLeft = () => { var _ = null >= new GameVersion(); }; - TestDelegate greaterThanOrEqualOperatorNullRight = () => { var _ = new GameVersion() >= null; }; + TestDelegate actNonGenericCompareTo = () => new GameVersion().CompareTo((object?)null); // ReSharper restore UnusedVariable // ReSharper restore ReturnValueOfPureMethodIsNotUsed // Assert Assert.That(actGenericCompareTo, Throws.Exception); Assert.That(actNonGenericCompareTo, Throws.Exception); - Assert.That(lessThanOperatorNullLeft, Throws.Exception); - Assert.That(lessThanOperatorNullRight, Throws.Exception); - Assert.That(lessThanOrEqualOperatorNullLeft, Throws.Exception); - Assert.That(lessThanOrEqualOperatorNullRight, Throws.Exception); - Assert.That(greaterThanOperatorNullLeft, Throws.Exception); - Assert.That(greaterThanOperatorNullRight, Throws.Exception); - Assert.That(greaterThanOrEqualOperatorNullLeft, Throws.Exception); - Assert.That(greaterThanOrEqualOperatorNullRight, Throws.Exception); } [Test] diff --git a/Tests/Data/DisposableKSP.cs b/Tests/Data/DisposableKSP.cs index 02a366d9df..6750dd64ad 100644 --- a/Tests/Data/DisposableKSP.cs +++ b/Tests/Data/DisposableKSP.cs @@ -61,8 +61,6 @@ public void Dispose() throw new AssertionException(_failureMessage, ex); } } - - KSP = null; } } } diff --git a/Tests/Data/TestData.cs b/Tests/Data/TestData.cs index 33e299ec03..54534e7a3a 100644 --- a/Tests/Data/TestData.cs +++ b/Tests/Data/TestData.cs @@ -18,7 +18,7 @@ public static string DataDir() // But this makes updates hard. // 4. A better, but much harder solution, is to not require harded files on disk for any of our tests, but that's // a lot of work. - => Path.Combine(Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName, + => Path.Combine(Directory.GetParent(Assembly.GetExecutingAssembly().Location)!.FullName, "../../../../../../Tests/Data"); public static string DataDir(string file) @@ -339,7 +339,7 @@ public static CkanModule DogeCoinFlag_101_module_find() CkanModule doge = DogeCoinFlag_101_module(); // Hand hack in the 'find' directive. - doge.install[0].file = null; + doge.install![0].file = null; doge.install[0].find = "DogeCoinFlag"; return doge; @@ -353,7 +353,7 @@ public static CkanModule DogeCoinFlag_101_module_include() { CkanModule doge = DogeCoinFlag_101_module(); - doge.install[0].filter = null; + doge.install![0].filter = null; doge.install[0].filter_regexp = null; doge.install[0].include_only = new List { "dogecoin.png" }; doge.install[0].include_only_regexp = new List { "\\.bak$" }; @@ -899,13 +899,13 @@ public RandomModuleGenerator(Random generator) } public CkanModule GeneratorRandomModule( - GameVersion ksp_version = null, - List conflicts = null, - List depends = null, - List suggests = null, - List provides = null, - string identifier = null, - ModuleVersion version = null) + GameVersion? ksp_version = null, + List? conflicts = null, + List? depends = null, + List? suggests = null, + List? provides = null, + string? identifier = null, + ModuleVersion? version = null) => new CkanModule(new ModuleVersion(1.ToString(CultureInfo.InvariantCulture)), identifier ?? Generator.Next().ToString(CultureInfo.InvariantCulture), Generator.Next().ToString(CultureInfo.InvariantCulture), diff --git a/Tests/GUI/GUIConfiguration.cs b/Tests/GUI/GUIConfiguration.cs index 9c474c0d8d..7d68c4d08e 100644 --- a/Tests/GUI/GUIConfiguration.cs +++ b/Tests/GUI/GUIConfiguration.cs @@ -13,7 +13,7 @@ namespace Tests.GUI [TestFixture] public class GuiConfigurationTests { - private string tempDir; + private string? tempDir; [OneTimeSetUp] public void Setup() @@ -24,13 +24,16 @@ public void Setup() [OneTimeTearDown] public void TearDown() { - Directory.Delete(tempDir, true); + if (tempDir != null) + { + Directory.Delete(tempDir, true); + } } [Test] public void LoadOrCreateConfiguration_MalformedXMLFile_ThrowsKraken() { - string tempFile = Path.Combine(tempDir, "invalid.xml"); + string tempFile = Path.Combine(tempDir!, "invalid.xml"); using (var stream = new StreamWriter(tempFile)) { @@ -43,7 +46,7 @@ public void LoadOrCreateConfiguration_MalformedXMLFile_ThrowsKraken() [Test] public void LoadOrCreateConfiguration_CorrectConfigurationFile_Loaded() { - string tempFile = Path.Combine(tempDir, "valid.xml"); + string tempFile = Path.Combine(tempDir!, "valid.xml"); using (var stream = new StreamWriter(tempFile)) { diff --git a/Tests/GUI/Model/GUIMod.cs b/Tests/GUI/Model/GUIMod.cs index d4f67df883..55032737f3 100644 --- a/Tests/GUI/Model/GUIMod.cs +++ b/Tests/GUI/Model/GUIMod.cs @@ -38,7 +38,7 @@ public void NewGuiModsAreNotSelectedForUpgrade() var registry = new Registry(repoData.Manager, repo.repo); var ckan_mod = registry.GetModuleByVersion("kOS", "0.14"); - var mod = new GUIMod(ckan_mod, repoData.Manager, registry, manager.CurrentInstance.VersionCriteria(), + var mod = new GUIMod(ckan_mod!, repoData.Manager, registry, manager.CurrentInstance.VersionCriteria(), null, false, false); Assert.True(mod.SelectedMod == mod.InstalledMod?.Module); } @@ -63,7 +63,7 @@ public void HasUpdate_UpdateAvailable_ReturnsTrue() { var registry = new Registry(repoData.Manager, repo.repo); - registry.RegisterModule(old_version, new List(), null, false); + registry.RegisterModule(old_version, new List(), tidy.KSP, false); var upgradeableGroups = registry.CheckUpgradeable(tidy.KSP, new HashSet()); @@ -104,15 +104,15 @@ public void GameCompatibility_OutOfOrderGameVersions_TrueMaxVersion() { var registry = new Registry(repoData.Manager, repo.repo); - CkanModule mainVersion = registry.GetModuleByVersion("OutOfOrderMod", "1.2.0"); - CkanModule prevVersion = registry.GetModuleByVersion("OutOfOrderMod", "1.1.0"); + var mainVersion = registry.GetModuleByVersion("OutOfOrderMod", "1.2.0"); + var prevVersion = registry.GetModuleByVersion("OutOfOrderMod", "1.1.0"); // Act - GUIMod m = new GUIMod(mainVersion, repoData.Manager, registry, tidy.KSP.VersionCriteria(), + GUIMod m = new GUIMod(mainVersion!, repoData.Manager, registry, tidy.KSP.VersionCriteria(), null, false, false); // Assert - Assert.AreEqual("1.4.2", m.GameCompatibilityVersion.ToString()); + Assert.AreEqual("1.4.2", m.GameCompatibilityVersion?.ToString()); } } diff --git a/Tests/GUI/Model/ModList.cs b/Tests/GUI/Model/ModList.cs index 82939afdca..bba9f5c9e6 100644 --- a/Tests/GUI/Model/ModList.cs +++ b/Tests/GUI/Model/ModList.cs @@ -49,7 +49,7 @@ public void IsVisible_WithAllAndNoNameFilter_ReturnsTrueForCompatible() var item = new ModList(); Assert.That(item.IsVisible( - new GUIMod(ckan_mod, repoData.Manager, registry, manager.CurrentInstance.VersionCriteria(), + new GUIMod(ckan_mod!, repoData.Manager, registry, manager.CurrentInstance.VersionCriteria(), null, false, false), manager.CurrentInstance.Name, manager.CurrentInstance.game, @@ -150,20 +150,20 @@ public void InstallAndSortByCompat_WithAnyCompat_NoCrash() registry.RepositoriesClear(); registry.RepositoriesAdd(repo.repo); // A module with a ksp_version of "any" to repro our issue - var anyVersionModule = registry.GetModuleByVersion("DogeCoinFlag", "1.01"); + var anyVersionModule = registry.GetModuleByVersion("DogeCoinFlag", "1.01")!; Assert.IsNotNull(anyVersionModule, "DogeCoinFlag 1.01 should exist"); var modList = new ModList(); var listGui = new DataGridView(); - var installer = new ModuleInstaller(instance.KSP, manager.Cache, manager.User); - var downloader = new NetAsyncModulesDownloader(user, manager.Cache); + var installer = new ModuleInstaller(instance.KSP, manager.Cache!, manager.User); + var downloader = new NetAsyncModulesDownloader(user, manager.Cache!); // Act // Install module and set it as pre-installed - manager.Cache.Store(TestData.DogeCoinFlag_101_module(), TestData.DogeCoinFlagZip(), new Progress(percent => {})); + manager.Cache?.Store(TestData.DogeCoinFlag_101_module(), TestData.DogeCoinFlagZip(), new Progress(percent => {})); registry.RegisterModule(anyVersionModule, new List(), instance.KSP, false); - HashSet possibleConfigOnlyDirs = null; + HashSet? possibleConfigOnlyDirs = null; installer.InstallList( new List { anyVersionModule }, new RelationshipResolverOptions(), @@ -188,7 +188,7 @@ public void InstallAndSortByCompat_WithAnyCompat_NoCrash() Assert.IsNotNull(modList); var modules = repoData.Manager.GetAllAvailableModules(Enumerable.Repeat(repo.repo, 1)) - .Select(mod => new GUIMod(mod.Latest(), repoData.Manager, registry, instance.KSP.VersionCriteria(), + .Select(mod => new GUIMod(mod.Latest()!, repoData.Manager, registry, instance.KSP.VersionCriteria(), null, false, false)) .ToList(); diff --git a/Tests/GUI/ThreadSafetyTests.cs b/Tests/GUI/ThreadSafetyTests.cs index b1114c03ce..1696077f34 100644 --- a/Tests/GUI/ThreadSafetyTests.cs +++ b/Tests/GUI/ThreadSafetyTests.cs @@ -22,7 +22,7 @@ public class ThreadSafetyTests public void GUIAssemblyModule_MethodsWithForbidGUICalls_DontCallGUI() { // Arrange / Act - var mainModule = ModuleDefinition.ReadModule(Assembly.GetAssembly(typeof(CKAN.GUI.Main)) + var mainModule = ModuleDefinition.ReadModule(Assembly.GetAssembly(typeof(CKAN.GUI.Main))! .Location); var allMethods = mainModule.Types .SelectMany(t => GetAllNestedTypes(t)) @@ -50,6 +50,7 @@ private IEnumerable GetAllNestedTypes(TypeDefinition td) private IEnumerable FindStartedTasks(MethodDefinition md) => StartNewCalls(md).Select(FindStartNewArgument) + .OfType() .Select(taskArg => new MethodCall() { md, taskArg }); private IEnumerable StartNewCalls(MethodDefinition md) @@ -71,7 +72,7 @@ private bool isStartNew(MethodReference mr) // 2. newobj a System.Action to hold it // 3. callvirt StartNew // ... so find the operand of the ldftn most immediately preceding the call - private MethodDefinition FindStartNewArgument(Instruction instr) + private MethodDefinition? FindStartNewArgument(Instruction instr) => instr.OpCode.Name == "ldftn" ? instr.Operand as MethodDefinition : FindStartNewArgument(instr.Previous); @@ -112,10 +113,11 @@ private IEnumerable methodsCalledBy(MethodDefinition methDef) .Where(instr => callOpCodes.Contains(instr.OpCode.Name)) .Select(instr => instr.Operand as MethodDefinition ?? GetSetterDef(instr.Operand as MethodReference)) + .OfType() .Where(calledMeth => calledMeth?.Body != null); // Property setters are virtual and have references instead of definitions - private MethodDefinition GetSetterDef(MethodReference mr) + private MethodDefinition? GetSetterDef(MethodReference? mr) => (mr?.Name.StartsWith("set_") ?? false) ? mr.Resolve() : null; @@ -139,7 +141,7 @@ private bool unsafeType(TypeDefinition t) || (t.BaseType != null && unsafeType(t.BaseType.Resolve())); private static readonly Type forbidAttrib = typeof(ForbidGUICallsAttribute); - private static readonly string winformsNamespace = typeof(Control).Namespace; + private static readonly string winformsNamespace = typeof(Control).Namespace!; private static readonly HashSet callOpCodes = new HashSet { diff --git a/Tests/NetKAN/AVC.cs b/Tests/NetKAN/AVC.cs index 8a68530e3c..4dbca00764 100644 --- a/Tests/NetKAN/AVC.cs +++ b/Tests/NetKAN/AVC.cs @@ -17,9 +17,9 @@ public void Json() var avc = JsonConvert.DeserializeObject(json); - Assert.AreEqual("0.24.2", avc.ksp_version.ToString()); - Assert.AreEqual("0.24.0", avc.ksp_version_min.ToString()); - Assert.AreEqual("0.24.2", avc.ksp_version_max.ToString()); + Assert.AreEqual("0.24.2", avc?.ksp_version?.ToString()); + Assert.AreEqual("0.24.0", avc?.ksp_version_min?.ToString()); + Assert.AreEqual("0.24.2", avc?.ksp_version_max?.ToString()); } [Test] @@ -29,9 +29,9 @@ public void JsonOneLineVersion() var avc = JsonConvert.DeserializeObject(json); - Assert.AreEqual("0.24.2", avc.ksp_version.ToString()); - Assert.AreEqual("0.24.0", avc.ksp_version_min.ToString()); - Assert.AreEqual("1.0.0", avc.ksp_version_max.ToString()); + Assert.AreEqual("0.24.2", avc?.ksp_version?.ToString()); + Assert.AreEqual("0.24.0", avc?.ksp_version_min?.ToString()); + Assert.AreEqual("1.0.0", avc?.ksp_version_max?.ToString()); } [Test] @@ -40,7 +40,7 @@ public void WildcardMajor_OutputsAnyVersion() var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":-1, ""MINOR"":-1, ""PATCH"":-1}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (GameVersion) converter.ReadJson(reader, null, null, null); + var result = (GameVersion)converter.ReadJson(reader, null, null, null)!; Assert.That(!result.IsMajorDefined); } @@ -50,7 +50,7 @@ public void WildcardMinor_VersionOnlyHasMajor() var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":1, ""MINOR"":-1, ""PATCH"":-1}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (GameVersion) converter.ReadJson(reader, null, null, null); + var result = (GameVersion)converter.ReadJson(reader, null, null, null)!; Assert.That(result, Is.EqualTo(GameVersion.Parse("1"))); } @@ -60,7 +60,7 @@ public void WildcardPatch_VersionOnlyHasMajorMinor() var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":1, ""MINOR"":5, ""PATCH"":-1}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (GameVersion)converter.ReadJson(reader, null, null, null); + var result = (GameVersion)converter.ReadJson(reader, null, null, null)!; Assert.That(result, Is.EqualTo(GameVersion.Parse("1.5"))); } @@ -70,7 +70,7 @@ public void MissingMajor_OutputsAnyVersion() var converter = new JsonAvcToGameVersion(); string json = @"{}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (GameVersion) converter.ReadJson(reader, null, null, null); + var result = (GameVersion)converter.ReadJson(reader, null, null, null)!; Assert.That(!result.IsMajorDefined); } @@ -80,7 +80,7 @@ public void MissingMinor_VersionOnlyHasMajor() var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":1}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (GameVersion) converter.ReadJson(reader, null, null, null); + var result = (GameVersion)converter.ReadJson(reader, null, null, null)!; Assert.That(result, Is.EqualTo(GameVersion.Parse("1"))); } @@ -90,7 +90,7 @@ public void MissingPatch_VersionOnlyHasMajorMinor() var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":1, ""MINOR"":5}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (GameVersion)converter.ReadJson(reader, null, null, null); + var result = (GameVersion)converter.ReadJson(reader, null, null, null)!; Assert.That(result, Is.EqualTo(GameVersion.Parse("1.5"))); } diff --git a/Tests/NetKAN/Extensions/JObjectExtensionsTests.cs b/Tests/NetKAN/Extensions/JObjectExtensionsTests.cs index 26ccc4c4de..ee3f7b8c09 100644 --- a/Tests/NetKAN/Extensions/JObjectExtensionsTests.cs +++ b/Tests/NetKAN/Extensions/JObjectExtensionsTests.cs @@ -18,7 +18,7 @@ public void SafeAddAddsPropertyWhenItDoesNotExist() sut.SafeAdd("foo", "bar"); // Assert - Assert.That((string)sut["foo"], Is.EqualTo("bar"), + Assert.That((string?)sut["foo"], Is.EqualTo("bar"), "SafeAdd() should add property if it doesn't exist." ); } @@ -34,7 +34,7 @@ public void SafeAddDoesNotAddPropertyWhenItAlreadyExists() sut.SafeAdd("foo", "baz"); // Assert - Assert.That((string)sut["foo"], Is.EqualTo("bar"), + Assert.That((string?)sut["foo"], Is.EqualTo("bar"), "SafeAdd() should not add property if it already exists." ); } @@ -50,7 +50,7 @@ public void SafeAddDoesNotAddPropertyWhenValueIsNull() sut.SafeAdd("foo", null as JToken); // Assert - Assert.That((string)sut["foo"], Is.EqualTo("bar"), + Assert.That((string?)sut["foo"], Is.EqualTo("bar"), "SafeAdd() should not add property if value is null." ); } @@ -63,7 +63,7 @@ public void SafeAddDoesNotAddPropertyWhenValueIsTokenWithNullValue() var sut = new JObject(); // Act - sut.SafeAdd("foo", (string)null); + sut.SafeAdd("foo", (string?)null); // Assert Assert.That(sut.Properties().Any(i => i.Name == "foo"), Is.False, diff --git a/Tests/NetKAN/Extensions/VersionExtensionsTests.cs b/Tests/NetKAN/Extensions/VersionExtensionsTests.cs index fcff933952..257f452a5c 100644 --- a/Tests/NetKAN/Extensions/VersionExtensionsTests.cs +++ b/Tests/NetKAN/Extensions/VersionExtensionsTests.cs @@ -32,7 +32,7 @@ public void ToSpecVersionJsonReturnsStringForHigherVersions() var result = version.ToSpecVersionJson(); // Assert - Assert.That((string)result == "v1.2", Is.True, + Assert.That((string?)result == "v1.2", Is.True, "ToSpecVersionJson() should return a string for versions higher than 1." ); } diff --git a/Tests/NetKAN/Extensions/YamlExtensionsTests.cs b/Tests/NetKAN/Extensions/YamlExtensionsTests.cs index 1c0f785c01..fdad14a286 100644 --- a/Tests/NetKAN/Extensions/YamlExtensionsTests.cs +++ b/Tests/NetKAN/Extensions/YamlExtensionsTests.cs @@ -38,30 +38,30 @@ public void Parse_ValidInput_Works() YamlMappingNode yaml = YamlExtensions.Parse(input).First(); // Assert - Assert.AreEqual("v1.4", (string)yaml["spec_version"]); - Assert.AreEqual("Astrogator", (string)yaml["identifier"]); - Assert.AreEqual("#/ckan/github/HebaruSan/Astrogator", (string)yaml["$kref"]); - Assert.AreEqual("#/ckan/ksp-avc", (string)yaml["$vref"]); - Assert.AreEqual("GPL-3.0", (string)yaml["license"]); + Assert.AreEqual("v1.4", (string?)yaml["spec_version"]); + Assert.AreEqual("Astrogator", (string?)yaml["identifier"]); + Assert.AreEqual("#/ckan/github/HebaruSan/Astrogator", (string?)yaml["$kref"]); + Assert.AreEqual("#/ckan/ksp-avc", (string?)yaml["$vref"]); + Assert.AreEqual("GPL-3.0", (string?)yaml["license"]); CollectionAssert.AreEqual( new string[] { "plugin", "information", "control" }, - (yaml["tags"] as YamlSequenceNode).Children.Select(yn => (string)yn) + (yaml["tags"] as YamlSequenceNode)?.Children.Select(yn => (string?)yn) ); Assert.AreEqual( "https://forum.kerbalspaceprogram.com/index.php?/topic/155998-*", - (string)yaml["resources"]["homepage"] + (string?)yaml["resources"]["homepage"] ); Assert.AreEqual( "https://github.com/HebaruSan/Astrogator/issues", - (string)yaml["resources"]["bugtracker"] + (string?)yaml["resources"]["bugtracker"] ); Assert.AreEqual( "https://github.com/HebaruSan/Astrogator", - (string)yaml["resources"]["repository"] + (string?)yaml["resources"]["repository"] ); - Assert.AreEqual("ModuleManager", (string)yaml["recommends"][0]["name"]); - Assert.AreEqual("LoadingTipsPlus", (string)yaml["recommends"][1]["name"]); + Assert.AreEqual("ModuleManager", (string?)yaml["recommends"][0]["name"]); + Assert.AreEqual("LoadingTipsPlus", (string?)yaml["recommends"][1]["name"]); } [Test] @@ -111,30 +111,30 @@ public void ToJObject_ValidInput_Works() JObject json = yaml.ToJObject(); // Assert - Assert.AreEqual("v1.4", (string)json["spec_version"]); - Assert.AreEqual("Astrogator", (string)json["identifier"]); - Assert.AreEqual("#/ckan/github/HebaruSan/Astrogator", (string)json["$kref"]); - Assert.AreEqual("#/ckan/ksp-avc", (string)json["$vref"]); - Assert.AreEqual("GPL-3.0", (string)json["license"]); + Assert.AreEqual("v1.4", (string?)json["spec_version"]); + Assert.AreEqual("Astrogator", (string?)json["identifier"]); + Assert.AreEqual("#/ckan/github/HebaruSan/Astrogator", (string?)json["$kref"]); + Assert.AreEqual("#/ckan/ksp-avc", (string?)json["$vref"]); + Assert.AreEqual("GPL-3.0", (string?)json["license"]); CollectionAssert.AreEqual( new string[] { "plugin", "information", "control" }, - (json["tags"] as JArray).Select(elt => (string)elt) + (json["tags"] as JArray)?.Select(elt => (string?)elt) ); Assert.AreEqual( "https://forum.kerbalspaceprogram.com/index.php?/topic/155998-*", - (string)json["resources"]["homepage"] + (string?)json["resources"]?["homepage"] ); Assert.AreEqual( "https://github.com/HebaruSan/Astrogator/issues", - (string)json["resources"]["bugtracker"] + (string?)json["resources"]?["bugtracker"] ); Assert.AreEqual( "https://github.com/HebaruSan/Astrogator", - (string)json["resources"]["repository"] + (string?)json["resources"]?["repository"] ); - Assert.AreEqual("ModuleManager", (string)json["recommends"][0]["name"]); - Assert.AreEqual("LoadingTipsPlus", (string)json["recommends"][1]["name"]); + Assert.AreEqual("ModuleManager", (string?)json["recommends"]?[0]?["name"]); + Assert.AreEqual("LoadingTipsPlus", (string?)json["recommends"]?[1]?["name"]); } } } diff --git a/Tests/NetKAN/MainClass.cs b/Tests/NetKAN/MainClass.cs index 96cff11cc2..6fdcb8fde4 100644 --- a/Tests/NetKAN/MainClass.cs +++ b/Tests/NetKAN/MainClass.cs @@ -18,10 +18,10 @@ public void FixVersionStringsUnharmed() { JObject metadata = JObject.Parse(TestData.DogeCoinFlag_101()); - Assert.AreEqual("1.01", (string)metadata["version"], "Original version as expected"); + Assert.AreEqual("1.01", (string?)metadata["version"], "Original version as expected"); metadata = new EpochTransformer().Transform(new Metadata(metadata), opts).First().Json(); - Assert.AreEqual("1.01", (string)metadata["version"], "Version unharmed without x_netkan_force_v"); + Assert.AreEqual("1.01", (string?)metadata["version"], "Version unharmed without x_netkan_force_v"); } [TestCase(@"{""spec_version"": 1, ""version"" : ""1.01""}", "1.01", "1.01")] @@ -35,11 +35,11 @@ public void FixVersionStrings(string json, string orig_version, string new_versi { JObject metadata = JObject.Parse(json); - Assert.AreEqual(orig_version, (string)metadata["version"], "JSON parsed as expected"); + Assert.AreEqual(orig_version, (string?)metadata["version"], "JSON parsed as expected"); metadata = new ForcedVTransformer().Transform(new Metadata(metadata), opts).First().Json(); - Assert.AreEqual(new_version, (string)metadata["version"], "Output string as expected"); + Assert.AreEqual(new_version, (string?)metadata["version"], "Output string as expected"); } [TestCase(@"{""spec_version"": 1, ""version"" : ""1.01""}", "1.01", "1.01")] @@ -50,9 +50,9 @@ public void FixVersionStrings(string json, string orig_version, string new_versi public void ApplyEpochNumber(string json, string orig_version, string new_version) { JObject metadata = JObject.Parse(json); - Assert.AreEqual(orig_version, (string)metadata["version"], "JSON parsed as expected"); + Assert.AreEqual(orig_version, (string?)metadata["version"], "JSON parsed as expected"); metadata = new EpochTransformer().Transform(new Metadata(metadata), opts).First().Json(); - Assert.AreEqual(new_version, (string)metadata["version"], "Output string as expected"); + Assert.AreEqual(new_version, (string?)metadata["version"], "Output string as expected"); } [TestCase(@"{""spec_version"": 1, ""version"" : ""1.01""}", false)] diff --git a/Tests/NetKAN/Model/MetadataTests.cs b/Tests/NetKAN/Model/MetadataTests.cs index 2b6fd35d68..f116d71264 100644 --- a/Tests/NetKAN/Model/MetadataTests.cs +++ b/Tests/NetKAN/Model/MetadataTests.cs @@ -71,7 +71,7 @@ public void Merge_MismatchedSizeOrHash_Throws(string[] moduleJsons) // Act / Assert var exception = Assert.Throws(() => Metadata.Merge(modules)); - StringAssert.Contains("does not match download from", exception.Message); + StringAssert.Contains("does not match download from", exception?.Message); } [Test, diff --git a/Tests/NetKAN/NetkanOverride.cs b/Tests/NetKAN/NetkanOverride.cs index 96fb32a0b7..0f7992e647 100644 --- a/Tests/NetKAN/NetkanOverride.cs +++ b/Tests/NetKAN/NetkanOverride.cs @@ -1,6 +1,8 @@ using System.Linq; + using Newtonsoft.Json.Linq; using NUnit.Framework; + using Tests.Data; using CKAN.NetKAN.Model; using CKAN.NetKAN.Transformers; @@ -10,7 +12,7 @@ namespace Tests.NetKAN [TestFixture] public class NetkanOverride { - private JObject such_metadata; + private JObject? such_metadata; private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [SetUp] @@ -27,7 +29,7 @@ public void ExactOverride() // Add our override and processs. JObject new_metadata = ProcessOverrides( - such_metadata, + such_metadata!, @"[{ ""version"" : ""1.01"", ""override"" : { @@ -35,7 +37,7 @@ public void ExactOverride() } }]"); - Assert.AreEqual("doge",new_metadata["author"].ToString(),"Override processed"); + Assert.AreEqual("doge", new_metadata!["author"]?.ToString(), "Override processed"); // Make sure our original metadata didn't change. OriginalAuthorUnchanged(); @@ -45,7 +47,7 @@ public void ExactOverride() public void UntriggeredOverride() { JObject new_metadata = ProcessOverrides( - such_metadata, + such_metadata!, @"[{ ""version"" : ""1.02"", ""override"" : { @@ -53,7 +55,7 @@ public void UntriggeredOverride() } }]"); - Assert.AreEqual("pjf", new_metadata["author"].ToString(), "Untrigged override changes nothing"); + Assert.AreEqual("pjf", new_metadata["author"]?.ToString(), "Untrigged override changes nothing"); } [Test] @@ -96,9 +98,9 @@ public void UntriggeredOverride() public void RangedOverride(string label, string expected_author, string override_json) { JObject new_metadata = ProcessOverrides( - such_metadata, override_json); + such_metadata!, override_json); - Assert.AreEqual(expected_author, new_metadata["author"].ToString(), label); + Assert.AreEqual(expected_author, new_metadata["author"]?.ToString(), label); OriginalAuthorUnchanged(); } @@ -106,11 +108,11 @@ public void RangedOverride(string label, string expected_author, string override [Test] public void DeleteOverride() { - Assert.IsTrue(such_metadata.TryGetValue("abstract", out _)); - Assert.IsTrue(such_metadata.TryGetValue("author", out _)); + Assert.IsTrue(such_metadata?.TryGetValue("abstract", out _)); + Assert.IsTrue(such_metadata?.TryGetValue("author", out _)); JObject new_metadata = ProcessOverrides( - such_metadata, + such_metadata!, @"[{ ""version"" : ""1.01"", ""delete"" : [ ""abstract"", ""author"" ] @@ -118,14 +120,14 @@ public void DeleteOverride() Assert.IsFalse(new_metadata.TryGetValue("abstract", out _)); - Assert.IsFalse(new_metadata.TryGetValue("author", out _)); + Assert.IsFalse(new_metadata.TryGetValue("author", out _)); } [Test] public void LaterOverridesOverrideEarlierOverrides() { var metadata = such_metadata; - metadata["x_netkan_override"] = JArray.Parse(@"[ + metadata!["x_netkan_override"] = JArray.Parse(@"[ { ""version"": ""1.01"", ""before"": ""$all"", @@ -148,7 +150,7 @@ public void LaterOverridesOverrideEarlierOverrides() var transformedMetadata1 = earlyTransformer.Transform(new Metadata(metadata), opts).First().Json(); var transformedMetadata2 = lateTransformer.Transform(new Metadata(transformedMetadata1), opts).First(); - Assert.AreEqual((string)transformedMetadata2.Json()["name"], "LATE"); + Assert.AreEqual((string?)transformedMetadata2.Json()["name"], "LATE"); } /// @@ -156,7 +158,7 @@ public void LaterOverridesOverrideEarlierOverrides() /// private void OriginalAuthorUnchanged() { - Assert.AreEqual("pjf", such_metadata["author"].ToString(), "Sanity check"); + Assert.AreEqual("pjf", such_metadata?["author"]?.ToString(), "Sanity check"); } /// @@ -165,8 +167,8 @@ private void OriginalAuthorUnchanged() private JObject ProcessOverrides(JObject metadata) { var transformer = new VersionedOverrideTransformer( - before: new string[] { null }, - after: new string[] { null } + before: new string?[] { null }, + after: new string?[] { null } ); return transformer.Transform(new Metadata(metadata), opts).First().Json(); diff --git a/Tests/NetKAN/SDMod.cs b/Tests/NetKAN/SDMod.cs index efa384efc2..53f58e0fa2 100644 --- a/Tests/NetKAN/SDMod.cs +++ b/Tests/NetKAN/SDMod.cs @@ -21,7 +21,7 @@ public void SDHome() public void SD_Version_Select_214() { var mod = SpacedockMod.FromJson(TestData.KS_CustomAsteroids_string()); - Assert.AreEqual(711, mod.Latest().id, "GH #214 - Select default_version_id"); + Assert.AreEqual(711, mod?.Latest().id, "GH #214 - Select default_version_id"); } [Test] @@ -30,12 +30,12 @@ public void SD_Version_Select_214() [TestCase("/mod/42/Example With Spaces/download/1.23", ExpectedResult = "https://spacedock.info/mod/42/Example%20With%20Spaces/download/1.23")] [TestCase("/mod/79/Salyut%20Stations%20%26%20Soyuz%20Ferries/download/0.93", ExpectedResult = "https://spacedock.info/mod/79/Salyut%20Stations%20%26%20Soyuz%20Ferries/download/0.93")] // GH #816: Ensure URLs with & are encoded correctly. - public string SD_URL_encode_816(string path) + public string? SD_URL_encode_816(string path) { return SpacedockMod.FromJson(string.Format( @"{{""name"":""Mod"",""id"":69420,""game"":""Kerbal Space Program"",""game_id"":3102,""short_description"":""A mod"",""description"":""A mod"",""downloads"":0,""followers"":0,""author"":""linuxgurugamer"",""default_version_id"":1,""shared_authors"":[],""background"":null,""bg_offset_y"":null,""license"":""MIT"",""website"":null,""donations"":null,""source_code"":null,""url"":""/mod/69420/Mod"",""versions"":[{{""friendly_version"":""1"",""game_version"":""1.12.2"",""id"":1,""created"":""2021-07-16T20:46:12.309009+00:00"",""download_path"":""{0}"",""changelog"":"""",""downloads"":0}}]}}", path - )).versions[0].download_path.OriginalString; + ))?.versions?[0].download_path?.OriginalString; } [Test] diff --git a/Tests/NetKAN/Services/FileServiceTests.cs b/Tests/NetKAN/Services/FileServiceTests.cs index 8adee3a5e4..ffe87a43e4 100644 --- a/Tests/NetKAN/Services/FileServiceTests.cs +++ b/Tests/NetKAN/Services/FileServiceTests.cs @@ -1,8 +1,10 @@ using System; using System.IO; + +using NUnit.Framework; + using CKAN; using CKAN.NetKAN.Services; -using NUnit.Framework; using Tests.Data; namespace Tests.NetKAN.Services @@ -23,16 +25,19 @@ public void TestFixtureSetup() [OneTimeTearDown] public void TestFixtureTearDown() { - _cache.Dispose(); + _cache?.Dispose(); _cache = null; - Directory.Delete(_cachePath, true); + if (_cachePath != null) + { + Directory.Delete(_cachePath, true); + } } [Test] public void GetsFileSizeCorrectly() { // Arrange - var sut = new FileService(_cache); + var sut = new FileService(_cache!); // Act var result = sut.GetSizeBytes(TestData.DogeCoinFlagZip()); @@ -47,7 +52,7 @@ public void GetsFileSizeCorrectly() public void GetsFileHashSha1Correctly() { // Arrange - var sut = new FileService(_cache); + var sut = new FileService(_cache!); // Act var result = sut.GetFileHashSha1(TestData.DogeCoinFlagZip()); @@ -62,7 +67,7 @@ public void GetsFileHashSha1Correctly() public void GetsFileHashSha256Correctly() { // Arrange - var sut = new FileService(_cache); + var sut = new FileService(_cache!); // Act var result = sut.GetFileHashSha256(TestData.DogeCoinFlagZip()); @@ -77,7 +82,7 @@ public void GetsFileHashSha256Correctly() public void GetsAsciiMimeCorrectly() { // Arrange - var sut = new FileService(_cache); + var sut = new FileService(_cache!); // Act var result = sut.GetMimetype(TestData.DataDir("FileIdentifier/test_ascii.txt")); @@ -92,7 +97,7 @@ public void GetsAsciiMimeCorrectly() public void GetsGzipMimeCorrectly() { // Arrange - var sut = new FileService(_cache); + var sut = new FileService(_cache!); // Act var result = sut.GetMimetype(TestData.DataDir("FileIdentifier/test_gzip.gz")); @@ -107,7 +112,7 @@ public void GetsGzipMimeCorrectly() public void GetsTarMimeCorrectly() { // Arrange - var sut = new FileService(_cache); + var sut = new FileService(_cache!); // Act var result = sut.GetMimetype(TestData.DataDir("FileIdentifier/test_tar.tar")); @@ -122,7 +127,7 @@ public void GetsTarMimeCorrectly() public void GetsTarGzMimeCorrectly() { // Arrange - var sut = new FileService(_cache); + var sut = new FileService(_cache!); // Act var result = sut.GetMimetype(TestData.DataDir("FileIdentifier/test_targz.tar.gz")); @@ -137,7 +142,7 @@ public void GetsTarGzMimeCorrectly() public void GetsZipMimeCorrectly() { // Arrange - var sut = new FileService(_cache); + var sut = new FileService(_cache!); // Act var result = sut.GetMimetype(TestData.DogeCoinFlagZip()); @@ -152,7 +157,7 @@ public void GetsZipMimeCorrectly() public void GetsUnknownMimeCorrectly() { // Arrange - var sut = new FileService(_cache); + var sut = new FileService(_cache!); string random_bin = TestData.DataDir("FileIdentifier/random.bin"); Assert.IsTrue(File.Exists(random_bin)); @@ -165,7 +170,7 @@ public void GetsUnknownMimeCorrectly() ); } - private string _cachePath; - private NetFileCache _cache; + private string? _cachePath; + private NetFileCache? _cache; } } diff --git a/Tests/NetKAN/Services/ModuleServiceTests.cs b/Tests/NetKAN/Services/ModuleServiceTests.cs index ec34658e26..1db973a6ee 100644 --- a/Tests/NetKAN/Services/ModuleServiceTests.cs +++ b/Tests/NetKAN/Services/ModuleServiceTests.cs @@ -19,7 +19,7 @@ public void HasInstallableFilesReturnsFalseWhenNoInstallableFiles() // Arrange var zip = TestData.DogeCoinFlagZip(); var json = JObject.Parse(TestData.DogeCoinFlag_101()); - json["install"][0]["file"] = "DOES_NOT_EXIST"; + json["install"]![0]!["file"] = "DOES_NOT_EXIST"; var sut = new ModuleService(new KerbalSpaceProgram()); @@ -65,7 +65,7 @@ public void GetsInternalCkanCorrectly() Assert.That(result, Is.Not.Null, "ModuleService should get an internal CKAN file." ); - Assert.That((string)result["identifier"], Is.EqualTo("DogeCoinFlag"), + Assert.That((string?)result?["identifier"], Is.EqualTo("DogeCoinFlag"), "ModuleService should get correct data for the internal CKAN file." ); } @@ -90,16 +90,16 @@ public void GetsInternalAvcCorrectly() Assert.That(result, Is.Not.Null, "ModuleService should get an internal AVC file." ); - Assert.That(result.version, Is.EqualTo(new ModuleVersion("1.1.0.0")), + Assert.That(result?.version, Is.EqualTo(new ModuleVersion("1.1.0.0")), "ModuleService should get correct version from the internal AVC file." ); - Assert.That(result.ksp_version, Is.EqualTo(GameVersion.Parse("0.24.2")), + Assert.That(result?.ksp_version, Is.EqualTo(GameVersion.Parse("0.24.2")), "ModuleService should get correct ksp_version from the internal AVC file." ); - Assert.That(result.ksp_version_min, Is.EqualTo(GameVersion.Parse("0.24.0")), + Assert.That(result?.ksp_version_min, Is.EqualTo(GameVersion.Parse("0.24.0")), "ModuleService should get correct ksp_version_min from the internal AVC file." ); - Assert.That(result.ksp_version_max, Is.EqualTo(GameVersion.Parse("0.24.2")), + Assert.That(result?.ksp_version_max, Is.EqualTo(GameVersion.Parse("0.24.2")), "ModuleService should get correct ksp_version_max from the internal AVC file." ); } diff --git a/Tests/NetKAN/Sources/Github/GithubApiTests.cs b/Tests/NetKAN/Sources/Github/GithubApiTests.cs index bc1c4663b1..57d033bbaa 100644 --- a/Tests/NetKAN/Sources/Github/GithubApiTests.cs +++ b/Tests/NetKAN/Sources/Github/GithubApiTests.cs @@ -17,8 +17,8 @@ public sealed class GithubApiTests // with GitHub, these sometimes cause test failures because github will throw random // 403s. (Hence we disable them in CI with --where="Category!=FlakyNetwork") - private string _cachePath; - private NetFileCache _cache; + private string? _cachePath; + private NetFileCache? _cache; [OneTimeSetUp] public void TestFixtureSetup() @@ -33,9 +33,12 @@ public void TestFixtureSetup() [OneTimeTearDown] public void TestFixtureTearDown() { - _cache.Dispose(); + _cache?.Dispose(); _cache = null; - Directory.Delete(_cachePath, recursive: true); + if (_cachePath != null) + { + Directory.Delete(_cachePath, recursive: true); + } } [Test] @@ -44,16 +47,16 @@ public void TestFixtureTearDown() public void GetsLatestReleaseCorrectly() { // Arrange - var sut = new GithubApi(new CachingHttpService(_cache)); + var sut = new GithubApi(new CachingHttpService(_cache!)); // Act var githubRelease = sut.GetLatestRelease(new GithubRef("#/ckan/github/KSP-CKAN/Test", false, false)); // Assert - Assert.IsNotNull(githubRelease.Author); - Assert.IsNotNull(githubRelease.Tag); - Assert.IsNotNull(githubRelease.Assets.FirstOrDefault()); - Assert.IsNotNull(githubRelease.Assets.FirstOrDefault()?.Download); + Assert.IsNotNull(githubRelease?.Author); + Assert.IsNotNull(githubRelease?.Tag); + Assert.IsNotNull(githubRelease?.Assets?.FirstOrDefault()); + Assert.IsNotNull(githubRelease?.Assets?.FirstOrDefault()?.Download); } } } diff --git a/Tests/NetKAN/Sources/Jenkins/JenkinsApiTests.cs b/Tests/NetKAN/Sources/Jenkins/JenkinsApiTests.cs index 7bc5ca0467..01011653f0 100644 --- a/Tests/NetKAN/Sources/Jenkins/JenkinsApiTests.cs +++ b/Tests/NetKAN/Sources/Jenkins/JenkinsApiTests.cs @@ -23,9 +23,12 @@ public void TestFixtureSetup() [OneTimeTearDown] public void TestFixtureTearDown() { - _cache.Dispose(); + _cache?.Dispose(); _cache = null; - Directory.Delete(_cachePath, recursive: true); + if (_cachePath != null) + { + Directory.Delete(_cachePath, recursive: true); + } } @@ -35,20 +38,19 @@ public void TestFixtureTearDown() public void GetLatestBuild_ModuleManager_Works() { // Arrange - IJenkinsApi sut = new JenkinsApi(new CachingHttpService(_cache)); + IJenkinsApi sut = new JenkinsApi(new CachingHttpService(_cache!)); // Act - JenkinsBuild build = sut.GetLatestBuild( + var build = sut.GetLatestBuild( new JenkinsRef("#/ckan/jenkins/https://ksp.sarbian.com/jenkins/job/ModuleManager/"), - new JenkinsOptions() - ); + new JenkinsOptions()); // Assert - Assert.IsNotNull(build.Url); - Assert.IsNotNull(build.Artifacts); + Assert.IsNotNull(build?.Url); + Assert.IsNotNull(build?.Artifacts); } - private string _cachePath; - private NetFileCache _cache; + private string? _cachePath; + private NetFileCache? _cache; } } diff --git a/Tests/NetKAN/Sources/Spacedock/SpacedockApiTests.cs b/Tests/NetKAN/Sources/Spacedock/SpacedockApiTests.cs index 1f8c478b61..6eec058bf2 100644 --- a/Tests/NetKAN/Sources/Spacedock/SpacedockApiTests.cs +++ b/Tests/NetKAN/Sources/Spacedock/SpacedockApiTests.cs @@ -14,8 +14,8 @@ namespace Tests.NetKAN.Sources.Spacedock [Category("Online")] public sealed class SpacedockApiTests { - private string _cachePath; - private NetFileCache _cache; + private string? _cachePath; + private NetFileCache? _cache; [OneTimeSetUp] public void TestFixtureSetup() @@ -30,9 +30,12 @@ public void TestFixtureSetup() [OneTimeTearDown] public void TestFixtureTearDown() { - _cache.Dispose(); + _cache?.Dispose(); _cache = null; - Directory.Delete(_cachePath, recursive: true); + if (_cachePath != null) + { + Directory.Delete(_cachePath, recursive: true); + } } [Test] @@ -40,27 +43,27 @@ public void TestFixtureTearDown() public void GetsModCorrectly() { // Arrange - var sut = new SpacedockApi(new CachingHttpService(_cache)); + var sut = new SpacedockApi(new CachingHttpService(_cache!)); // Act var result = sut.GetMod(20); // PlaneMode // Assert - var latestVersion = result.Latest(); + var latestVersion = result?.Latest(); - Assert.That(result.id, Is.EqualTo(20)); - Assert.That(result.author, Is.Not.Null); - Assert.That(result.background, Is.Not.Null); - Assert.That(result.license, Is.Not.Null); - Assert.That(result.name, Is.Not.Null); - Assert.That(result.short_description, Is.Not.Null); - Assert.That(result.source_code, Is.Not.Null); - Assert.That(result.website, Is.Not.Null); - Assert.That(result.versions.Length, Is.GreaterThan(0)); - Assert.That(latestVersion.changelog, Is.Not.Null); - Assert.That(latestVersion.download_path, Is.Not.Null); - Assert.That(latestVersion.friendly_version, Is.Not.Null); - Assert.That(latestVersion.KSP_version, Is.Not.Null); + Assert.That(result?.id, Is.EqualTo(20)); + Assert.That(result?.author, Is.Not.Null); + Assert.That(result?.background, Is.Not.Null); + Assert.That(result?.license, Is.Not.Null); + Assert.That(result?.name, Is.Not.Null); + Assert.That(result?.short_description, Is.Not.Null); + Assert.That(result?.source_code, Is.Not.Null); + Assert.That(result?.website, Is.Not.Null); + Assert.That(result?.versions?.Length, Is.GreaterThan(0)); + Assert.That(latestVersion?.changelog, Is.Not.Null); + Assert.That(latestVersion?.download_path, Is.Not.Null); + Assert.That(latestVersion?.friendly_version, Is.Not.Null); + Assert.That(latestVersion?.KSP_version, Is.Not.Null); } [Test] @@ -68,7 +71,7 @@ public void GetsModCorrectly() public void ThrowsWhenModMissing() { // Arrange - var sut = new SpacedockApi(new CachingHttpService(_cache)); + var sut = new SpacedockApi(new CachingHttpService(_cache!)); // Act TestDelegate act = () => sut.GetMod(-1); diff --git a/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs b/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs index 4b57309123..1368c7b81f 100644 --- a/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs +++ b/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs @@ -1,8 +1,10 @@ using System; using System.Linq; + using NUnit.Framework; using Newtonsoft.Json.Linq; using Moq; + using CKAN.NetKAN.Services; using CKAN.NetKAN.Model; using CKAN.NetKAN.Transformers; @@ -45,14 +47,14 @@ public void Transform_SimpleVersionFile_PropertiesSet(string remoteUrl, string v .Returns(remoteAvc); // Act - Metadata m = null; + Metadata? m = null; Assert.DoesNotThrow(() => m = TryKref(mHttp.Object, $"#/ckan/ksp-avc/{remoteUrl}")); // Assert - var json = m.Json(); - Assert.AreEqual(version, (string)json["version"]); - Assert.AreEqual(GameVersion, (string)json["ksp_version"]); - Assert.AreEqual(download, (string)json["download"]); + var json = m?.Json(); + Assert.AreEqual(version, (string?)json?["version"]); + Assert.AreEqual(GameVersion, (string?)json?["ksp_version"]); + Assert.AreEqual(download, (string?)json?["download"]); } private Metadata TryKref(IHttpService http, string kref) diff --git a/Tests/NetKAN/Transformers/AvcTransformerTests.cs b/Tests/NetKAN/Transformers/AvcTransformerTests.cs index fadf4e95bd..b221b9c005 100644 --- a/Tests/NetKAN/Transformers/AvcTransformerTests.cs +++ b/Tests/NetKAN/Transformers/AvcTransformerTests.cs @@ -55,10 +55,10 @@ public void AddsMissingVersionInfo() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["version"], Is.EqualTo("1.0.0"), + Assert.That((string?)transformedJson["version"], Is.EqualTo("1.0.0"), "AvcTransformer should add the version specified in the AVC version file." ); - Assert.That((string)transformedJson["ksp_version"], Is.EqualTo("1.0.4"), + Assert.That((string?)transformedJson["ksp_version"], Is.EqualTo("1.0.4"), "AvcTransformer should add the game version specified in the AVC version file." ); } @@ -98,10 +98,10 @@ public void PreferentiallyAddsRangedGameVersionInfo() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["ksp_version_min"], Is.EqualTo("0.90"), + Assert.That((string?)transformedJson["ksp_version_min"], Is.EqualTo("0.90"), "AvcTransformer should add the KSP min version specified in the AVC version file." ); - Assert.That((string)transformedJson["ksp_version_max"], Is.EqualTo("1.0.3"), + Assert.That((string?)transformedJson["ksp_version_max"], Is.EqualTo("1.0.3"), "AvcTransformer should add the KSP min version specified in the AVC version file." ); Assert.That(transformedJson["ksp_version"], Is.Null, @@ -247,15 +247,15 @@ public void CorrectlyCalculatesGameVersionInfo( var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["ksp_version"], Is.EqualTo(expectedKsp), + Assert.That((string?)transformedJson["ksp_version"], Is.EqualTo(expectedKsp), "AvcTransformer should calculate ksp_version correctly" ); - Assert.That((string)transformedJson["ksp_version_min"], Is.EqualTo(expectedKspMin), + Assert.That((string?)transformedJson["ksp_version_min"], Is.EqualTo(expectedKspMin), "AvcTransformer should calculate ksp_version_min correctly" ); - Assert.That((string)transformedJson["ksp_version_max"], Is.EqualTo(expectedKspMax), + Assert.That((string?)transformedJson["ksp_version_max"], Is.EqualTo(expectedKspMax), "AvcTransformer should calculate ksp_version_max correctly" ); } @@ -291,7 +291,7 @@ public void DoesNotOverrideExistingVersionInfo() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["version"], Is.EqualTo("9001"), + Assert.That((string?)transformedJson["version"], Is.EqualTo("9001"), "AvcTransformer should not override an existing version." ); } @@ -328,7 +328,7 @@ public void Transform_TrustVersionFileTrue_OverridesExistingInfo() JObject transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["version"], Is.EqualTo("1.2.3"), + Assert.That((string?)transformedJson["version"], Is.EqualTo("1.2.3"), "AvcTransformer should override an existing version when x_netkan_trust_version_file is true." ); } diff --git a/Tests/NetKAN/Transformers/CurseTransformerTests.cs b/Tests/NetKAN/Transformers/CurseTransformerTests.cs index 8bee722a40..04ea29dbf5 100644 --- a/Tests/NetKAN/Transformers/CurseTransformerTests.cs +++ b/Tests/NetKAN/Transformers/CurseTransformerTests.cs @@ -35,9 +35,9 @@ public void DoesNotReplaceGameVersionProperties() var transformedJson = result.Json(); // Assert - Assert.AreEqual(null, (string)transformedJson["ksp_version"]); - Assert.AreEqual(null, (string)transformedJson["ksp_version_max"]); - Assert.AreEqual("0.23.5", (string)transformedJson["ksp_version_min"]); + Assert.AreEqual(null, (string?)transformedJson["ksp_version"]); + Assert.AreEqual(null, (string?)transformedJson["ksp_version_max"]); + Assert.AreEqual("0.23.5", (string?)transformedJson["ksp_version_min"]); } private static CurseMod MakeTestMod() diff --git a/Tests/NetKAN/Transformers/DownloadAttributeTransformerTests.cs b/Tests/NetKAN/Transformers/DownloadAttributeTransformerTests.cs index 066958148d..be2c226874 100644 --- a/Tests/NetKAN/Transformers/DownloadAttributeTransformerTests.cs +++ b/Tests/NetKAN/Transformers/DownloadAttributeTransformerTests.cs @@ -52,16 +52,16 @@ public void AddsDownloadAttributes() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["download_hash"]["sha1"], Is.EqualTo(downloadHashSha1), + Assert.That((string?)transformedJson["download_hash"]?["sha1"], Is.EqualTo(downloadHashSha1), "DownloadAttributeTransformer should add a 'sha1' property withing 'download_hash' equal to the sha1 of the file." ); - Assert.That((string)transformedJson["download_hash"]["sha256"], Is.EqualTo(downloadHashSha256), + Assert.That((string?)transformedJson["download_hash"]?["sha256"], Is.EqualTo(downloadHashSha256), "DownloadAttributeTransformer should add a 'sha256' property withing 'download_hash' equal to the sha256 of the file." ); - Assert.That((long)transformedJson["download_size"], Is.EqualTo(downloadSize), + Assert.That((long?)transformedJson["download_size"], Is.EqualTo(downloadSize), "DownloadAttributeTransformer should add a download_size property equal to the size of the file in bytes." ); - Assert.That((string)transformedJson["download_content_type"], Is.EqualTo(downloadMimetype), + Assert.That((string?)transformedJson["download_content_type"], Is.EqualTo(downloadMimetype), "DownloadAttributeTransformer should add a download_content_type property equal to the Mimetype of the file." ); } @@ -74,7 +74,7 @@ public void DoesNothingIfFileDoesNotExist() var mFileService = new Mock(); mHttp.Setup(i => i.DownloadModule(It.IsAny())) - .Returns((string)null); + .Returns((string?)null); var sut = new DownloadAttributeTransformer(mHttp.Object, mFileService.Object); diff --git a/Tests/NetKAN/Transformers/EpochTransformerTests.cs b/Tests/NetKAN/Transformers/EpochTransformerTests.cs index 55df664a28..3d41aa48ab 100644 --- a/Tests/NetKAN/Transformers/EpochTransformerTests.cs +++ b/Tests/NetKAN/Transformers/EpochTransformerTests.cs @@ -46,7 +46,7 @@ public void Transform_WithHighVersionParam_MatchesExpected(string version, strin var transformedJson = result.Json(); // Assert - Assert.AreEqual(expected, (string)transformedJson["version"]); + Assert.AreEqual(expected, (string?)transformedJson["version"]); } } } diff --git a/Tests/NetKAN/Transformers/GeneratedByTransformerTests.cs b/Tests/NetKAN/Transformers/GeneratedByTransformerTests.cs index 3d22301d53..21ff87f2b7 100644 --- a/Tests/NetKAN/Transformers/GeneratedByTransformerTests.cs +++ b/Tests/NetKAN/Transformers/GeneratedByTransformerTests.cs @@ -24,7 +24,7 @@ public void AddsGeneratedByProperty() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["x_generated_by"], Does.Contain("netkan"), + Assert.That((string?)transformedJson["x_generated_by"], Does.Contain("netkan"), "GeneratedByTransformer should add an x_generated_by property containing the string 'netkan'" ); } diff --git a/Tests/NetKAN/Transformers/GithubTransformerTests.cs b/Tests/NetKAN/Transformers/GithubTransformerTests.cs index 9c7b367707..225b16622e 100644 --- a/Tests/NetKAN/Transformers/GithubTransformerTests.cs +++ b/Tests/NetKAN/Transformers/GithubTransformerTests.cs @@ -16,7 +16,8 @@ public sealed class GithubTransformerTests { private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); - private Mock apiMockUp; + private Mock? apiMockUp; + [OneTimeSetUp] public void setupApiMockup() { @@ -107,7 +108,7 @@ public void CalculatesRepositoryUrlCorrectly() json["$kref"] = "#/ckan/github/ExampleAccount/ExampleProject"; json["identifier"] = "ExampleProject1"; - var sut = new GithubTransformer(apiMockUp.Object, false); + var sut = new GithubTransformer(apiMockUp!.Object, false); // Act var result = sut.Transform(new Metadata(json), opts).First(); @@ -116,7 +117,7 @@ public void CalculatesRepositoryUrlCorrectly() // Assert Assert.AreEqual( "https://github.com/ExampleAccount/ExampleProject", - (string)transformedJson["resources"]["repository"] + (string?)transformedJson["resources"]?["repository"] ); } @@ -173,7 +174,7 @@ public void Transform_DownloadURLWithEncodedCharacter_DontDoubleEncode() // Assert Assert.AreEqual( "https://github.com/jrodrigv/DestructionEffects/releases/download/v1.8%2C0/DestructionEffects.1.8.0_0412018.zip", - (string)transformedJson["download"] + (string?)transformedJson["download"] ); } @@ -186,7 +187,7 @@ public void Transform_MultipleReleases_TransformsAll() json["$kref"] = "#/ckan/github/ExampleAccount/ExampleProject"; json["identifier"] = "ExampleProject3"; - var sut = new GithubTransformer(apiMockUp.Object, false); + var sut = new GithubTransformer(apiMockUp!.Object, false); // Act var results = sut.Transform( @@ -198,20 +199,20 @@ public void Transform_MultipleReleases_TransformsAll() // Assert Assert.AreEqual( "http://github.example/download/1.0", - (string)transformedJsons[0]["download"] + (string?)transformedJsons[0]["download"] ); Assert.AreEqual( "http://github.example/download/1.1", - (string)transformedJsons[1]["download"] + (string?)transformedJsons[1]["download"] ); Assert.AreEqual( "1.0", - (string)transformedJsons[0]["x_netkan_version_pieces"]["tag"] + (string?)transformedJsons[0]["x_netkan_version_pieces"]?["tag"] ); Assert.AreEqual( "1.1", - (string)transformedJsons[1]["x_netkan_version_pieces"]["tag"] + (string?)transformedJsons[1]["x_netkan_version_pieces"]?["tag"] ); } @@ -224,7 +225,7 @@ public void Transform_MultipleAssets_TransformsAll() json["$kref"] = "#/ckan/github/ExampleAccount/ExampleProject/version_from_asset/^.+_(?.+)\\.zip$"; json["identifier"] = "ExampleProject4"; - var sut = new GithubTransformer(apiMockUp.Object, false); + var sut = new GithubTransformer(apiMockUp!.Object, false); // Act var results = sut.Transform( @@ -236,20 +237,20 @@ public void Transform_MultipleAssets_TransformsAll() // Assert Assert.AreEqual( "http://github.example/download/1.2/ExampleProject_1.2-1.8.1.zip", - (string)transformedJsons[0]["download"] + (string?)transformedJsons[0]["download"] ); Assert.AreEqual( "http://github.example/download/1.2/ExampleProject_1.2-1.9.1.zip", - (string)transformedJsons[1]["download"] + (string?)transformedJsons[1]["download"] ); Assert.AreEqual( "1.2-1.8.1", - (string)transformedJsons[0]["version"] + (string?)transformedJsons[0]["version"] ); Assert.AreEqual( "1.2-1.9.1", - (string)transformedJsons[1]["version"] + (string?)transformedJsons[1]["version"] ); } @@ -262,7 +263,7 @@ public void Transform_SkipReleases_SkipsCorrectly() json["$kref"] = "#/ckan/github/ExampleAccount/ExampleProject"; json["identifier"] = "ExampleProject5"; - var sut = new GithubTransformer(apiMockUp.Object, false); + var sut = new GithubTransformer(apiMockUp!.Object, false); // Act var results = sut.Transform( @@ -273,11 +274,11 @@ public void Transform_SkipReleases_SkipsCorrectly() // Assert Assert.AreEqual( "1.1", - results[0].Version.ToString() + results[0]?.Version?.ToString() ); Assert.AreEqual( "1.2", - results[1].Version.ToString() + results[1]?.Version?.ToString() ); } } diff --git a/Tests/NetKAN/Transformers/InstallSizeTransformerTests.cs b/Tests/NetKAN/Transformers/InstallSizeTransformerTests.cs index 3ea1b7a6ab..376e7dfee5 100644 --- a/Tests/NetKAN/Transformers/InstallSizeTransformerTests.cs +++ b/Tests/NetKAN/Transformers/InstallSizeTransformerTests.cs @@ -35,7 +35,7 @@ public void Transform_NormalModule_CorrectInstallSize() var transformedJson = result.Json(); // Assert - Assert.AreEqual(52291, (int)transformedJson["install_size"]); + Assert.AreEqual(52291, (int?)transformedJson["install_size"]); } private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); diff --git a/Tests/NetKAN/Transformers/InternalCkanTransformerTests.cs b/Tests/NetKAN/Transformers/InternalCkanTransformerTests.cs index 24088fc448..9c495be162 100644 --- a/Tests/NetKAN/Transformers/InternalCkanTransformerTests.cs +++ b/Tests/NetKAN/Transformers/InternalCkanTransformerTests.cs @@ -52,7 +52,7 @@ public void AddsMissingProperties() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["foo"], Is.EqualTo("bar"), + Assert.That((string?)transformedJson["foo"], Is.EqualTo("bar"), "InternalCkanTransformer should add properties from the internal ckan that don't exist on the original." ); } @@ -93,7 +93,7 @@ public void DoesNotOverrideExistingProperties() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["foo"], Is.EqualTo("baz"), + Assert.That((string?)transformedJson["foo"], Is.EqualTo("baz"), "InternalCkanTransformer should not override existing properties." ); } diff --git a/Tests/NetKAN/Transformers/MetaNetkanTransformerTests.cs b/Tests/NetKAN/Transformers/MetaNetkanTransformerTests.cs index 65641d6797..faccac90cd 100644 --- a/Tests/NetKAN/Transformers/MetaNetkanTransformerTests.cs +++ b/Tests/NetKAN/Transformers/MetaNetkanTransformerTests.cs @@ -1,8 +1,10 @@ using System; using System.Linq; + using Moq; using Newtonsoft.Json.Linq; using NUnit.Framework; + using CKAN; using CKAN.NetKAN.Model; using CKAN.NetKAN.Services; @@ -89,7 +91,7 @@ public void TargetMetadataAddsMissingProperties() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["foo"], Is.EqualTo("bar"), + Assert.That((string?)transformedJson["foo"], Is.EqualTo("bar"), "MetaNetkanTransformer add properties from target netkan that do not already exist." ); } @@ -119,7 +121,7 @@ public void TargetMetadataDoesNotOverrideExistingProperty() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["foo"], Is.EqualTo("baz"), + Assert.That((string?)transformedJson["foo"], Is.EqualTo("baz"), "MetaNetkanTransformer should not override existing properties." ); } diff --git a/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs b/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs index a348308731..631dd38ac6 100644 --- a/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs +++ b/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs @@ -59,9 +59,9 @@ public void DoesNotReplaceGameVersionProperties() JObject transformedJson = result.Json(); // Assert - Assert.AreEqual(null, (string)transformedJson["ksp_version"]); - Assert.AreEqual(null, (string)transformedJson["ksp_version_max"]); - Assert.AreEqual("0.23.5", (string)transformedJson["ksp_version_min"]); + Assert.AreEqual(null, (string?)transformedJson["ksp_version"]); + Assert.AreEqual(null, (string?)transformedJson["ksp_version_max"]); + Assert.AreEqual("0.23.5", (string?)transformedJson["ksp_version_min"]); } } diff --git a/Tests/NetKAN/Transformers/VersionEditTransformerTests.cs b/Tests/NetKAN/Transformers/VersionEditTransformerTests.cs index 7f7cc4aab6..ae65a79575 100644 --- a/Tests/NetKAN/Transformers/VersionEditTransformerTests.cs +++ b/Tests/NetKAN/Transformers/VersionEditTransformerTests.cs @@ -48,7 +48,7 @@ public void EditsCorrectlyWithString() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["version"], Is.EqualTo("1.2.3")); + Assert.That((string?)transformedJson["version"], Is.EqualTo("1.2.3")); } [Test] @@ -70,7 +70,7 @@ public void EditsCorrectlyWithOnlyFind() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["version"], Is.EqualTo("1.2.3")); + Assert.That((string?)transformedJson["version"], Is.EqualTo("1.2.3")); } [Test] @@ -93,7 +93,7 @@ public void EditsCorrectlyWithFindAndReplace() var transformedJson = result.Json(); // Assert - Assert.That((string)transformedJson["version"], Is.EqualTo("FOO-1.2.3-BAR")); + Assert.That((string?)transformedJson["version"], Is.EqualTo("FOO-1.2.3-BAR")); } [Test] diff --git a/Tests/NetKAN/Validators/DownloadArrayValidatorTests.cs b/Tests/NetKAN/Validators/DownloadArrayValidatorTests.cs index e7ccb8461e..3c3be2ca59 100644 --- a/Tests/NetKAN/Validators/DownloadArrayValidatorTests.cs +++ b/Tests/NetKAN/Validators/DownloadArrayValidatorTests.cs @@ -37,7 +37,7 @@ public void Validate_OldSpecArray_Throws() // Act / Assert var exception = Assert.Throws(() => validator.Validate(new Metadata(jobj))); - Assert.AreEqual(DownloadArrayValidator.ErrorMessage, exception.Message); + Assert.AreEqual(DownloadArrayValidator.ErrorMessage, exception?.Message); } [Test] diff --git a/Tests/NetKAN/Validators/ObeysCKANSchemaValidatorTests.cs b/Tests/NetKAN/Validators/ObeysCKANSchemaValidatorTests.cs index 386db6c2dc..2e3943f6ca 100644 --- a/Tests/NetKAN/Validators/ObeysCKANSchemaValidatorTests.cs +++ b/Tests/NetKAN/Validators/ObeysCKANSchemaValidatorTests.cs @@ -64,7 +64,10 @@ public void Validate_InstallToGameDataSlashmods_DoesNotThrow() ]"))); } - private void TryModule(string json, string removeProperty = null, string addProperty = null, JToken addPropertyValue = null) + private void TryModule(string json, + string? removeProperty = null, + string? addProperty = null, + JToken? addPropertyValue = null) { // Arrange var jObj = JObject.Parse(json); diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 0cedf0cc1c..98e4a1210e 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -17,7 +17,9 @@ true Debug;Release;NoGUI false - 7.3 + 9 + enable + true IDE1006,NU1701 net48;net7.0;net7.0-windows $(TargetFramework.Replace("-windows", "")) diff --git a/Tests/Util.cs b/Tests/Util.cs index 45424fd8de..5b72b88178 100644 --- a/Tests/Util.cs +++ b/Tests/Util.cs @@ -59,10 +59,9 @@ public static void AssertNoAsyncVoidMethods(Assembly assembly) { var messages = assembly .GetAsyncVoidMethods() - .Select(method => - string.Format("'{0}.{1}' is an async void method.", - method.DeclaringType.Name, - method.Name)) + .Select(method => string.Format("'{0}.{1}' is an async void method.", + method.DeclaringType?.Name ?? "", + method.Name)) .ToList(); Assert.False(messages.Any(), "Async void methods found!" + Environment.NewLine + string.Join(Environment.NewLine, messages)); @@ -85,7 +84,7 @@ private static IEnumerable GetLoadableTypes(this Assembly assembly) { if (assembly == null) { - throw new ArgumentNullException("assembly"); + throw new ArgumentNullException(nameof(assembly)); } try @@ -94,7 +93,7 @@ private static IEnumerable GetLoadableTypes(this Assembly assembly) } catch (ReflectionTypeLoadException e) { - return e.Types.Where(t => t != null); + return e.Types.OfType(); } }