diff --git a/Content.IntegrationTests/Content.IntegrationTests.csproj b/Content.IntegrationTests/Content.IntegrationTests.csproj index 34ef2a0290f..5f2a5b0cebb 100644 --- a/Content.IntegrationTests/Content.IntegrationTests.csproj +++ b/Content.IntegrationTests/Content.IntegrationTests.csproj @@ -24,4 +24,5 @@ + diff --git a/Content.IntegrationTests/DummyParallaxManager.cs b/Content.IntegrationTests/DummyParallaxManager.cs index 91c739fa742..2daa682673f 100644 --- a/Content.IntegrationTests/DummyParallaxManager.cs +++ b/Content.IntegrationTests/DummyParallaxManager.cs @@ -1,5 +1,3 @@ -using System; -using System.Threading.Tasks; using Content.Client.Parallax.Managers; using Content.Client.Parallax; using Robust.Shared.Maths; diff --git a/Content.IntegrationTests/GlobalUsings.cs b/Content.IntegrationTests/GlobalUsings.cs new file mode 100644 index 00000000000..8422c5c3cdc --- /dev/null +++ b/Content.IntegrationTests/GlobalUsings.cs @@ -0,0 +1,5 @@ +// Global usings for Content.IntegrationTests + +global using NUnit.Framework; +global using System; +global using System.Threading.Tasks; diff --git a/Content.IntegrationTests/PoolManager.cs b/Content.IntegrationTests/PoolManager.cs index 026ac68a0a8..09f7ffd945a 100644 --- a/Content.IntegrationTests/PoolManager.cs +++ b/Content.IntegrationTests/PoolManager.cs @@ -1,10 +1,8 @@ -using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; -using System.Threading.Tasks; using Content.Client.IoC; using Content.Client.Parallax.Managers; using Content.IntegrationTests.Tests; @@ -14,8 +12,6 @@ using Content.IntegrationTests.Tests.Networking; using Content.Server.GameTicking; using Content.Shared.CCVar; -using Microsoft.Diagnostics.Tracing.Parsers.Kernel; -using NUnit.Framework; using Robust.Client; using Robust.Server; using Robust.Shared; @@ -61,13 +57,13 @@ private static readonly (string cvar, string value)[] ServerTestCvars = // @formatter:on }; - private static int PairId; - private static object PairLock = new(); + private static int _pairId; + private static readonly object PairLock = new(); // Pair, IsBorrowed - private static Dictionary Pairs = new(); - private static bool Dead; - private static Exception PoolFailureReason; + private static readonly Dictionary Pairs = new(); + private static bool _dead; + private static Exception _poolFailureReason; private static async Task ConfigurePrototypes(RobustIntegrationTest.IntegrationInstance instance, PoolSettings settings) @@ -108,18 +104,21 @@ await instance.WaitPost(() => options.BeforeStart += () => { - IoCManager.Resolve() - .LoadExtraSystemType(); - IoCManager.Resolve().RegisterClass(); + var entSysMan = IoCManager.Resolve(); + var compFactory = IoCManager.Resolve(); + entSysMan.LoadExtraSystemType(); + compFactory.RegisterClass(); + entSysMan.LoadExtraSystemType(); + compFactory.RegisterClass(); + entSysMan.LoadExtraSystemType(); + compFactory.RegisterClass(); IoCManager.Register(); IoCManager.Register(); IoCManager.Register(); - IoCManager.Resolve() - .LoadExtraSystemType(); - IoCManager.Resolve() - .LoadExtraSystemType(); - IoCManager.Resolve().LoadExtraSystemType(); - IoCManager.Resolve().LoadExtraSystemType(); + entSysMan.LoadExtraSystemType(); + entSysMan.LoadExtraSystemType(); + entSysMan.LoadExtraSystemType(); + entSysMan.LoadExtraSystemType(); IoCManager.Resolve().GetSawmill("loc").Level = LogLevel.Error; IoCManager.Resolve() .OnValueChanged(RTCVars.FailureLogLevel, value => logHandler.FailureLevel = value, true); @@ -141,9 +140,9 @@ public static void Shutdown() List localPairs; lock (PairLock) { - if(Dead) + if (_dead) return; - Dead = true; + _dead = true; localPairs = Pairs.Keys.ToList(); } @@ -163,7 +162,7 @@ public static string DeathReport() { var borrowed = Pairs[pair]; builder.AppendLine($"Pair {pair.PairId}, Tests Run: {pair.TestHistory.Count}, Borrowed: {borrowed}"); - for (int i = 0; i < pair.TestHistory.Count; i++) + for (var i = 0; i < pair.TestHistory.Count; i++) { builder.AppendLine($"#{i}: {pair.TestHistory[i]}"); } @@ -211,10 +210,14 @@ public static string DeathReport() { ClientBeforeIoC = () => { - IoCManager.Resolve() - .LoadExtraSystemType(); - IoCManager.Resolve() - .RegisterClass(); + var entSysMan = IoCManager.Resolve(); + var compFactory = IoCManager.Resolve(); + entSysMan.LoadExtraSystemType(); + compFactory.RegisterClass(); + entSysMan.LoadExtraSystemType(); + compFactory.RegisterClass(); + entSysMan.LoadExtraSystemType(); + compFactory.RegisterClass(); IoCManager.Register(true); IoCManager.Resolve().GetSawmill("loc").Level = LogLevel.Error; IoCManager.Resolve() @@ -232,9 +235,9 @@ public static string DeathReport() private static void SetupCVars(PoolSettings poolSettings, RobustIntegrationTest.IntegrationOptions options) { - foreach (var serverTestCvar in ServerTestCvars) + foreach (var (cvar, value) in ServerTestCvars) { - options.CVarOverrides[serverTestCvar.cvar] = serverTestCvar.value; + options.CVarOverrides[cvar] = value; } if (poolSettings.DummyTicker) @@ -266,8 +269,10 @@ private static void SetupCVars(PoolSettings poolSettings, RobustIntegrationTest. /// /// See /// - public static async Task GetServerClient(PoolSettings poolSettings = null) => - await GetServerClientPair(poolSettings ?? new PoolSettings()); + public static async Task GetServerClient(PoolSettings poolSettings = null) + { + return await GetServerClientPair(poolSettings ?? new PoolSettings()); + } private static string GetDefaultTestName(TestContext testContext) { @@ -328,7 +333,7 @@ await testOut.WriteLineAsync( if (pair != null && pair.TestHistory.Count > 1) { await testOut.WriteLineAsync($"{nameof(GetServerClientPair)}: Pair {pair.PairId} Test History Start"); - for (int i = 0; i < pair.TestHistory.Count; i++) + for (var i = 0; i < pair.TestHistory.Count; i++) { await testOut.WriteLineAsync($"- Pair {pair.PairId} Test #{i}: {pair.TestHistory[i]}"); } @@ -403,6 +408,8 @@ private static async Task CleanPooledPair(PoolSettings poolSettings, Pair pair, methodWatch.Start(); await testOut.WriteLineAsync($"Recycling: {methodWatch.Elapsed.TotalMilliseconds} ms: Setting CVar "); var configManager = pair.Server.ResolveDependency(); + var entityManager = pair.Server.ResolveDependency(); + var gameTicker = entityManager.System(); await pair.Server.WaitPost(() => { configManager.SetCVar(CCVars.GameLobbyEnabled, poolSettings.InLobby); @@ -414,14 +421,14 @@ await pair.Server.WaitPost(() => pair.Client.SetConnectTarget(pair.Server); await pair.Server.WaitPost(() => { - EntitySystem.Get().RestartRound(); + gameTicker.RestartRound(); }); await pair.Client.WaitPost(() => { cNetMgr.ClientConnect(null!, 0, null!); }); } - await ReallyBeIdle(pair,11); + await ReallyBeIdle(pair, 11); await testOut.WriteLineAsync($"Recycling: {methodWatch.Elapsed.TotalMilliseconds} ms: Disconnecting client, and restarting server"); @@ -443,7 +450,7 @@ await pair.Server.WaitPost(() => serverProtoManager.RemoveString(pair.Settings.ExtraPrototypes.Trim()); }); } - if(!pair.Settings.NoClient) + if (!pair.Settings.NoClient) { var clientProtoManager = pair.Client.ResolveDependency(); await pair.Client.WaitPost(() => @@ -471,7 +478,7 @@ await pair.Client.WaitPost(() => await testOut.WriteLineAsync($"Recycling: {methodWatch.Elapsed.TotalMilliseconds} ms: Restarting server again"); await pair.Server.WaitPost(() => { - EntitySystem.Get().RestartRound(); + gameTicker.RestartRound(); }); @@ -495,17 +502,17 @@ await pair.Client.WaitPost(() => private static void DieIfPoolFailure() { - if (PoolFailureReason != null) + if (_poolFailureReason != null) { - // If the PoolFailureReason is not null, we can assume at least one test failed. + // If the _poolFailureReason is not null, we can assume at least one test failed. // So we say inconclusive so we don't add more failed tests to search through. Assert.Inconclusive(@" In a different test, the pool manager had an exception when trying to create a server/client pair. Instead of risking that the pool manager will fail at creating a server/client pairs for every single test, -we are just going to end this here to save a lot of time. This is the exception that started this:\n {0}", PoolFailureReason); +we are just going to end this here to save a lot of time. This is the exception that started this:\n {0}", _poolFailureReason); } - if (Dead) + if (_dead) { // If Pairs is null, we ran out of time, we can't assume a test failed. // So we are going to tell it all future tests are a failure. @@ -525,12 +532,12 @@ private static async Task CreateServerClientPair(PoolSettings poolSettings ServerLogHandler = serverLog, Client = client, ClientLogHandler = clientLog, - PairId = Interlocked.Increment(ref PairId) + PairId = Interlocked.Increment(ref _pairId) }; } catch (Exception ex) { - PoolFailureReason = ex; + _poolFailureReason = ex; throw; } @@ -565,6 +572,8 @@ public static async Task CreateTestMap(PairTracker pairTracker) var settings = pairTracker.Pair.Settings; var mapManager = server.ResolveDependency(); var tileDefinitionManager = server.ResolveDependency(); + var entityManager = server.ResolveDependency(); + var xformSystem = entityManager.System(); if (settings.NoServer) throw new Exception("Cannot setup test map without server"); var mapData = new TestMapData(); @@ -573,7 +582,7 @@ await server.WaitPost(() => mapData.MapId = mapManager.CreateMap(); mapData.MapUid = mapManager.GetMapEntityId(mapData.MapId); mapData.MapGrid = mapManager.CreateGrid(mapData.MapId); - mapData.GridUid = mapData.MapGrid.Owner; + mapData.GridUid = mapData.MapGrid.Owner; // Fixing this requires an engine PR. mapData.GridCoords = new EntityCoordinates(mapData.GridUid, 0, 0); var plating = tileDefinitionManager["Plating"]; var platingTile = new Tile(plating.TileId); @@ -610,11 +619,11 @@ public static async Task RunTicksSync(Pair pair, int ticks) /// How many ticks to run public static async Task ReallyBeIdle(Pair pair, int runTicks = 25) { - for (int i = 0; i < runTicks; i++) + for (var i = 0; i < runTicks; i++) { await pair.Client.WaitRunTicks(1); await pair.Server.WaitRunTicks(1); - for (int idleCycles = 0; idleCycles < 4; idleCycles++) + for (var idleCycles = 0; idleCycles < 4; idleCycles++) { await pair.Client.WaitIdleAsync(); await pair.Server.WaitIdleAsync(); @@ -809,7 +818,9 @@ public bool CanFastRecycle(PoolSettings nextSettings) // Prototype hot reload is not available outside TOOLS builds, // so we can't pool test instances that use ExtraPrototypes without TOOLS. #if TOOLS +#pragma warning disable CA1822 // Can't be marked as static b/c the other branch exists but Omnisharp can't see both. private bool NoToolsExtraPrototypes => false; +#pragma warning restore CA1822 #else private bool NoToolsExtraPrototypes => !string.IsNullOrEmpty(ExtraPrototypes); #endif diff --git a/Content.IntegrationTests/PoolManagerTestEventHandler.cs b/Content.IntegrationTests/PoolManagerTestEventHandler.cs index 1bdb1541f48..e21ba8b1754 100644 --- a/Content.IntegrationTests/PoolManagerTestEventHandler.cs +++ b/Content.IntegrationTests/PoolManagerTestEventHandler.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading.Tasks; -using NUnit.Framework; - + [assembly: Parallelizable(ParallelScope.Children)] namespace Content.IntegrationTests; diff --git a/Content.IntegrationTests/PoolTestLogHandler.cs b/Content.IntegrationTests/PoolTestLogHandler.cs index 2dcb40c6031..efa185e148c 100644 --- a/Content.IntegrationTests/PoolTestLogHandler.cs +++ b/Content.IntegrationTests/PoolTestLogHandler.cs @@ -1,6 +1,4 @@ -using System; -using System.IO; -using NUnit.Framework; +using System.IO; using Robust.Shared.Log; using Robust.Shared.Timing; using Serilog.Events; diff --git a/Content.IntegrationTests/Tests/Access/AccessReaderTest.cs b/Content.IntegrationTests/Tests/Access/AccessReaderTest.cs index 6b4df318b4f..b5074008a6e 100644 --- a/Content.IntegrationTests/Tests/Access/AccessReaderTest.cs +++ b/Content.IntegrationTests/Tests/Access/AccessReaderTest.cs @@ -1,8 +1,6 @@ using System.Collections.Generic; -using System.Threading.Tasks; using Content.Shared.Access.Components; using Content.Shared.Access.Systems; -using NUnit.Framework; using Robust.Shared.GameObjects; namespace Content.IntegrationTests.Tests.Access @@ -14,63 +12,82 @@ public sealed class AccessReaderTest [Test] public async Task TestTags() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; + var entityManager = server.ResolveDependency(); await server.WaitAssertion(() => { - var system = EntitySystem.Get(); + var system = entityManager.System(); // test empty var reader = new AccessReaderComponent(); - Assert.That(system.AreAccessTagsAllowed(new[] { "Foo" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new[] { "Bar" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new string[] { }, reader), Is.True); + Assert.Multiple(() => + { + Assert.That(system.AreAccessTagsAllowed(new[] { "Foo" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(new[] { "Bar" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(Array.Empty(), reader), Is.True); + }); // test deny reader = new AccessReaderComponent(); reader.DenyTags.Add("A"); - Assert.That(system.AreAccessTagsAllowed(new[] { "Foo" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.False); - Assert.That(system.AreAccessTagsAllowed(new[] { "A", "Foo" }, reader), Is.False); - Assert.That(system.AreAccessTagsAllowed(new string[] { }, reader), Is.True); + Assert.Multiple(() => + { + Assert.That(system.AreAccessTagsAllowed(new[] { "Foo" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.False); + Assert.That(system.AreAccessTagsAllowed(new[] { "A", "Foo" }, reader), Is.False); + Assert.That(system.AreAccessTagsAllowed(Array.Empty(), reader), Is.True); + }); // test one list reader = new AccessReaderComponent(); reader.AccessLists.Add(new HashSet { "A" }); - Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new[] { "B" }, reader), Is.False); - Assert.That(system.AreAccessTagsAllowed(new[] { "A", "B" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new string[] { }, reader), Is.False); + Assert.Multiple(() => + { + Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(new[] { "B" }, reader), Is.False); + Assert.That(system.AreAccessTagsAllowed(new[] { "A", "B" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(Array.Empty(), reader), Is.False); + }); // test one list - two items reader = new AccessReaderComponent(); reader.AccessLists.Add(new HashSet { "A", "B" }); - Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.False); - Assert.That(system.AreAccessTagsAllowed(new[] { "B" }, reader), Is.False); - Assert.That(system.AreAccessTagsAllowed(new[] { "A", "B" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new string[] { }, reader), Is.False); + Assert.Multiple(() => + { + Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.False); + Assert.That(system.AreAccessTagsAllowed(new[] { "B" }, reader), Is.False); + Assert.That(system.AreAccessTagsAllowed(new[] { "A", "B" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(Array.Empty(), reader), Is.False); + }); // test two list reader = new AccessReaderComponent(); reader.AccessLists.Add(new HashSet { "A" }); reader.AccessLists.Add(new HashSet { "B", "C" }); - Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new[] { "B" }, reader), Is.False); - Assert.That(system.AreAccessTagsAllowed(new[] { "A", "B" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new[] { "C", "B" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new[] { "C", "B", "A" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new string[] { }, reader), Is.False); + Assert.Multiple(() => + { + Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(new[] { "B" }, reader), Is.False); + Assert.That(system.AreAccessTagsAllowed(new[] { "A", "B" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(new[] { "C", "B" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(new[] { "C", "B", "A" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(Array.Empty(), reader), Is.False); + }); // test deny list reader = new AccessReaderComponent(); reader.AccessLists.Add(new HashSet { "A" }); reader.DenyTags.Add("B"); - Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.True); - Assert.That(system.AreAccessTagsAllowed(new[] { "B" }, reader), Is.False); - Assert.That(system.AreAccessTagsAllowed(new[] { "A", "B" }, reader), Is.False); - Assert.That(system.AreAccessTagsAllowed(new string[] { }, reader), Is.False); + Assert.Multiple(() => + { + Assert.That(system.AreAccessTagsAllowed(new[] { "A" }, reader), Is.True); + Assert.That(system.AreAccessTagsAllowed(new[] { "B" }, reader), Is.False); + Assert.That(system.AreAccessTagsAllowed(new[] { "A", "B" }, reader), Is.False); + Assert.That(system.AreAccessTagsAllowed(Array.Empty(), reader), Is.False); + }); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Administration/Logs/AddTests.cs b/Content.IntegrationTests/Tests/Administration/Logs/AddTests.cs index 59322d9fc19..42366824017 100644 --- a/Content.IntegrationTests/Tests/Administration/Logs/AddTests.cs +++ b/Content.IntegrationTests/Tests/Administration/Logs/AddTests.cs @@ -1,7 +1,5 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Content.Server.Administration.Logs; using Content.Server.Database; using Content.Server.GameTicking; @@ -9,7 +7,6 @@ using Content.Shared.Administration.Logs; using Content.Shared.CCVar; using Content.Shared.Database; -using NUnit.Framework; using Robust.Server.Player; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; @@ -24,7 +21,7 @@ public sealed class AddTests [Test] public async Task AddAndGetSingleLog() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); @@ -71,7 +68,7 @@ await PoolManager.WaitUntil(server, async () => [Test] public async Task AddAndGetUnformattedLog() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var sDatabase = server.ResolveDependency(); @@ -115,15 +112,18 @@ await PoolManager.WaitUntil(server, async () => { Round = sGamerTicker.RoundId, Search = log.Message, - Types = new HashSet {log.Type}, + Types = new HashSet { log.Type }, }; await foreach (var json in sDatabase.GetAdminLogsJson(filter)) { var root = json.RootElement; - Assert.That(root.TryGetProperty("entity", out _), Is.True); - Assert.That(root.TryGetProperty("guid", out _), Is.True); + Assert.Multiple(() => + { + Assert.That(root.TryGetProperty("entity", out _), Is.True); + Assert.That(root.TryGetProperty("guid", out _), Is.True); + }); json.Dispose(); } @@ -135,7 +135,7 @@ await PoolManager.WaitUntil(server, async () => [TestCase(500)] public async Task BulkAddLogs(int amount) { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); @@ -204,7 +204,7 @@ await PoolManager.WaitUntil(server, async () => [Test] public async Task PreRoundAddAndGetSingle() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{Dirty = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { Dirty = true }); var server = pairTracker.Pair.Server; var configManager = server.ResolveDependency(); @@ -255,7 +255,7 @@ await PoolManager.WaitUntil(server, async () => { Round = sGamerTicker.RoundId, Search = log.Message, - Types = new HashSet {log.Type}, + Types = new HashSet { log.Type }, }; await foreach (var json in sDatabase.GetAdminLogsJson(filter)) diff --git a/Content.IntegrationTests/Tests/Administration/Logs/FilterTests.cs b/Content.IntegrationTests/Tests/Administration/Logs/FilterTests.cs index f67817ac65e..d02790d7626 100644 --- a/Content.IntegrationTests/Tests/Administration/Logs/FilterTests.cs +++ b/Content.IntegrationTests/Tests/Administration/Logs/FilterTests.cs @@ -1,12 +1,7 @@ -using System; -using System.Threading.Tasks; using Content.Server.Administration.Logs; using Content.Shared.Administration.Logs; -using Content.Shared.CCVar; using Content.Shared.Database; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.Map; namespace Content.IntegrationTests.Tests.Administration.Logs; @@ -19,7 +14,7 @@ public sealed class FilterTests [TestCase(DateOrder.Descending)] public async Task Date(DateOrder order) { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/Administration/Logs/QueryTests.cs b/Content.IntegrationTests/Tests/Administration/Logs/QueryTests.cs index 4805ce20cef..7f5de897e1f 100644 --- a/Content.IntegrationTests/Tests/Administration/Logs/QueryTests.cs +++ b/Content.IntegrationTests/Tests/Administration/Logs/QueryTests.cs @@ -1,12 +1,8 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Content.Server.Administration.Logs; using Content.Server.GameTicking; -using Content.Shared.CCVar; using Content.Shared.Database; -using NUnit.Framework; using Robust.Server.Player; using Robust.Shared.GameObjects; @@ -44,9 +40,9 @@ await server.WaitPost(() => { Round = sGamerTicker.RoundId, Search = guid.ToString(), - Types = new HashSet {LogType.Unknown}, + Types = new HashSet { LogType.Unknown }, After = date, - AnyPlayers = new[] {player.UserId.UserId} + AnyPlayers = new[] { player.UserId.UserId } }; await PoolManager.WaitUntil(server, async () => diff --git a/Content.IntegrationTests/Tests/Atmos/AlarmThresholdTest.cs b/Content.IntegrationTests/Tests/Atmos/AlarmThresholdTest.cs index fb483ebe75b..663cb27758b 100644 --- a/Content.IntegrationTests/Tests/Atmos/AlarmThresholdTest.cs +++ b/Content.IntegrationTests/Tests/Atmos/AlarmThresholdTest.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; using Content.Shared.Atmos.Monitor; -using NUnit.Framework; using Robust.Shared.Prototypes; namespace Content.IntegrationTests.Tests.Atmos @@ -25,7 +23,7 @@ public sealed class AlarmThresholdTest [Test] public async Task TestAlarmThreshold() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; var prototypeManager = server.ResolveDependency(); @@ -39,8 +37,11 @@ await server.WaitPost(() => await server.WaitAssertion(() => { // ensure upper/lower bounds are calculated - Assert.That(threshold.UpperWarningBound.Value, Is.EqualTo(5f * 0.5f)); - Assert.That(threshold.LowerWarningBound.Value, Is.EqualTo(1f * 1.5f)); + Assert.Multiple(() => + { + Assert.That(threshold.UpperWarningBound.Value, Is.EqualTo(5f * 0.5f)); + Assert.That(threshold.LowerWarningBound.Value, Is.EqualTo(1f * 1.5f)); + }); // ensure that setting bounds to zero/ // negative numbers is an invalid set @@ -102,7 +103,7 @@ await server.WaitAssertion(() => threshold.SetEnabled(AtmosMonitorLimitType.LowerWarning, true); // Check a value that's in between each upper/lower warning/panic: - threshold.CheckThreshold(3f, out AtmosAlarmType alarmType); + threshold.CheckThreshold(3f, out var alarmType); Assert.That(alarmType, Is.EqualTo(AtmosAlarmType.Normal)); threshold.CheckThreshold(1.5f, out alarmType); Assert.That(alarmType, Is.EqualTo(AtmosAlarmType.Warning)); diff --git a/Content.IntegrationTests/Tests/Atmos/ConstantsTest.cs b/Content.IntegrationTests/Tests/Atmos/ConstantsTest.cs index 6eba112b2f2..adcd3a38eaf 100644 --- a/Content.IntegrationTests/Tests/Atmos/ConstantsTest.cs +++ b/Content.IntegrationTests/Tests/Atmos/ConstantsTest.cs @@ -1,9 +1,6 @@ -using System; -using System.Linq; -using System.Threading.Tasks; +using System.Linq; using Content.Server.Atmos.EntitySystems; using Content.Shared.Atmos; -using NUnit.Framework; using Robust.Shared.GameObjects; namespace Content.IntegrationTests.Tests.Atmos @@ -15,16 +12,19 @@ public sealed class ConstantsTest [Test] public async Task TotalGasesTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; + var entityManager = server.ResolveDependency(); await server.WaitPost(() => { - var atmosSystem = EntitySystem.Get(); + var atmosSystem = entityManager.System(); - Assert.That(atmosSystem.Gases.Count(), Is.EqualTo(Atmospherics.TotalNumberOfGases)); - - Assert.That(Enum.GetValues(typeof(Gas)).Length, Is.EqualTo(Atmospherics.TotalNumberOfGases)); + Assert.Multiple(() => + { + Assert.That(atmosSystem.Gases.Count(), Is.EqualTo(Atmospherics.TotalNumberOfGases)); + Assert.That(Enum.GetValues(typeof(Gas)), Has.Length.EqualTo(Atmospherics.TotalNumberOfGases)); + }); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Atmos/GasMixtureTest.cs b/Content.IntegrationTests/Tests/Atmos/GasMixtureTest.cs index 1302dc9f4b9..cc74d5e675c 100644 --- a/Content.IntegrationTests/Tests/Atmos/GasMixtureTest.cs +++ b/Content.IntegrationTests/Tests/Atmos/GasMixtureTest.cs @@ -1,8 +1,6 @@ -using System.Threading.Tasks; -using Content.Server.Atmos; +using Content.Server.Atmos; using Content.Server.Atmos.EntitySystems; using Content.Shared.Atmos; -using NUnit.Framework; using Robust.Shared.GameObjects; namespace Content.IntegrationTests.Tests.Atmos @@ -14,7 +12,7 @@ public sealed class GasMixtureTest [Test] public async Task TestMerge() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var atmosphereSystem = server.ResolveDependency().GetEntitySystem(); @@ -28,23 +26,35 @@ await server.WaitAssertion(() => b.AdjustMoles(Gas.Nitrogen, 50); // a now has 50 moles of oxygen - Assert.That(a.TotalMoles, Is.EqualTo(50)); - Assert.That(a.GetMoles(Gas.Oxygen), Is.EqualTo(50)); + Assert.Multiple(() => + { + Assert.That(a.TotalMoles, Is.EqualTo(50)); + Assert.That(a.GetMoles(Gas.Oxygen), Is.EqualTo(50)); + }); // b now has 50 moles of nitrogen - Assert.That(b.TotalMoles, Is.EqualTo(50)); - Assert.That(b.GetMoles(Gas.Nitrogen), Is.EqualTo(50)); + Assert.Multiple(() => + { + Assert.That(b.TotalMoles, Is.EqualTo(50)); + Assert.That(b.GetMoles(Gas.Nitrogen), Is.EqualTo(50)); + }); atmosphereSystem.Merge(b, a); // b now has its contents and the contents of a - Assert.That(b.TotalMoles, Is.EqualTo(100)); - Assert.That(b.GetMoles(Gas.Oxygen), Is.EqualTo(50)); - Assert.That(b.GetMoles(Gas.Nitrogen), Is.EqualTo(50)); + Assert.Multiple(() => + { + Assert.That(b.TotalMoles, Is.EqualTo(100)); + Assert.That(b.GetMoles(Gas.Oxygen), Is.EqualTo(50)); + Assert.That(b.GetMoles(Gas.Nitrogen), Is.EqualTo(50)); + }); // a should be the same, however. - Assert.That(a.TotalMoles, Is.EqualTo(50)); - Assert.That(a.GetMoles(Gas.Oxygen), Is.EqualTo(50)); + Assert.Multiple(() => + { + Assert.That(a.TotalMoles, Is.EqualTo(50)); + Assert.That(a.GetMoles(Gas.Oxygen), Is.EqualTo(50)); + }); }); await pairTracker.CleanReturnAsync(); @@ -59,7 +69,7 @@ await server.WaitAssertion(() => [TestCase(Atmospherics.BreathPercentage)] public async Task RemoveRatio(float ratio) { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; await server.WaitAssertion(() => @@ -75,14 +85,23 @@ await server.WaitAssertion(() => var b = a.RemoveRatio(ratio); // check that the amount of moles in the original and the new mixture are correct. - Assert.That(b.TotalMoles, Is.EqualTo(origTotal * ratio)); - Assert.That(a.TotalMoles, Is.EqualTo(origTotal - b.TotalMoles)); - - Assert.That(b.GetMoles(Gas.Oxygen), Is.EqualTo(100 * ratio)); - Assert.That(b.GetMoles(Gas.Nitrogen), Is.EqualTo(100 * ratio)); - - Assert.That(a.GetMoles(Gas.Oxygen), Is.EqualTo(100 - b.GetMoles(Gas.Oxygen))); - Assert.That(a.GetMoles(Gas.Nitrogen), Is.EqualTo(100 - b.GetMoles(Gas.Nitrogen))); + Assert.Multiple(() => + { + Assert.That(b.TotalMoles, Is.EqualTo(origTotal * ratio)); + Assert.That(a.TotalMoles, Is.EqualTo(origTotal - b.TotalMoles)); + }); + + Assert.Multiple(() => + { + Assert.That(b.GetMoles(Gas.Oxygen), Is.EqualTo(100 * ratio)); + Assert.That(b.GetMoles(Gas.Nitrogen), Is.EqualTo(100 * ratio)); + }); + + Assert.Multiple(() => + { + Assert.That(a.GetMoles(Gas.Oxygen), Is.EqualTo(100 - b.GetMoles(Gas.Oxygen))); + Assert.That(a.GetMoles(Gas.Nitrogen), Is.EqualTo(100 - b.GetMoles(Gas.Nitrogen))); + }); }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/Body/LegTest.cs b/Content.IntegrationTests/Tests/Body/LegTest.cs index 3930e3dfb34..cd5fa23da0c 100644 --- a/Content.IntegrationTests/Tests/Body/LegTest.cs +++ b/Content.IntegrationTests/Tests/Body/LegTest.cs @@ -1,11 +1,8 @@ -using System.Threading.Tasks; -using Content.Server.Body.Systems; +using Content.Server.Body.Systems; using Content.Shared.Body.Components; using Content.Shared.Body.Part; using Content.Shared.Rotation; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -31,24 +28,34 @@ public sealed class LegTest public async Task RemoveLegsFallTest() { await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings - {NoClient = true, ExtraPrototypes = Prototypes}); + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; + EntityUid human = default!; AppearanceComponent appearance = null; + var entityManager = server.ResolveDependency(); var mapManager = server.ResolveDependency(); + var appearanceSystem = entityManager.System(); await server.WaitAssertion(() => { var mapId = mapManager.CreateMap(); + BodyComponent body = null; - var human = entityManager.SpawnEntity("HumanBodyAndAppearanceDummy", + human = entityManager.SpawnEntity("HumanBodyAndAppearanceDummy", new MapCoordinates(Vector2.Zero, mapId)); - Assert.That(entityManager.TryGetComponent(human, out BodyComponent body)); - Assert.That(entityManager.TryGetComponent(human, out appearance)); + Assert.Multiple(() => + { + Assert.That(entityManager.TryGetComponent(human, out body)); + Assert.That(entityManager.TryGetComponent(human, out appearance)); + }); - Assert.That(!appearance.TryGetData(RotationVisuals.RotationState, out RotationState _)); + Assert.That(!appearanceSystem.TryGetData(human, RotationVisuals.RotationState, out RotationState _, appearance)); var bodySystem = entityManager.System(); var legs = bodySystem.GetBodyChildrenOfType(human, BodyPartType.Leg, body); @@ -61,8 +68,11 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(appearance.TryGetData(RotationVisuals.RotationState, out RotationState state)); +#pragma warning disable NUnit2045 + // Interdependent assertions. + Assert.That(appearanceSystem.TryGetData(human, RotationVisuals.RotationState, out RotationState state, appearance)); Assert.That(state, Is.EqualTo(RotationState.Horizontal)); +#pragma warning restore NUnit2045 }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Body/LungTest.cs b/Content.IntegrationTests/Tests/Body/LungTest.cs index 7cb54d39371..637740d64d4 100644 --- a/Content.IntegrationTests/Tests/Body/LungTest.cs +++ b/Content.IntegrationTests/Tests/Body/LungTest.cs @@ -1,16 +1,16 @@ -using System.Threading.Tasks; using Content.Server.Atmos.Components; using Content.Server.Atmos.EntitySystems; using Content.Server.Body.Components; using Content.Server.Body.Systems; using Content.Shared.Body.Components; -using NUnit.Framework; using Robust.Server.GameObjects; using Robust.Shared; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Maths; +using System.Linq; namespace Content.IntegrationTests.Tests.Body { @@ -52,7 +52,10 @@ public async Task AirConsistencyTest() { // --- Setup await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings - {NoClient = true, ExtraPrototypes = Prototypes}); + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); @@ -68,17 +71,22 @@ public async Task AirConsistencyTest() BodyComponent body = default; EntityUid human = default; GridAtmosphereComponent relevantAtmos = default; - float startingMoles = 0.0f; + var startingMoles = 0.0f; var testMapName = "Maps/Test/Breathing/3by3-20oxy-80nit.yml"; await server.WaitPost(() => { mapId = mapManager.CreateMap(); - grid = mapLoader.LoadGrid(mapId, testMapName); + Assert.That(mapLoader.TryLoad(mapId, testMapName, out var roots)); + + var query = entityManager.GetEntityQuery(); + var grids = roots.Where(x => query.HasComponent(x)); + Assert.That(grids, Is.Not.Empty); + grid = grids.First(); }); - Assert.NotNull(grid, $"Test blueprint {testMapName} not found."); + Assert.That(grid, Is.Not.Null, $"Test blueprint {testMapName} not found."); float GetMapMoles() { @@ -96,13 +104,15 @@ await server.WaitAssertion(() => var coords = new Vector2(0.5f, -1f); var coordinates = new EntityCoordinates(grid.Value, coords); human = entityManager.SpawnEntity("HumanBodyDummy", coordinates); - respSys = EntitySystem.Get(); - metaSys = EntitySystem.Get(); + respSys = entityManager.System(); + metaSys = entityManager.System(); relevantAtmos = entityManager.GetComponent(grid.Value); startingMoles = GetMapMoles(); - Assert.True(entityManager.TryGetComponent(human, out body)); - Assert.True(entityManager.HasComponent(human)); +#pragma warning disable NUnit2045 + Assert.That(entityManager.TryGetComponent(human, out body), Is.True); + Assert.That(entityManager.HasComponent(human), Is.True); +#pragma warning restore NUnit2045 }); // --- End setup @@ -131,7 +141,10 @@ await server.WaitAssertion(() => public async Task NoSuffocationTest() { await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings - {NoClient = true, ExtraPrototypes = Prototypes}); + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); @@ -149,10 +162,16 @@ public async Task NoSuffocationTest() await server.WaitPost(() => { mapId = mapManager.CreateMap(); - grid = mapLoader.LoadGrid(mapId, testMapName); + + Assert.That(mapLoader.TryLoad(mapId, testMapName, out var ents), Is.True); + var query = entityManager.GetEntityQuery(); + grid = ents + .Select(x => x) + .FirstOrDefault((uid) => uid.HasValue && query.HasComponent(uid.Value), null); + Assert.That(grid, Is.Not.Null); }); - Assert.NotNull(grid, $"Test blueprint {testMapName} not found."); + Assert.That(grid, Is.Not.Null, $"Test blueprint {testMapName} not found."); await server.WaitAssertion(() => { @@ -162,11 +181,12 @@ await server.WaitAssertion(() => human = entityManager.SpawnEntity("HumanBodyDummy", coordinates); var mixture = entityManager.System().GetContainingMixture(human); +#pragma warning disable NUnit2045 Assert.That(mixture.TotalMoles, Is.GreaterThan(0)); - - Assert.True(entityManager.HasComponent(human)); - Assert.True(entityManager.TryGetComponent(human, out respirator)); - Assert.False(respirator.SuffocationCycles > respirator.SuffocationCycleThreshold); + Assert.That(entityManager.HasComponent(human), Is.True); + Assert.That(entityManager.TryGetComponent(human, out respirator), Is.True); + Assert.That(respirator.SuffocationCycles, Is.LessThanOrEqualTo(respirator.SuffocationCycleThreshold)); +#pragma warning restore NUnit2045 }); var increment = 10; @@ -179,7 +199,7 @@ await server.WaitAssertion(() => await server.WaitRunTicks(increment); await server.WaitAssertion(() => { - Assert.False(respirator.SuffocationCycles > respirator.SuffocationCycleThreshold, + Assert.That(respirator.SuffocationCycles, Is.LessThanOrEqualTo(respirator.SuffocationCycleThreshold), $"Entity {entityManager.GetComponent(human).EntityName} is suffocating on tick {tick}"); }); } diff --git a/Content.IntegrationTests/Tests/Body/SaveLoadReparentTest.cs b/Content.IntegrationTests/Tests/Body/SaveLoadReparentTest.cs index deb2f059c6c..d89048ce539 100644 --- a/Content.IntegrationTests/Tests/Body/SaveLoadReparentTest.cs +++ b/Content.IntegrationTests/Tests/Body/SaveLoadReparentTest.cs @@ -1,10 +1,8 @@ -using System.Linq; -using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; using Content.Shared.Body.Components; using Content.Shared.Body.Systems; -using NUnit.Framework; using Robust.Server.GameObjects; -using Robust.Server.Maps; using Robust.Shared.GameObjects; using Robust.Shared.Map; @@ -85,10 +83,22 @@ await server.WaitAssertion(() => }); } - Assert.That(entities - .EntityQuery() - .Where(e => entities.GetComponent(e.Owner).EntityPrototype!.Name == - "HumanBodyDummy"), Is.Not.Empty); + // Converts an entity query enumerator to an enumerable. + static IEnumerable<(EntityUid Uid, TComp Comp)> EnumerateQueryEnumerator(EntityQueryEnumerator query) + where TComp : Component + { + while (query.MoveNext(out var uid, out var comp)) + yield return (uid, comp); + } + + Assert.That( + EnumerateQueryEnumerator( + entities.EntityQueryEnumerator() + ).Where((e) => + entities.GetComponent(e.Uid).EntityPrototype!.Name == "HumanBodyDummy" + ), + Is.Not.Empty + ); const string mapPath = $"/{nameof(SaveLoadReparentTest)}{nameof(Test)}map.yml"; @@ -96,22 +106,26 @@ await server.WaitAssertion(() => maps.DeleteMap(mapId); mapId = maps.CreateMap(); - mapLoader.LoadMap(mapId, mapPath); + Assert.That(mapLoader.TryLoad(mapId, mapPath, out _), Is.True); - var query = entities - .EntityQuery() - .Where(e => entities.GetComponent(e.Owner).EntityPrototype!.Name == "HumanBodyDummy") - .ToArray(); + var query = EnumerateQueryEnumerator( + entities.EntityQueryEnumerator() + ).Where((e) => + entities.GetComponent(e.Uid).EntityPrototype!.Name == "HumanBodyDummy" + ).ToArray(); Assert.That(query, Is.Not.Empty); - foreach (var body in query) + foreach (var (uid, body) in query) { - human = body.Owner; + human = uid; parts = bodySystem.GetBodyChildren(human).ToArray(); organs = bodySystem.GetBodyOrgans(human).ToArray(); - Assert.That(parts, Is.Not.Empty); - Assert.That(organs, Is.Not.Empty); + Assert.Multiple(() => + { + Assert.That(parts, Is.Not.Empty); + Assert.That(organs, Is.Not.Empty); + }); foreach (var (id, component) in parts) { diff --git a/Content.IntegrationTests/Tests/Buckle/BuckleTest.cs b/Content.IntegrationTests/Tests/Buckle/BuckleTest.cs index f2f278b4aed..2421e065608 100644 --- a/Content.IntegrationTests/Tests/Buckle/BuckleTest.cs +++ b/Content.IntegrationTests/Tests/Buckle/BuckleTest.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using Content.Server.Body.Systems; using Content.Shared.Buckle; using Content.Shared.ActionBlocker; @@ -8,7 +7,6 @@ using Content.Shared.Hands.Components; using Content.Shared.Hands.EntitySystems; using Content.Shared.Standing; -using NUnit.Framework; using Robust.Shared.GameObjects; namespace Content.IntegrationTests.Tests.Buckle @@ -50,15 +48,16 @@ public sealed class BuckleTest public async Task BuckleUnbuckleCooldownRangeTest() { await using var pairTracker = - await PoolManager.GetServerClient(new PoolSettings {ExtraPrototypes = Prototypes}); + await PoolManager.GetServerClient(new PoolSettings { ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); var coordinates = testMap.GridCoords; var entityManager = server.ResolveDependency(); - var actionBlocker = entityManager.EntitySysManager.GetEntitySystem(); - var buckleSystem = entityManager.EntitySysManager.GetEntitySystem(); - var standingState = entityManager.EntitySysManager.GetEntitySystem(); + var actionBlocker = entityManager.System(); + var buckleSystem = entityManager.System(); + var standingState = entityManager.System(); + var xformSystem = entityManager.System(); EntityUid human = default; EntityUid chair = default; @@ -71,47 +70,58 @@ await server.WaitAssertion(() => chair = entityManager.SpawnEntity(StrapDummyId, coordinates); // Default state, unbuckled - Assert.True(entityManager.TryGetComponent(human, out buckle)); - Assert.NotNull(buckle); - Assert.Null(buckle.BuckledTo); - Assert.False(buckle.Buckled); - Assert.True(actionBlocker.CanMove(human)); - Assert.True(actionBlocker.CanChangeDirection(human)); - Assert.True(standingState.Down(human)); - Assert.True(standingState.Stand(human)); + Assert.That(entityManager.TryGetComponent(human, out buckle)); + Assert.Multiple(() => + { + Assert.That(buckle, Is.Not.Null); + Assert.That(buckle.BuckledTo, Is.Null); + Assert.That(buckle.Buckled, Is.False); + Assert.That(actionBlocker.CanMove(human)); + Assert.That(actionBlocker.CanChangeDirection(human)); + Assert.That(standingState.Down(human)); + Assert.That(standingState.Stand(human)); + }); // Default state, no buckled entities, strap - Assert.True(entityManager.TryGetComponent(chair, out strap)); - Assert.NotNull(strap); - Assert.IsEmpty(strap.BuckledEntities); - Assert.Zero(strap.OccupiedSize); + Assert.That(entityManager.TryGetComponent(chair, out strap)); + Assert.Multiple(() => + { + Assert.That(strap, Is.Not.Null); + Assert.That(strap.BuckledEntities, Is.Empty); + Assert.That(strap.OccupiedSize, Is.Zero); + }); // Side effects of buckling - Assert.True(buckleSystem.TryBuckle(human, human, chair, buckle)); - Assert.NotNull(buckle.BuckledTo); - Assert.True(buckle.Buckled); - - Assert.False(actionBlocker.CanMove(human)); - Assert.False(actionBlocker.CanChangeDirection(human)); - Assert.False(standingState.Down(human)); - Assert.That( - (entityManager.GetComponent(human).WorldPosition - - entityManager.GetComponent(chair).WorldPosition).Length, - Is.LessThanOrEqualTo(0)); - - // Side effects of buckling for the strap - Assert.That(strap.BuckledEntities, Does.Contain(human)); - Assert.That(strap.OccupiedSize, Is.EqualTo(buckle.Size)); - Assert.Positive(strap.OccupiedSize); - + Assert.That(buckleSystem.TryBuckle(human, human, chair, buckle)); + Assert.Multiple(() => + { + Assert.That(buckle.BuckledTo, Is.Not.Null); + Assert.That(buckle.Buckled); + + Assert.That(actionBlocker.CanMove(human), Is.False); + Assert.That(actionBlocker.CanChangeDirection(human), Is.False); + Assert.That(standingState.Down(human), Is.False); + Assert.That( + (xformSystem.GetWorldPosition(human) - xformSystem.GetWorldPosition(chair)).LengthSquared, + Is.LessThanOrEqualTo(0) + ); + + // Side effects of buckling for the strap + Assert.That(strap.BuckledEntities, Does.Contain(human)); + Assert.That(strap.OccupiedSize, Is.EqualTo(buckle.Size)); + Assert.Positive(strap.OccupiedSize); + }); + +#pragma warning disable NUnit2045 // Interdependent asserts. // Trying to buckle while already buckled fails - Assert.False(buckleSystem.TryBuckle(human, human, chair, buckle)); + Assert.That(buckleSystem.TryBuckle(human, human, chair, buckle), Is.False); // Trying to unbuckle too quickly fails - Assert.False(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle)); - Assert.True(buckle.Buckled); - Assert.False(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle)); - Assert.True(buckle.Buckled); + Assert.That(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle), Is.False); + Assert.That(buckle.Buckled); + Assert.That(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle), Is.False); + Assert.That(buckle.Buckled); +#pragma warning restore NUnit2045 }); // Wait enough ticks for the unbuckling cooldown to run out @@ -119,32 +129,39 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { +#pragma warning disable NUnit2045 // Interdependent asserts. + Assert.That(buckle.Buckled); // Still buckled - Assert.True(buckle.Buckled); +#pragma warning restore NUnit2045 // Unbuckle - Assert.True(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle)); - Assert.Null(buckle.BuckledTo); - Assert.False(buckle.Buckled); - Assert.True(actionBlocker.CanMove(human)); - Assert.True(actionBlocker.CanChangeDirection(human)); - Assert.True(standingState.Down(human)); - - // Unbuckle, strap - Assert.IsEmpty(strap.BuckledEntities); - Assert.Zero(strap.OccupiedSize); - + Assert.That(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle)); + Assert.Multiple(() => + { + Assert.That(buckle.BuckledTo, Is.Null); + Assert.That(buckle.Buckled, Is.False); + Assert.That(actionBlocker.CanMove(human)); + Assert.That(actionBlocker.CanChangeDirection(human)); + Assert.That(standingState.Down(human)); + + // Unbuckle, strap + Assert.That(strap.BuckledEntities, Is.Empty); + Assert.That(strap.OccupiedSize, Is.Zero); + }); + +#pragma warning disable NUnit2045 // Interdependent asserts. // Re-buckling has no cooldown - Assert.True(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); - Assert.True(buckle.Buckled); + Assert.That(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); + Assert.That(buckle.Buckled); // On cooldown - Assert.False(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle)); - Assert.True(buckle.Buckled); - Assert.False(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle)); - Assert.True(buckle.Buckled); - Assert.False(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle)); - Assert.True(buckle.Buckled); + Assert.That(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle), Is.False); + Assert.That(buckle.Buckled); + Assert.That(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle), Is.False); + Assert.That(buckle.Buckled); + Assert.That(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle), Is.False); + Assert.That(buckle.Buckled); +#pragma warning restore NUnit2045 }); // Wait enough ticks for the unbuckling cooldown to run out @@ -152,45 +169,57 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { +#pragma warning disable NUnit2045 // Interdependent asserts. // Still buckled - Assert.True(buckle.Buckled); + Assert.That(buckle.Buckled); // Unbuckle - Assert.True(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle)); - Assert.False(buckle.Buckled); + Assert.That(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle)); + Assert.That(buckle.Buckled, Is.False); +#pragma warning restore NUnit2045 // Move away from the chair - entityManager.GetComponent(human).WorldPosition += (1000, 1000); + var xformQuery = entityManager.GetEntityQuery(); + var oldWorldPosition = xformSystem.GetWorldPosition(chair, xformQuery); + xformSystem.SetWorldPosition(human, oldWorldPosition + (1000, 1000), xformQuery); // Out of range - Assert.False(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); - Assert.False(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle)); - Assert.False(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle)); +#pragma warning disable NUnit2045 // Interdependent asserts. + Assert.That(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle), Is.False); + Assert.That(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle), Is.False); + Assert.That(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle), Is.False); +#pragma warning restore NUnit2045 // Move near the chair - entityManager.GetComponent(human).WorldPosition = - entityManager.GetComponent(chair).WorldPosition + (0.5f, 0); + oldWorldPosition = xformSystem.GetWorldPosition(chair, xformQuery); + xformSystem.SetWorldPosition(human, oldWorldPosition + (0.5f, 0), xformQuery); // In range - Assert.True(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); - Assert.True(buckle.Buckled); - Assert.False(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle)); - Assert.True(buckle.Buckled); - Assert.False(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle)); - Assert.True(buckle.Buckled); +#pragma warning disable NUnit2045 // Interdependent asserts. + Assert.That(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); + Assert.That(buckle.Buckled); + Assert.That(buckleSystem.TryUnbuckle(human, human, buckleComp: buckle), Is.False); + Assert.That(buckle.Buckled); + Assert.That(buckleSystem.ToggleBuckle(human, human, chair, buckle: buckle), Is.False); + Assert.That(buckle.Buckled); +#pragma warning restore NUnit2045 // Force unbuckle - Assert.True(buckleSystem.TryUnbuckle(human, human, true, buckleComp: buckle)); - Assert.False(buckle.Buckled); - Assert.True(actionBlocker.CanMove(human)); - Assert.True(actionBlocker.CanChangeDirection(human)); - Assert.True(standingState.Down(human)); + Assert.That(buckleSystem.TryUnbuckle(human, human, true, buckleComp: buckle)); + Assert.Multiple(() => + { + Assert.That(buckle.Buckled, Is.False); + Assert.That(actionBlocker.CanMove(human)); + Assert.That(actionBlocker.CanChangeDirection(human)); + Assert.That(standingState.Down(human)); + }); // Re-buckle - Assert.True(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); + Assert.That(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); // Move away from the chair - entityManager.GetComponent(human).WorldPosition += (1, 0); + oldWorldPosition = xformSystem.GetWorldPosition(chair, xformQuery); + xformSystem.SetWorldPosition(human, oldWorldPosition + (1, 0), xformQuery); }); await server.WaitRunTicks(1); @@ -198,9 +227,12 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { // No longer buckled - Assert.False(buckle.Buckled); - Assert.Null(buckle.BuckledTo); - Assert.IsEmpty(strap.BuckledEntities); + Assert.Multiple(() => + { + Assert.That(buckle.Buckled, Is.False); + Assert.That(buckle.BuckledTo, Is.Null); + Assert.That(strap.BuckledEntities, Is.Empty); + }); }); await pairTracker.CleanReturnAsync(); @@ -210,7 +242,10 @@ await server.WaitAssertion(() => public async Task BuckledDyingDropItemsTest() { await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings - {NoClient = true, ExtraPrototypes = Prototypes}); + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -233,22 +268,28 @@ await server.WaitAssertion(() => var chair = entityManager.SpawnEntity(StrapDummyId, coordinates); // Component sanity check - Assert.True(entityManager.TryGetComponent(human, out buckle)); - Assert.True(entityManager.HasComponent(chair)); - Assert.True(entityManager.TryGetComponent(human, out hands)); - Assert.True(entityManager.TryGetComponent(human, out body)); + Assert.Multiple(() => + { + Assert.That(entityManager.TryGetComponent(human, out buckle)); + Assert.That(entityManager.HasComponent(chair)); + Assert.That(entityManager.TryGetComponent(human, out hands)); + Assert.That(entityManager.TryGetComponent(human, out body)); + }); // Buckle - Assert.True(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); - Assert.NotNull(buckle.BuckledTo); - Assert.True(buckle.Buckled); + Assert.That(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); + Assert.Multiple(() => + { + Assert.That(buckle.BuckledTo, Is.Not.Null); + Assert.That(buckle.Buckled); + }); // Put an item into every hand for (var i = 0; i < hands.Count; i++) { var akms = entityManager.SpawnEntity(ItemDummyId, coordinates); - Assert.True(handsSys.TryPickupAnyHand(human, akms)); + Assert.That(handsSys.TryPickupAnyHand(human, akms)); } }); @@ -257,16 +298,16 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { // Still buckled - Assert.True(buckle.Buckled); + Assert.That(buckle.Buckled); // With items in all hands foreach (var hand in hands.Hands.Values) { - Assert.NotNull(hand.HeldEntity); + Assert.That(hand.HeldEntity, Is.Not.Null); } var bodySystem = entityManager.System(); - var legs = bodySystem.GetBodyChildrenOfType(body.Owner, BodyPartType.Leg, body); + var legs = bodySystem.GetBodyChildrenOfType(human, BodyPartType.Leg, body); // Break our guy's kneecaps foreach (var leg in legs) @@ -280,12 +321,12 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { // Still buckled - Assert.True(buckle.Buckled); + Assert.That(buckle.Buckled); // Now with no item in any hand foreach (var hand in hands.Hands.Values) { - Assert.Null(hand.HeldEntity); + Assert.That(hand.HeldEntity, Is.Null); } buckleSystem.TryUnbuckle(human, human, true, buckleComp: buckle); @@ -298,13 +339,17 @@ await server.WaitAssertion(() => public async Task ForceUnbuckleBuckleTest() { await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings - {NoClient = true, ExtraPrototypes = Prototypes}); + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); var coordinates = testMap.GridCoords; var entityManager = server.ResolveDependency(); var buckleSystem = entityManager.System(); + var xformSystem = entityManager.System(); EntityUid human = default; EntityUid chair = default; @@ -316,31 +361,44 @@ await server.WaitAssertion(() => chair = entityManager.SpawnEntity(StrapDummyId, coordinates); // Component sanity check - Assert.True(entityManager.TryGetComponent(human, out buckle)); - Assert.True(entityManager.HasComponent(chair)); + Assert.Multiple(() => + { + Assert.That(entityManager.TryGetComponent(human, out buckle)); + Assert.That(entityManager.HasComponent(chair)); + }); // Buckle - Assert.True(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); - Assert.NotNull(buckle.BuckledTo); - Assert.True(buckle.Buckled); + Assert.That(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); + Assert.Multiple(() => + { + Assert.That(buckle.BuckledTo, Is.Not.Null); + Assert.That(buckle.Buckled); + }); // Move the buckled entity away - entityManager.GetComponent(human).WorldPosition += (100, 0); + var xformQuery = entityManager.GetEntityQuery(); + var oldWorldPosition = xformSystem.GetWorldPosition(chair, xformQuery); + xformSystem.SetWorldPosition(human, oldWorldPosition + (100, 0), xformQuery); }); await PoolManager.WaitUntil(server, () => !buckle.Buckled, 10); - Assert.False(buckle.Buckled); + Assert.That(buckle.Buckled, Is.False); await server.WaitAssertion(() => { // Move the now unbuckled entity back onto the chair - entityManager.GetComponent(human).WorldPosition -= (100, 0); + var xformQuery = entityManager.GetEntityQuery(); + var oldWorldPosition = xformSystem.GetWorldPosition(chair, xformQuery); + xformSystem.SetWorldPosition(human, oldWorldPosition, xformQuery); // Buckle - Assert.True(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); - Assert.NotNull(buckle.BuckledTo); - Assert.True(buckle.Buckled); + Assert.That(buckleSystem.TryBuckle(human, human, chair, buckleComp: buckle)); + Assert.Multiple(() => + { + Assert.That(buckle.BuckledTo, Is.Not.Null); + Assert.That(buckle.Buckled); + }); }); await server.WaitRunTicks(60); @@ -348,8 +406,11 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { // Still buckled - Assert.NotNull(buckle.BuckledTo); - Assert.True(buckle.Buckled); + Assert.Multiple(() => + { + Assert.That(buckle.BuckledTo, Is.Not.Null); + Assert.That(buckle.Buckled); + }); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/CargoTest.cs b/Content.IntegrationTests/Tests/CargoTest.cs index 61a451af8a3..86810453ca3 100644 --- a/Content.IntegrationTests/Tests/CargoTest.cs +++ b/Content.IntegrationTests/Tests/CargoTest.cs @@ -1,12 +1,8 @@ -using System.Threading.Tasks; using System.Linq; using Content.Server.Cargo.Components; using Content.Server.Cargo.Systems; using Content.Shared.Cargo.Prototypes; -using Content.Shared.CCVar; using Content.Shared.Stacks; -using NUnit.Framework; -using Robust.Shared.Configuration; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -20,7 +16,7 @@ public sealed class CargoTest [Test] public async Task NoCargoOrderArbitrage() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings() {NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings() { NoClient = true }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -54,7 +50,7 @@ await server.WaitAssertion(() => [Test] public async Task NoCargoBountyArbitageTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings() {NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings() { NoClient = true }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -95,7 +91,7 @@ await server.WaitAssertion(() => [Test] public async Task NoStaticPriceAndStackPrice() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -111,7 +107,7 @@ await server.WaitAssertion(() => var coord = new EntityCoordinates(grid.Owner, 0, 0); var protoIds = protoManager.EnumeratePrototypes() - .Where(p=>!p.Abstract) + .Where(p => !p.Abstract) .Where(p => !p.Components.ContainsKey("MapGrid")) // Grids are not for sale. .Select(p => p.ID) .ToList(); @@ -150,7 +146,7 @@ await server.WaitAssertion(() => [Test] public async Task StackPrice() { - const string StackProto = @" + const string stackProto = @" - type: entity id: A @@ -168,7 +164,7 @@ public async Task StackPrice() count: 5 "; - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = StackProto}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = stackProto }); var server = pairTracker.Pair.Server; var entManager = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/Chemistry/DispenserTest.cs b/Content.IntegrationTests/Tests/Chemistry/DispenserTest.cs index eebb3358dfe..affb43db3ec 100644 --- a/Content.IntegrationTests/Tests/Chemistry/DispenserTest.cs +++ b/Content.IntegrationTests/Tests/Chemistry/DispenserTest.cs @@ -1,9 +1,7 @@ -using System.Threading.Tasks; using Content.Client.Chemistry.UI; using Content.IntegrationTests.Tests.Interaction; using Content.Shared.Chemistry; using Content.Shared.Containers.ItemSlots; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Chemistry; @@ -20,7 +18,7 @@ public async Task InsertEjectBuiTest() // Insert beaker await Interact("Beaker"); - Assert.IsNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Null); // Open BUI await Interact(); @@ -30,18 +28,18 @@ public async Task InsertEjectBuiTest() await SendBui(ReagentDispenserUiKey.Key, ev); // Beaker is back in the player's hands - Assert.IsNotNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Not.Null); AssertPrototype("Beaker", Hands.ActiveHandEntity); // Re-insert the beaker await Interact(); - Assert.IsNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Null); // Re-eject using the button directly instead of sending a BUI event. This test is really just a test of the // bui/window helper methods. await ClickControl(nameof(ReagentDispenserWindow.EjectButton)); await RunTicks(5); - Assert.IsNotNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Not.Null); AssertPrototype("Beaker", Hands.ActiveHandEntity); } } diff --git a/Content.IntegrationTests/Tests/Chemistry/FixedPoint2SerializationTest.cs b/Content.IntegrationTests/Tests/Chemistry/FixedPoint2SerializationTest.cs index beff69eddf0..66918e3a496 100644 --- a/Content.IntegrationTests/Tests/Chemistry/FixedPoint2SerializationTest.cs +++ b/Content.IntegrationTests/Tests/Chemistry/FixedPoint2SerializationTest.cs @@ -1,6 +1,5 @@ using System.Reflection; using Content.Shared.FixedPoint; -using NUnit.Framework; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.Markdown.Mapping; using Robust.Shared.Serialization.Markdown.Value; @@ -35,8 +34,10 @@ public void SerializeNullTest() public void SerializeNullableValueTest() { var node = Serialization.WriteValue(FixedPoint2.New(2.5f)); +#pragma warning disable NUnit2045 // Interdependent assertions Assert.That(node is ValueDataNode); - Assert.That(((ValueDataNode)node).Value, Is.EqualTo("2.5")); + Assert.That(((ValueDataNode) node).Value, Is.EqualTo("2.5")); +#pragma warning restore NUnit2045 } [Test] diff --git a/Content.IntegrationTests/Tests/Chemistry/SolutionSystemTests.cs b/Content.IntegrationTests/Tests/Chemistry/SolutionSystemTests.cs index 661868e6387..0372e5ca882 100644 --- a/Content.IntegrationTests/Tests/Chemistry/SolutionSystemTests.cs +++ b/Content.IntegrationTests/Tests/Chemistry/SolutionSystemTests.cs @@ -1,8 +1,6 @@ -using System.Threading.Tasks; using Content.Server.Chemistry.EntitySystems; using Content.Shared.Chemistry.Components; using Content.Shared.FixedPoint; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Prototypes; @@ -47,7 +45,11 @@ public sealed class SolutionSystemTests [Test] public async Task TryAddTwoNonReactiveReagent() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var entityManager = server.ResolveDependency(); @@ -76,8 +78,11 @@ await server.WaitAssertion(() => solution.TryGetReagent("Water", out var water); solution.TryGetReagent("Oil", out var oil); - Assert.That(water, Is.EqualTo(waterQuantity)); - Assert.That(oil, Is.EqualTo(oilQuantity)); + Assert.Multiple(() => + { + Assert.That(water, Is.EqualTo(waterQuantity)); + Assert.That(oil, Is.EqualTo(oilQuantity)); + }); }); await pairTracker.CleanReturnAsync(); @@ -88,7 +93,11 @@ await server.WaitAssertion(() => [Test] public async Task TryAddTooMuchNonReactiveReagent() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -118,8 +127,11 @@ await server.WaitAssertion(() => solution.TryGetReagent("Water", out var water); solution.TryGetReagent("Oil", out var oil); - Assert.That(water, Is.EqualTo(waterQuantity)); - Assert.That(oil, Is.EqualTo(FixedPoint2.Zero)); + Assert.Multiple(() => + { + Assert.That(water, Is.EqualTo(waterQuantity)); + Assert.That(oil, Is.EqualTo(FixedPoint2.Zero)); + }); }); await pairTracker.CleanReturnAsync(); @@ -129,7 +141,11 @@ await server.WaitAssertion(() => [Test] public async Task TryMixAndOverflowTooMuchReagent() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; @@ -141,10 +157,10 @@ public async Task TryMixAndOverflowTooMuchReagent() EntityUid beaker; - await server.WaitAssertion((System.Action)(() => + await server.WaitAssertion(() => { - int ratio = 9; - int threshold = 20; + var ratio = 9; + var threshold = 20; var waterQuantity = FixedPoint2.New(10); var oilQuantity = FixedPoint2.New(ratio * waterQuantity.Int()); @@ -159,18 +175,23 @@ await server.WaitAssertion((System.Action)(() => Assert.That(containerSystem .TryMixAndOverflow(beaker, solution, oilAdded, threshold, out var overflowingSolution)); - Assert.That(solution.Volume, Is.EqualTo(FixedPoint2.New(threshold))); - solution.TryGetReagent("Water", out var waterMix); - solution.TryGetReagent("Oil", out var oilMix); - Assert.That(waterMix, Is.EqualTo(FixedPoint2.New(threshold / (ratio + 1)))); - Assert.That(oilMix, Is.EqualTo(FixedPoint2.New(threshold / (ratio + 1) * ratio))); + Assert.Multiple(() => + { + Assert.That(solution.Volume, Is.EqualTo(FixedPoint2.New(threshold))); + + solution.TryGetReagent("Water", out var waterMix); + solution.TryGetReagent("Oil", out var oilMix); + Assert.That(waterMix, Is.EqualTo(FixedPoint2.New(threshold / (ratio + 1)))); + Assert.That(oilMix, Is.EqualTo(FixedPoint2.New(threshold / (ratio + 1) * ratio))); + + Assert.That(overflowingSolution.Volume, Is.EqualTo(FixedPoint2.New(80))); - Assert.That(overflowingSolution.Volume, Is.EqualTo(FixedPoint2.New(80))); - overflowingSolution.TryGetReagent("Water", out var waterOverflow); - overflowingSolution.TryGetReagent("Oil", out var oilOverFlow); - Assert.That(waterOverflow, Is.EqualTo(waterQuantity - waterMix)); - Assert.That(oilOverFlow, Is.EqualTo(oilQuantity - oilMix)); - })); + overflowingSolution.TryGetReagent("Water", out var waterOverflow); + overflowingSolution.TryGetReagent("Oil", out var oilOverFlow); + Assert.That(waterOverflow, Is.EqualTo(waterQuantity - waterMix)); + Assert.That(oilOverFlow, Is.EqualTo(oilQuantity - oilMix)); + }); + }); await pairTracker.CleanReturnAsync(); } @@ -179,7 +200,11 @@ await server.WaitAssertion((System.Action)(() => [Test] public async Task TryMixAndOverflowTooBigOverflow() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var entityManager = server.ResolveDependency(); @@ -192,8 +217,8 @@ public async Task TryMixAndOverflowTooBigOverflow() await server.WaitAssertion(() => { - int ratio = 9; - int threshold = 60; + var ratio = 9; + var threshold = 60; var waterQuantity = FixedPoint2.New(10); var oilQuantity = FixedPoint2.New(ratio * waterQuantity.Int()); diff --git a/Content.IntegrationTests/Tests/Chemistry/TryAllReactionsTest.cs b/Content.IntegrationTests/Tests/Chemistry/TryAllReactionsTest.cs index 282b2a169d9..37a9c7c1625 100644 --- a/Content.IntegrationTests/Tests/Chemistry/TryAllReactionsTest.cs +++ b/Content.IntegrationTests/Tests/Chemistry/TryAllReactionsTest.cs @@ -1,11 +1,7 @@ -using System; using System.Linq; -using System.Threading.Tasks; using Content.Server.Chemistry.EntitySystems; -using Content.Server.Engineering.Components; using Content.Shared.Chemistry.Components; using Content.Shared.Chemistry.Reaction; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Prototypes; @@ -29,7 +25,11 @@ public sealed class TryAllReactionsTest [Test] public async Task TryAllTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var entityManager = server.ResolveDependency(); @@ -54,9 +54,11 @@ await server.WaitAssertion(() => .TryGetSolution(beaker, "beaker", out component)); foreach (var (id, reactant) in reactionPrototype.Reactants) { +#pragma warning disable NUnit2045 Assert.That(solutionSystem .TryAddReagent(beaker, component, id, reactant.Amount, out var quantity)); Assert.That(reactant.Amount, Is.EqualTo(quantity)); +#pragma warning restore NUnit2045 } solutionSystem.SetTemperature(beaker, component, reactionPrototype.MinimumTemperature); diff --git a/Content.IntegrationTests/Tests/Cleanup/EuiManagerTest.cs b/Content.IntegrationTests/Tests/Cleanup/EuiManagerTest.cs index 78619f98f44..d8efb03f7da 100644 --- a/Content.IntegrationTests/Tests/Cleanup/EuiManagerTest.cs +++ b/Content.IntegrationTests/Tests/Cleanup/EuiManagerTest.cs @@ -1,10 +1,7 @@ using System.Linq; -using System.Threading.Tasks; using Content.Server.Administration.UI; using Content.Server.EUI; -using NUnit.Framework; using Robust.Server.Player; -using Robust.Shared.IoC; namespace Content.IntegrationTests.Tests.Cleanup; @@ -14,9 +11,9 @@ public sealed class EuiManagerTest public async Task EuiManagerRecycleWithOpenWindowTest() { // Even though we are using the server EUI here, we actually want to see if the client EUIManager crashes - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{Dirty = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { Dirty = true }); var server = pairTracker.Pair.Server; var sPlayerManager = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/ClickableTest.cs b/Content.IntegrationTests/Tests/ClickableTest.cs index dcaf06829e3..2a88a181d9c 100644 --- a/Content.IntegrationTests/Tests/ClickableTest.cs +++ b/Content.IntegrationTests/Tests/ClickableTest.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading.Tasks; using Content.Client.Clickable; -using NUnit.Framework; using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Shared.GameObjects; @@ -61,7 +58,7 @@ public async Task Test(string prototype, float clickPosX, float clickPosY, await server.WaitPost(() => { var ent = serverEntManager.SpawnEntity(prototype, testMap.GridCoords); - serverEntManager.GetComponent(ent).WorldRotation = angle; + serverEntManager.System().SetWorldRotation(ent, angle); entity = ent; }); @@ -78,7 +75,7 @@ await client.WaitPost(() => // these tests currently all assume player eye is 0 eyeManager.CurrentEye.Rotation = 0; - var pos = clientEntManager.GetComponent(entity).WorldPosition; + var pos = clientEntManager.System().GetWorldPosition(entity); var clickable = clientEntManager.GetComponent(entity); hit = clickable.CheckClick(sprite, xformQuery.GetComponent(entity), xformQuery, (clickPosX, clickPosY) + pos, eye, out _, out _, out _); diff --git a/Content.IntegrationTests/Tests/Climbing/ClimbingTest.cs b/Content.IntegrationTests/Tests/Climbing/ClimbingTest.cs index 0eb2635025a..3212e51e3ec 100644 --- a/Content.IntegrationTests/Tests/Climbing/ClimbingTest.cs +++ b/Content.IntegrationTests/Tests/Climbing/ClimbingTest.cs @@ -1,11 +1,8 @@ #nullable enable -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Server.Climbing; using Content.Shared.Climbing; -using NUnit.Framework; using Robust.Shared.Maths; -using Robust.Shared.Physics.Components; namespace Content.IntegrationTests.Tests.Climbing; @@ -20,8 +17,11 @@ public async Task ClimbTableTest() // Player is not initially climbing anything. var comp = Comp(Player); - Assert.That(comp.IsClimbing, Is.False); - Assert.That(comp.DisabledFixtureMasks.Count, Is.EqualTo(0)); + Assert.Multiple(() => + { + Assert.That(comp.IsClimbing, Is.False); + Assert.That(comp.DisabledFixtureMasks, Has.Count.EqualTo(0)); + }); // Attempt (and fail) to walk past the table. await Move(DirectionFlag.East, 1f); @@ -33,16 +33,23 @@ public async Task ClimbTableTest() await AwaitDoAfters(); // Player should now be climbing - Assert.That(comp.IsClimbing, Is.True); - Assert.That(comp.DisabledFixtureMasks.Count, Is.GreaterThan(0)); + Assert.Multiple(() => + { + Assert.That(comp.IsClimbing, Is.True); + Assert.That(comp.DisabledFixtureMasks, Has.Count.GreaterThan(0)); + }); // Can now walk over the table. await Move(DirectionFlag.East, 1f); - Assert.That(Delta(), Is.LessThan(0)); - // After walking away from the table, player should have stopped climbing. - Assert.That(comp.IsClimbing, Is.False); - Assert.That(comp.DisabledFixtureMasks.Count, Is.EqualTo(0)); + Assert.Multiple(() => + { + Assert.That(Delta(), Is.LessThan(0)); + + // After walking away from the table, player should have stopped climbing. + Assert.That(comp.IsClimbing, Is.False); + Assert.That(comp.DisabledFixtureMasks, Has.Count.EqualTo(0)); + }); // Try to walk back to the other side (and fail). await Move(DirectionFlag.West, 1f); @@ -51,14 +58,20 @@ public async Task ClimbTableTest() // Start climbing await Server.WaitPost(() => sys.TryClimb(Player, Player, Target.Value)); await AwaitDoAfters(); - Assert.That(comp.IsClimbing, Is.True); - Assert.That(comp.DisabledFixtureMasks.Count, Is.GreaterThan(0)); + + Assert.Multiple(() => + { + Assert.That(comp.IsClimbing, Is.True); + Assert.That(comp.DisabledFixtureMasks, Has.Count.GreaterThan(0)); + }); // Walk past table and stop climbing again. await Move(DirectionFlag.West, 1f); - Assert.That(Delta(), Is.GreaterThan(0)); - Assert.That(comp.IsClimbing, Is.False); - Assert.That(comp.DisabledFixtureMasks.Count, Is.EqualTo(0)); + Assert.Multiple(() => + { + Assert.That(Delta(), Is.GreaterThan(0)); + Assert.That(comp.IsClimbing, Is.False); + Assert.That(comp.DisabledFixtureMasks, Has.Count.EqualTo(0)); + }); } } - diff --git a/Content.IntegrationTests/Tests/Commands/PardonCommand.cs b/Content.IntegrationTests/Tests/Commands/PardonCommand.cs index d7de02371da..d889840917f 100644 --- a/Content.IntegrationTests/Tests/Commands/PardonCommand.cs +++ b/Content.IntegrationTests/Tests/Commands/PardonCommand.cs @@ -1,8 +1,5 @@ -using System; using System.Linq; -using System.Threading.Tasks; using Content.Server.Database; -using NUnit.Framework; using Robust.Server.Console; using Robust.Server.Player; @@ -17,7 +14,7 @@ public sealed class PardonCommand [Test] public async Task PardonTest() { - await using var pairTracker = await PoolManager.GetServerClient(new (){Destructive = true}); + await using var pairTracker = await PoolManager.GetServerClient(new() { Destructive = true }); var server = pairTracker.Pair.Server; var sPlayerManager = server.ResolveDependency(); @@ -30,17 +27,23 @@ await server.WaitAssertion(async () => var clientId = clientSession.UserId; // No bans on record - Assert.That(await sDatabase.GetServerBanAsync(null, clientId, null), Is.Null); - Assert.That(await sDatabase.GetServerBanAsync(1), Is.Null); - Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Is.Empty); + Assert.Multiple(async () => + { + Assert.That(await sDatabase.GetServerBanAsync(null, clientId, null), Is.Null); + Assert.That(await sDatabase.GetServerBanAsync(1), Is.Null); + Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Is.Empty); + }); // Try to pardon a ban that does not exist sConsole.ExecuteCommand("pardon 1"); // Still no bans on record - Assert.That(await sDatabase.GetServerBanAsync(null, clientId, null), Is.Null); - Assert.That(await sDatabase.GetServerBanAsync(1), Is.Null); - Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Is.Empty); + Assert.Multiple(async () => + { + Assert.That(await sDatabase.GetServerBanAsync(null, clientId, null), Is.Null); + Assert.That(await sDatabase.GetServerBanAsync(1), Is.Null); + Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Is.Empty); + }); var banReason = "test"; @@ -48,9 +51,12 @@ await server.WaitAssertion(async () => sConsole.ExecuteCommand($"ban {clientSession.Name} {banReason} 1440"); // Should have one ban on record now - Assert.That(await sDatabase.GetServerBanAsync(null, clientId, null), Is.Not.Null); - Assert.That(await sDatabase.GetServerBanAsync(1), Is.Not.Null); - Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Has.Count.EqualTo(1)); + Assert.Multiple(async () => + { + Assert.That(await sDatabase.GetServerBanAsync(null, clientId, null), Is.Not.Null); + Assert.That(await sDatabase.GetServerBanAsync(1), Is.Not.Null); + Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Has.Count.EqualTo(1)); + }); // Try to pardon a ban that does not exist sConsole.ExecuteCommand("pardon 2"); @@ -59,22 +65,23 @@ await server.WaitAssertion(async () => Assert.That(await sDatabase.GetServerBanAsync(null, clientId, null), Is.Not.Null); var ban = await sDatabase.GetServerBanAsync(1); - Assert.That(ban, Is.Not.Null); - - Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Has.Count.EqualTo(1)); - - // Check that it matches - Assert.That(ban.Id, Is.EqualTo(1)); - Assert.That(ban.UserId, Is.EqualTo(clientId)); - Assert.That(ban.BanTime.UtcDateTime - DateTime.UtcNow, Is.LessThanOrEqualTo(MarginOfError)); - Assert.NotNull(ban.ExpirationTime); - Assert.That(ban.ExpirationTime.Value.UtcDateTime - DateTime.UtcNow.AddHours(24), Is.LessThanOrEqualTo(MarginOfError)); - Assert.That(ban.Reason, Is.EqualTo(banReason)); - - // Done through the console - Assert.That(ban.BanningAdmin, Is.Null); - - Assert.That(ban.Unban, Is.Null); + Assert.Multiple(async () => + { + Assert.That(ban, Is.Not.Null); + Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Has.Count.EqualTo(1)); + + // Check that it matches + Assert.That(ban.Id, Is.EqualTo(1)); + Assert.That(ban.UserId, Is.EqualTo(clientId)); + Assert.That(ban.BanTime.UtcDateTime - DateTime.UtcNow, Is.LessThanOrEqualTo(MarginOfError)); + Assert.That(ban.ExpirationTime, Is.Not.Null); + Assert.That(ban.ExpirationTime.Value.UtcDateTime - DateTime.UtcNow.AddHours(24), Is.LessThanOrEqualTo(MarginOfError)); + Assert.That(ban.Reason, Is.EqualTo(banReason)); + + // Done through the console + Assert.That(ban.BanningAdmin, Is.Null); + Assert.That(ban.Unban, Is.Null); + }); // Pardon the actual ban sConsole.ExecuteCommand("pardon 1"); @@ -84,42 +91,48 @@ await server.WaitAssertion(async () => // Direct id lookup returns a pardoned ban var pardonedBan = await sDatabase.GetServerBanAsync(1); - Assert.That(pardonedBan, Is.Not.Null); + Assert.Multiple(async () => + { + // Check that it matches + Assert.That(pardonedBan, Is.Not.Null); - // The list is still returned since that ignores pardons - Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Has.Count.EqualTo(1)); + // The list is still returned since that ignores pardons + Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Has.Count.EqualTo(1)); - // Check that it matches - Assert.That(pardonedBan.Id, Is.EqualTo(1)); - Assert.That(pardonedBan.UserId, Is.EqualTo(clientId)); - Assert.That(pardonedBan.BanTime.UtcDateTime - DateTime.UtcNow, Is.LessThanOrEqualTo(MarginOfError)); - Assert.NotNull(pardonedBan.ExpirationTime); - Assert.That(pardonedBan.ExpirationTime.Value.UtcDateTime - DateTime.UtcNow.AddHours(24), Is.LessThanOrEqualTo(MarginOfError)); - Assert.That(pardonedBan.Reason, Is.EqualTo(banReason)); + Assert.That(pardonedBan.Id, Is.EqualTo(1)); + Assert.That(pardonedBan.UserId, Is.EqualTo(clientId)); + Assert.That(pardonedBan.BanTime.UtcDateTime - DateTime.UtcNow, Is.LessThanOrEqualTo(MarginOfError)); + Assert.That(pardonedBan.ExpirationTime, Is.Not.Null); + Assert.That(pardonedBan.ExpirationTime.Value.UtcDateTime - DateTime.UtcNow.AddHours(24), Is.LessThanOrEqualTo(MarginOfError)); + Assert.That(pardonedBan.Reason, Is.EqualTo(banReason)); - // Done through the console - Assert.That(pardonedBan.BanningAdmin, Is.Null); + // Done through the console + Assert.That(pardonedBan.BanningAdmin, Is.Null); - Assert.That(pardonedBan.Unban, Is.Not.Null); - Assert.That(pardonedBan.Unban.BanId, Is.EqualTo(1)); + Assert.That(pardonedBan.Unban, Is.Not.Null); + Assert.That(pardonedBan.Unban.BanId, Is.EqualTo(1)); - // Done through the console - Assert.That(pardonedBan.Unban.UnbanningAdmin, Is.Null); + // Done through the console + Assert.That(pardonedBan.Unban.UnbanningAdmin, Is.Null); - Assert.That(pardonedBan.Unban.UnbanTime.UtcDateTime - DateTime.UtcNow, Is.LessThanOrEqualTo(MarginOfError)); + Assert.That(pardonedBan.Unban.UnbanTime.UtcDateTime - DateTime.UtcNow, Is.LessThanOrEqualTo(MarginOfError)); + }); // Try to pardon it again sConsole.ExecuteCommand("pardon 1"); // Nothing changes - // No bans should be returned - Assert.That(await sDatabase.GetServerBanAsync(null, clientId, null), Is.Null); + Assert.Multiple(async () => + { + // No bans should be returned + Assert.That(await sDatabase.GetServerBanAsync(null, clientId, null), Is.Null); - // Direct id lookup returns a pardoned ban - Assert.That(await sDatabase.GetServerBanAsync(1), Is.Not.Null); + // Direct id lookup returns a pardoned ban + Assert.That(await sDatabase.GetServerBanAsync(1), Is.Not.Null); - // The list is still returned since that ignores pardons - Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Has.Count.EqualTo(1)); + // The list is still returned since that ignores pardons + Assert.That(await sDatabase.GetServerBansAsync(null, clientId, null), Has.Count.EqualTo(1)); + }); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Commands/RejuvenateTest.cs b/Content.IntegrationTests/Tests/Commands/RejuvenateTest.cs index 1c72004920a..782189c5458 100644 --- a/Content.IntegrationTests/Tests/Commands/RejuvenateTest.cs +++ b/Content.IntegrationTests/Tests/Commands/RejuvenateTest.cs @@ -1,11 +1,9 @@ -using System.Threading.Tasks; -using Content.Server.Administration.Commands; +using Content.Server.Administration.Commands; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; using Content.Shared.Mobs.Components; using Content.Shared.Mobs.Systems; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Prototypes; @@ -34,7 +32,11 @@ public sealed class RejuvenateTest [Test] public async Task RejuvenateDeadTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var entManager = server.ResolveDependency(); var mapManager = server.ResolveDependency(); @@ -45,37 +47,50 @@ public async Task RejuvenateDeadTest() await server.WaitAssertion(() => { var human = entManager.SpawnEntity("DamageableDummy", MapCoordinates.Nullspace); + DamageableComponent damageable = null; + MobStateComponent mobState = null; // Sanity check - Assert.True(entManager.TryGetComponent(human, out DamageableComponent damageable)); - Assert.True(entManager.TryGetComponent(human, out MobStateComponent mobState)); - Assert.That(mobStateSystem.IsAlive(human, mobState), Is.True); - Assert.That(mobStateSystem.IsCritical(human, mobState), Is.False); - Assert.That(mobStateSystem.IsDead(human, mobState), Is.False); - Assert.That(mobStateSystem.IsIncapacitated(human, mobState), Is.False); + Assert.Multiple(() => + { + Assert.That(entManager.TryGetComponent(human, out damageable)); + Assert.That(entManager.TryGetComponent(human, out mobState)); + }); + Assert.Multiple(() => + { + Assert.That(mobStateSystem.IsAlive(human, mobState), Is.True); + Assert.That(mobStateSystem.IsCritical(human, mobState), Is.False); + Assert.That(mobStateSystem.IsDead(human, mobState), Is.False); + Assert.That(mobStateSystem.IsIncapacitated(human, mobState), Is.False); + }); // Kill the entity - DamageSpecifier damage = new(prototypeManager.Index("Toxin"), - FixedPoint2.New(10000000)); + DamageSpecifier damage = new(prototypeManager.Index("Toxin"), FixedPoint2.New(10000000)); damSystem.TryChangeDamage(human, damage, true); // Check that it is dead - Assert.That(mobStateSystem.IsAlive(human, mobState), Is.False); - Assert.That(mobStateSystem.IsCritical(human, mobState), Is.False); - Assert.That(mobStateSystem.IsDead(human, mobState), Is.True); - Assert.That(mobStateSystem.IsIncapacitated(human, mobState), Is.True); + Assert.Multiple(() => + { + Assert.That(mobStateSystem.IsAlive(human, mobState), Is.False); + Assert.That(mobStateSystem.IsCritical(human, mobState), Is.False); + Assert.That(mobStateSystem.IsDead(human, mobState), Is.True); + Assert.That(mobStateSystem.IsIncapacitated(human, mobState), Is.True); + }); // Rejuvenate them RejuvenateCommand.PerformRejuvenate(human); // Check that it is alive and with no damage - Assert.That(mobStateSystem.IsAlive(human, mobState), Is.True); - Assert.That(mobStateSystem.IsCritical(human, mobState), Is.False); - Assert.That(mobStateSystem.IsDead(human, mobState), Is.False); - Assert.That(mobStateSystem.IsIncapacitated(human, mobState), Is.False); + Assert.Multiple(() => + { + Assert.That(mobStateSystem.IsAlive(human, mobState), Is.True); + Assert.That(mobStateSystem.IsCritical(human, mobState), Is.False); + Assert.That(mobStateSystem.IsDead(human, mobState), Is.False); + Assert.That(mobStateSystem.IsIncapacitated(human, mobState), Is.False); - Assert.That(damageable.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); + Assert.That(damageable.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); + }); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Commands/RestartRoundTest.cs b/Content.IntegrationTests/Tests/Commands/RestartRoundTest.cs index 33e83714fbf..2efe022c5e8 100644 --- a/Content.IntegrationTests/Tests/Commands/RestartRoundTest.cs +++ b/Content.IntegrationTests/Tests/Commands/RestartRoundTest.cs @@ -1,9 +1,6 @@ -using System; -using System.Threading.Tasks; using Content.Server.GameTicking; using Content.Server.GameTicking.Commands; using Content.Shared.CCVar; -using NUnit.Framework; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; using Robust.Shared.Timing; @@ -19,7 +16,7 @@ public sealed class RestartRoundNowTest [TestCase(false)] public async Task RestartRoundAfterStart(bool lobbyEnabled) { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings(){Dirty = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings() { Dirty = true }); var server = pairTracker.Pair.Server; var configManager = server.ResolveDependency(); @@ -54,7 +51,7 @@ await server.WaitAssertion(() => { var tickAfterRestart = entityManager.CurrentTick; - Assert.That(tickBeforeRestart < tickAfterRestart); + Assert.That(tickBeforeRestart, Is.LessThan(tickAfterRestart)); }); await PoolManager.RunTicksSync(pairTracker.Pair, 5); diff --git a/Content.IntegrationTests/Tests/Construction/ConstructionActionValid.cs b/Content.IntegrationTests/Tests/Construction/ConstructionActionValid.cs index 774b01fd807..e6e7ea0d339 100644 --- a/Content.IntegrationTests/Tests/Construction/ConstructionActionValid.cs +++ b/Content.IntegrationTests/Tests/Construction/ConstructionActionValid.cs @@ -1,9 +1,7 @@ using System.Text; -using System.Threading.Tasks; using Content.Server.Construction.Completions; using Content.Shared.Construction; using Content.Shared.Construction.Prototypes; -using NUnit.Framework; using Robust.Shared.Prototypes; namespace Content.IntegrationTests.Tests.Construction @@ -49,7 +47,7 @@ private bool IsValid(IGraphAction action, IPrototypeManager protoMan, out string [Test] public async Task ConstructionGraphSpawnPrototypeValid() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoMan = server.ResolveDependency(); @@ -89,7 +87,7 @@ public async Task ConstructionGraphSpawnPrototypeValid() [Test] public async Task ConstructionGraphNodeEntityPrototypeValid() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoMan = server.ResolveDependency(); @@ -115,7 +113,7 @@ public async Task ConstructionGraphNodeEntityPrototypeValid() [Test] public async Task ConstructionGraphEdgeValid() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoMan = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/Construction/ConstructionPrototypeTest.cs b/Content.IntegrationTests/Tests/Construction/ConstructionPrototypeTest.cs index d9021a0a277..f23e2932488 100644 --- a/Content.IntegrationTests/Tests/Construction/ConstructionPrototypeTest.cs +++ b/Content.IntegrationTests/Tests/Construction/ConstructionPrototypeTest.cs @@ -1,11 +1,9 @@ using Content.Server.Construction.Components; using Content.Shared.Construction.Prototypes; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Prototypes; -using System.Threading.Tasks; namespace Content.IntegrationTests.Tests.Construction { @@ -22,7 +20,7 @@ public sealed class ConstructionPrototypeTest [Test] public async Task TestStartNodeValid() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var entMan = server.ResolveDependency(); @@ -54,7 +52,7 @@ await server.WaitAssertion(() => [Test] public async Task TestStartIsValid() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoMan = server.ResolveDependency(); @@ -72,7 +70,7 @@ public async Task TestStartIsValid() [Test] public async Task TestTargetIsValid() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoMan = server.ResolveDependency(); @@ -121,7 +119,7 @@ public async Task DeconstructionIsValid() [Test] public async Task TestStartReachesValidTarget() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoMan = server.ResolveDependency(); @@ -131,12 +129,15 @@ public async Task TestStartReachesValidTarget() var start = proto.StartNode; var target = proto.TargetNode; var graph = protoMan.Index(proto.Graph); + +#pragma warning disable NUnit2045 // Interdependent assertions. Assert.That(graph.TryPath(start, target, out var path), $"Unable to find path from \"{start}\" to \"{target}\" on graph \"{graph.ID}\""); - Assert.That(path!.Length, Is.GreaterThanOrEqualTo(1), $"Unable to find path from \"{start}\" to \"{target}\" on graph \"{graph.ID}\"."); + Assert.That(path, Has.Length.GreaterThanOrEqualTo(1), $"Unable to find path from \"{start}\" to \"{target}\" on graph \"{graph.ID}\"."); var next = path[0]; Assert.That(next.Entity, Is.Not.Null, $"The next node ({next.Name}) in the path from the start node ({start}) to the target node ({target}) must specify an entity! Graph: {graph.ID}"); Assert.That(protoMan.TryIndex(next.Entity, out EntityPrototype entity), $"The next node ({next.Name}) in the path from the start node ({start}) to the target node ({target}) specified an invalid entity prototype ({next.Entity})"); Assert.That(entity.Components.ContainsKey("Construction"), $"The next node ({next.Name}) in the path from the start node ({start}) to the target node ({target}) specified an entity prototype ({next.Entity}) without a ConstructionComponent."); +#pragma warning restore NUnit2045 } await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Construction/Interaction/ComputerContruction.cs b/Content.IntegrationTests/Tests/Construction/Interaction/ComputerContruction.cs index aade73e7018..87f3c06c12b 100644 --- a/Content.IntegrationTests/Tests/Construction/Interaction/ComputerContruction.cs +++ b/Content.IntegrationTests/Tests/Construction/Interaction/ComputerContruction.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Construction.Interaction; diff --git a/Content.IntegrationTests/Tests/Construction/Interaction/CraftingTests.cs b/Content.IntegrationTests/Tests/Construction/Interaction/CraftingTests.cs index 698f81b1226..5c48703dff6 100644 --- a/Content.IntegrationTests/Tests/Construction/Interaction/CraftingTests.cs +++ b/Content.IntegrationTests/Tests/Construction/Interaction/CraftingTests.cs @@ -1,8 +1,6 @@ using System.Linq; -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Shared.Stacks; -using NUnit.Framework; using Robust.Shared.Containers; namespace Content.IntegrationTests.Tests.Construction.Interaction; @@ -80,48 +78,67 @@ public async Task CancelCraft() await RunTicks(5); var sys = SEntMan.System(); - Assert.That(sys.IsEntityInContainer(rods), Is.False); - Assert.That(sys.IsEntityInContainer(wires), Is.False); - Assert.That(sys.IsEntityInContainer(shard), Is.False); - + Assert.Multiple(() => + { + Assert.That(sys.IsEntityInContainer(rods), Is.False); + Assert.That(sys.IsEntityInContainer(wires), Is.False); + Assert.That(sys.IsEntityInContainer(shard), Is.False); + }); + +#pragma warning disable CS4014 // Legacy construction code uses DoAfterAwait. If we await it we will be waiting forever. await Server.WaitPost(() => SConstruction.TryStartItemConstruction(Spear, Player)); +#pragma warning restore CS4014 await RunTicks(1); // DoAfter is in progress. Entity not spawned, stacks have been split and someingredients are in a container. - Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1)); - Assert.That(sys.IsEntityInContainer(shard), Is.True); - Assert.That(sys.IsEntityInContainer(rods), Is.False); - Assert.That(sys.IsEntityInContainer(wires), Is.False); - Assert.That(rodStack.Count, Is.EqualTo(8)); - Assert.That(wireStack.Count, Is.EqualTo(8)); - await FindEntity(Spear, shouldSucceed: false); + Assert.Multiple(async () => + { + Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1)); + Assert.That(sys.IsEntityInContainer(shard), Is.True); + Assert.That(sys.IsEntityInContainer(rods), Is.False); + Assert.That(sys.IsEntityInContainer(wires), Is.False); + Assert.That(rodStack, Has.Count.EqualTo(8)); + Assert.That(wireStack, Has.Count.EqualTo(8)); + + await FindEntity(Spear, shouldSucceed: false); + }); // Cancel the DoAfter. Should drop ingredients to the floor. await CancelDoAfters(); - Assert.That(sys.IsEntityInContainer(rods), Is.False); - Assert.That(sys.IsEntityInContainer(wires), Is.False); - Assert.That(sys.IsEntityInContainer(shard), Is.False); - await FindEntity(Spear, shouldSucceed: false); - await AssertEntityLookup((Rod, 10), (Cable, 10), (ShardGlass, 1)); + Assert.Multiple(async () => + { + Assert.That(sys.IsEntityInContainer(rods), Is.False); + Assert.That(sys.IsEntityInContainer(wires), Is.False); + Assert.That(sys.IsEntityInContainer(shard), Is.False); + await FindEntity(Spear, shouldSucceed: false); + await AssertEntityLookup((Rod, 10), (Cable, 10), (ShardGlass, 1)); + }); // Re-attempt the do-after +#pragma warning disable CS4014 // Legacy construction code uses DoAfterAwait. See above. await Server.WaitPost(() => SConstruction.TryStartItemConstruction(Spear, Player)); +#pragma warning restore CS4014 await RunTicks(1); // DoAfter is in progress. Entity not spawned, ingredients are in a container. - Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1)); - Assert.That(sys.IsEntityInContainer(shard), Is.True); - await FindEntity(Spear, shouldSucceed: false); + Assert.Multiple(async () => + { + Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1)); + Assert.That(sys.IsEntityInContainer(shard), Is.True); + await FindEntity(Spear, shouldSucceed: false); + }); // Finish the DoAfter await AwaitDoAfters(); // Spear has been crafted. Rods and wires are no longer contained. Glass has been consumed. - await FindEntity(Spear); - Assert.That(sys.IsEntityInContainer(rods), Is.False); - Assert.That(sys.IsEntityInContainer(wires), Is.False); - Assert.That(SEntMan.Deleted(shard)); + Assert.Multiple(async () => + { + await FindEntity(Spear); + Assert.That(sys.IsEntityInContainer(rods), Is.False); + Assert.That(sys.IsEntityInContainer(wires), Is.False); + Assert.That(SEntMan.Deleted(shard)); + }); } #endif } - diff --git a/Content.IntegrationTests/Tests/Construction/Interaction/GrilleWindowConstruction.cs b/Content.IntegrationTests/Tests/Construction/Interaction/GrilleWindowConstruction.cs index 69ea71f10e2..1a2f4bcda14 100644 --- a/Content.IntegrationTests/Tests/Construction/Interaction/GrilleWindowConstruction.cs +++ b/Content.IntegrationTests/Tests/Construction/Interaction/GrilleWindowConstruction.cs @@ -1,7 +1,5 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Shared.Construction.Prototypes; -using NUnit.Framework; using Robust.Shared.Maths; namespace Content.IntegrationTests.Tests.Construction.Interaction; diff --git a/Content.IntegrationTests/Tests/Construction/Interaction/MachineConstruction.cs b/Content.IntegrationTests/Tests/Construction/Interaction/MachineConstruction.cs index 6f0478a6521..0382912ccbb 100644 --- a/Content.IntegrationTests/Tests/Construction/Interaction/MachineConstruction.cs +++ b/Content.IntegrationTests/Tests/Construction/Interaction/MachineConstruction.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Construction.Interaction; diff --git a/Content.IntegrationTests/Tests/Construction/Interaction/PanelScrewing.cs b/Content.IntegrationTests/Tests/Construction/Interaction/PanelScrewing.cs index f6ca9ec72e7..2f69f3abea5 100644 --- a/Content.IntegrationTests/Tests/Construction/Interaction/PanelScrewing.cs +++ b/Content.IntegrationTests/Tests/Construction/Interaction/PanelScrewing.cs @@ -1,7 +1,5 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Shared.Wires; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Construction.Interaction; diff --git a/Content.IntegrationTests/Tests/Construction/Interaction/PlaceableDeconstruction.cs b/Content.IntegrationTests/Tests/Construction/Interaction/PlaceableDeconstruction.cs index 1ce57422dd0..bc0cb9bcef3 100644 --- a/Content.IntegrationTests/Tests/Construction/Interaction/PlaceableDeconstruction.cs +++ b/Content.IntegrationTests/Tests/Construction/Interaction/PlaceableDeconstruction.cs @@ -1,7 +1,5 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Shared.Placeable; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Construction.Interaction; diff --git a/Content.IntegrationTests/Tests/Construction/Interaction/WallConstruction.cs b/Content.IntegrationTests/Tests/Construction/Interaction/WallConstruction.cs index 5cdb00ce95c..05cf8cac1b8 100644 --- a/Content.IntegrationTests/Tests/Construction/Interaction/WallConstruction.cs +++ b/Content.IntegrationTests/Tests/Construction/Interaction/WallConstruction.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Construction.Interaction; @@ -15,10 +13,10 @@ public async Task ConstructWall() { await StartConstruction(Wall); await Interact(Steel, 2); - Assert.IsNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Null); AssertPrototype(Girder); await Interact(Steel, 2); - Assert.IsNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Null); AssertPrototype(WallSolid); } @@ -33,4 +31,3 @@ public async Task DeconstructWall() await AssertEntityLookup((Steel, 4)); } } - diff --git a/Content.IntegrationTests/Tests/Construction/Interaction/WindowConstruction.cs b/Content.IntegrationTests/Tests/Construction/Interaction/WindowConstruction.cs index 60deadcaeea..2be20202775 100644 --- a/Content.IntegrationTests/Tests/Construction/Interaction/WindowConstruction.cs +++ b/Content.IntegrationTests/Tests/Construction/Interaction/WindowConstruction.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Construction.Interaction; diff --git a/Content.IntegrationTests/Tests/Construction/Interaction/WindowRepair.cs b/Content.IntegrationTests/Tests/Construction/Interaction/WindowRepair.cs index 0c104a41be3..e04fbfd1429 100644 --- a/Content.IntegrationTests/Tests/Construction/Interaction/WindowRepair.cs +++ b/Content.IntegrationTests/Tests/Construction/Interaction/WindowRepair.cs @@ -1,9 +1,7 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; -using NUnit.Framework; using Robust.Shared.Prototypes; namespace Content.IntegrationTests.Tests.Construction.Interaction; diff --git a/Content.IntegrationTests/Tests/ContainerOcclusionTest.cs b/Content.IntegrationTests/Tests/ContainerOcclusionTest.cs index 0ea036d8e12..089950aa192 100644 --- a/Content.IntegrationTests/Tests/ContainerOcclusionTest.cs +++ b/Content.IntegrationTests/Tests/ContainerOcclusionTest.cs @@ -1,11 +1,6 @@ -using System.Linq; -using System.Threading.Tasks; -using Content.Server.Storage.Components; using Content.Server.Storage.EntitySystems; -using NUnit.Framework; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -37,7 +32,7 @@ public sealed class ContainerOcclusionTest [Test] public async Task TestA() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { ExtraPrototypes = Prototypes }); var s = pairTracker.Pair.Server; var c = pairTracker.Pair.Client; @@ -64,8 +59,11 @@ await c.WaitAssertion(() => { var sprite = cEntities.GetComponent(dummy); var light = cEntities.GetComponent(dummy); - Assert.True(sprite.ContainerOccluded); - Assert.True(light.ContainerOccluded); + Assert.Multiple(() => + { + Assert.That(sprite.ContainerOccluded); + Assert.That(light.ContainerOccluded); + }); }); await pairTracker.CleanReturnAsync(); @@ -74,7 +72,7 @@ await c.WaitAssertion(() => [Test] public async Task TestB() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { ExtraPrototypes = Prototypes }); var s = pairTracker.Pair.Server; var c = pairTracker.Pair.Client; @@ -101,8 +99,11 @@ await c.WaitAssertion(() => { var sprite = cEntities.GetComponent(dummy); var light = cEntities.GetComponent(dummy); - Assert.False(sprite.ContainerOccluded); - Assert.False(light.ContainerOccluded); + Assert.Multiple(() => + { + Assert.That(sprite.ContainerOccluded, Is.False); + Assert.That(light.ContainerOccluded, Is.False); + }); }); await pairTracker.CleanReturnAsync(); @@ -111,7 +112,7 @@ await c.WaitAssertion(() => [Test] public async Task TestAb() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { ExtraPrototypes = Prototypes }); var s = pairTracker.Pair.Server; var c = pairTracker.Pair.Client; @@ -140,8 +141,11 @@ await c.WaitAssertion(() => { var sprite = cEntities.GetComponent(dummy); var light = cEntities.GetComponent(dummy); - Assert.True(sprite.ContainerOccluded); - Assert.True(light.ContainerOccluded); + Assert.Multiple(() => + { + Assert.That(sprite.ContainerOccluded); + Assert.That(light.ContainerOccluded); + }); }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/Damageable/DamageSpecifierTest.cs b/Content.IntegrationTests/Tests/Damageable/DamageSpecifierTest.cs index 67658d18ce7..41d17ddedae 100644 --- a/Content.IntegrationTests/Tests/Damageable/DamageSpecifierTest.cs +++ b/Content.IntegrationTests/Tests/Damageable/DamageSpecifierTest.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using Content.Shared.Damage; using Content.Shared.FixedPoint; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Damageable; @@ -23,9 +22,12 @@ public void TestDamageSpecifierOperations() DamageSpecifier output4 = new() { DamageDict = _output4 }; DamageSpecifier output5 = new() { DamageDict = _output5 }; - Assert.That((-input1).Equals(output1)); - Assert.That((input1 / 2).Equals(output2)); - Assert.That((input1 * 2).Equals(output3)); + Assert.Multiple(() => + { + Assert.That((-input1).Equals(output1)); + Assert.That((input1 / 2).Equals(output2)); + Assert.That((input1 * 2).Equals(output3)); + }); var difference = (input1 - input2); Assert.That(difference.Equals(output4)); diff --git a/Content.IntegrationTests/Tests/Damageable/DamageableTest.cs b/Content.IntegrationTests/Tests/Damageable/DamageableTest.cs index 9920e15e021..7099eb4326a 100644 --- a/Content.IntegrationTests/Tests/Damageable/DamageableTest.cs +++ b/Content.IntegrationTests/Tests/Damageable/DamageableTest.cs @@ -1,9 +1,7 @@ using System.Linq; -using System.Threading.Tasks; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -74,7 +72,11 @@ public sealed class DamageableTest [Test] public async Task TestDamageableComponents() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var sEntityManager = server.ResolveDependency(); @@ -97,7 +99,7 @@ public async Task TestDamageableComponents() DamageTypePrototype type3b = default!; DamageTypePrototype type3c = default!; - FixedPoint2 typeDamage, groupDamage; + FixedPoint2 typeDamage; await server.WaitPost(() => { @@ -127,74 +129,94 @@ await server.WaitAssertion(() => var uid = sDamageableEntity; // Check that the correct types are supported. - Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type1.ID), Is.False); - Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type2a.ID), Is.True); - Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type2b.ID), Is.False); - Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type3a.ID), Is.True); - Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type3b.ID), Is.True); - Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type3c.ID), Is.True); + Assert.Multiple(() => + { + Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type1.ID), Is.False); + Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type2a.ID), Is.True); + Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type2b.ID), Is.False); + Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type3a.ID), Is.True); + Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type3b.ID), Is.True); + Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type3c.ID), Is.True); + }); // Check that damage is evenly distributed over a group if its a nice multiple var types = group3.DamageTypes; - var damageToDeal = FixedPoint2.New(types.Count() * 5); + var damageToDeal = FixedPoint2.New(types.Count * 5); DamageSpecifier damage = new(group3, damageToDeal); sDamageableSystem.TryChangeDamage(uid, damage, true); - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(damageToDeal)); - Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(damageToDeal)); - foreach (var type in types) + Assert.Multiple(() => { - Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type, out typeDamage)); - Assert.That(typeDamage, Is.EqualTo(damageToDeal / types.Count())); - } + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(damageToDeal)); + Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(damageToDeal)); + foreach (var type in types) + { + Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type, out typeDamage)); + Assert.That(typeDamage, Is.EqualTo(damageToDeal / types.Count)); + } + }); // Heal sDamageableSystem.TryChangeDamage(uid, -damage); - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); - Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(FixedPoint2.Zero)); - foreach (var type in types) + Assert.Multiple(() => { - Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type, out typeDamage)); - Assert.That(typeDamage, Is.EqualTo(FixedPoint2.Zero)); - } + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); + Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(FixedPoint2.Zero)); + foreach (var type in types) + { + Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type, out typeDamage)); + Assert.That(typeDamage, Is.EqualTo(FixedPoint2.Zero)); + } + }); // Check that damage works properly if it is NOT perfectly divisible among group members types = group3.DamageTypes; - damageToDeal = FixedPoint2.New(types.Count() * 5 - 1); + damageToDeal = FixedPoint2.New(types.Count * 5 - 1); damage = new DamageSpecifier(group3, damageToDeal); sDamageableSystem.TryChangeDamage(uid, damage, true); - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(damageToDeal)); - Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(damageToDeal)); - Assert.That(sDamageableComponent.Damage.DamageDict[type3a.ID], Is.EqualTo(damageToDeal / types.Count())); - Assert.That(sDamageableComponent.Damage.DamageDict[type3b.ID], Is.EqualTo(damageToDeal / types.Count())); + Assert.Multiple(() => + { + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(damageToDeal)); + Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(damageToDeal)); + Assert.That(sDamageableComponent.Damage.DamageDict[type3a.ID], Is.EqualTo(damageToDeal / types.Count)); + Assert.That(sDamageableComponent.Damage.DamageDict[type3b.ID], Is.EqualTo(damageToDeal / types.Count)); - // last one will get 0.01 less, since its not perfectly divisble by 3 - Assert.That(sDamageableComponent.Damage.DamageDict[type3c.ID], Is.EqualTo(damageToDeal / types.Count() - 0.01)); + // last one will get 0.01 less, since its not perfectly divisble by 3 + Assert.That(sDamageableComponent.Damage.DamageDict[type3c.ID], Is.EqualTo(damageToDeal / types.Count - 0.01)); + }); // Heal sDamageableSystem.TryChangeDamage(uid, -damage); - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); - Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(FixedPoint2.Zero)); - foreach (var type in types) - { - Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type, out typeDamage)); - Assert.That(typeDamage, Is.EqualTo(FixedPoint2.Zero)); - } - // Test that unsupported groups return false when setting/getting damage (and don't change damage) - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); + Assert.Multiple(() => + { + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); + Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(FixedPoint2.Zero)); + foreach (var type in types) + { + Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type, out typeDamage)); + Assert.That(typeDamage, Is.EqualTo(FixedPoint2.Zero)); + } + + // Test that unsupported groups return false when setting/getting damage (and don't change damage) + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); + }); damage = new DamageSpecifier(group1, FixedPoint2.New(10)) + new DamageSpecifier(type2b, FixedPoint2.New(10)); sDamageableSystem.TryChangeDamage(uid, damage, true); - Assert.That(sDamageableComponent.DamagePerGroup.TryGetValue(group1.ID, out groupDamage), Is.False); - Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type1.ID, out typeDamage), Is.False); - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); + + Assert.Multiple(() => + { + Assert.That(sDamageableComponent.DamagePerGroup.TryGetValue(group1.ID, out _), Is.False); + Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type1.ID, out typeDamage), Is.False); + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); + }); // Test SetAll function sDamageableSystem.SetAllDamage(sDamageableEntity, sDamageableComponent, 10); - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(10 * sDamageableComponent.Damage.DamageDict.Count()))); + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(10 * sDamageableComponent.Damage.DamageDict.Count))); sDamageableSystem.SetAllDamage(sDamageableEntity, sDamageableComponent, 0); Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero)); @@ -202,9 +224,13 @@ await server.WaitAssertion(() => sDamageableSystem.TryChangeDamage(uid, new DamageSpecifier(type3a, 5)); sDamageableSystem.TryChangeDamage(uid, new DamageSpecifier(type3b, 7)); sDamageableSystem.TryChangeDamage(uid, new DamageSpecifier(group3, -11)); - Assert.That(sDamageableComponent.Damage.DamageDict[type3a.ID], Is.EqualTo(FixedPoint2.New(1.33))); - Assert.That(sDamageableComponent.Damage.DamageDict[type3b.ID], Is.EqualTo(FixedPoint2.New(3.33))); - Assert.That(sDamageableComponent.Damage.DamageDict[type3c.ID], Is.EqualTo(FixedPoint2.New(0))); + + Assert.Multiple(() => + { + Assert.That(sDamageableComponent.Damage.DamageDict[type3a.ID], Is.EqualTo(FixedPoint2.New(1.33))); + Assert.That(sDamageableComponent.Damage.DamageDict[type3b.ID], Is.EqualTo(FixedPoint2.New(3.33))); + Assert.That(sDamageableComponent.Damage.DamageDict[type3c.ID], Is.EqualTo(FixedPoint2.New(0))); + }); // Test Over-Healing sDamageableSystem.TryChangeDamage(uid, new DamageSpecifier(group3, FixedPoint2.New(-100))); diff --git a/Content.IntegrationTests/Tests/DeleteInventoryTest.cs b/Content.IntegrationTests/Tests/DeleteInventoryTest.cs index d1d557964b4..af897a611ee 100644 --- a/Content.IntegrationTests/Tests/DeleteInventoryTest.cs +++ b/Content.IntegrationTests/Tests/DeleteInventoryTest.cs @@ -1,11 +1,8 @@ -using System.Threading.Tasks; using Content.Shared.Clothing.Components; using Content.Shared.Clothing.EntitySystems; using Content.Shared.Inventory; -using NUnit.Framework; using Robust.Shared.Containers; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; namespace Content.IntegrationTests.Tests { @@ -17,7 +14,7 @@ public sealed class DeleteInventoryTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); var entMgr = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/Destructible/DestructibleDamageGroupTest.cs b/Content.IntegrationTests/Tests/Destructible/DestructibleDamageGroupTest.cs index aa54ad5a389..8b5452a507e 100644 --- a/Content.IntegrationTests/Tests/Destructible/DestructibleDamageGroupTest.cs +++ b/Content.IntegrationTests/Tests/Destructible/DestructibleDamageGroupTest.cs @@ -1,9 +1,7 @@ -using System.Threading.Tasks; using Content.Server.Destructible.Thresholds.Triggers; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -20,7 +18,11 @@ public sealed class DestructibleDamageGroupTest [Test] public async Task AndTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -51,7 +53,7 @@ await server.WaitPost(() => await server.WaitAssertion(() => { - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); }); await server.WaitAssertion(() => @@ -66,34 +68,40 @@ await server.WaitAssertion(() => sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage, true); // No thresholds reached yet, the earliest one is at 10 damage - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise brute damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage, true); // No threshold reached, burn needs to be 10 as well - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise burn damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, burnDamage * 2, true); // One threshold reached, brute 10 + burn 10 - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); // Threshold brute 10 + burn 10 var msg = sTestThresholdListenerSystem.ThresholdsReached[0]; var threshold = msg.Threshold; // Check that it matches the YAML prototype - Assert.That(threshold.Behaviors, Is.Empty); - Assert.NotNull(threshold.Trigger); - Assert.That(threshold.Triggered, Is.True); - Assert.IsInstanceOf(threshold.Trigger); + Assert.Multiple(() => + { + Assert.That(threshold.Behaviors, Is.Empty); + Assert.That(threshold.Trigger, Is.Not.Null); + Assert.That(threshold.Triggered, Is.True); + Assert.That(threshold.Trigger, Is.InstanceOf()); + }); var trigger = (AndTrigger) threshold.Trigger; - Assert.IsInstanceOf(trigger.Triggers[0]); - Assert.IsInstanceOf(trigger.Triggers[1]); + Assert.Multiple(() => + { + Assert.That(trigger.Triggers[0], Is.InstanceOf()); + Assert.That(trigger.Triggers[1], Is.InstanceOf()); + }); sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -101,26 +109,29 @@ await server.WaitAssertion(() => sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * 2, true); // No new thresholds reached - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise burn damage to 20 sDamageableSystem.TryChangeDamage(sDestructibleEntity, burnDamage * 2, true); // No new thresholds reached - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Lower brute damage to 0 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * -10); - Assert.That(sDamageableComponent.TotalDamage,Is.EqualTo(FixedPoint2.New(20))); + Assert.Multiple(() => + { + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(20))); - // No new thresholds reached, healing should not trigger it - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + // No new thresholds reached, healing should not trigger it + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); + }); // Raise brute damage back up to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * 2, true); // 10 brute + 10 burn threshold reached, brute was healed and brought back to its threshold amount and slash stayed the same - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -128,34 +139,40 @@ await server.WaitAssertion(() => sDamageableSystem.SetAllDamage(sDestructibleEntity, sDamageableComponent, 0); // No new thresholds reached, healing should not trigger it - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise brute damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * 2, true); // No new thresholds reached - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise burn damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, burnDamage * 2, true); // Both classes of damage were healed and then raised again, the threshold should have been reached as triggers once is default false - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); // Threshold brute 10 + burn 10 msg = sTestThresholdListenerSystem.ThresholdsReached[0]; threshold = msg.Threshold; // Check that it matches the YAML prototype - Assert.That(threshold.Behaviors, Is.Empty); - Assert.NotNull(threshold.Trigger); - Assert.That(threshold.Triggered, Is.True); - Assert.IsInstanceOf(threshold.Trigger); + Assert.Multiple(() => + { + Assert.That(threshold.Behaviors, Is.Empty); + Assert.That(threshold.Trigger, Is.Not.Null); + Assert.That(threshold.Triggered, Is.True); + Assert.That(threshold.Trigger, Is.InstanceOf()); + }); trigger = (AndTrigger) threshold.Trigger; - Assert.IsInstanceOf(trigger.Triggers[0]); - Assert.IsInstanceOf(trigger.Triggers[1]); + Assert.Multiple(() => + { + Assert.That(trigger.Triggers[0], Is.InstanceOf()); + Assert.That(trigger.Triggers[1], Is.InstanceOf()); + }); sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -166,19 +183,19 @@ await server.WaitAssertion(() => sDamageableSystem.SetAllDamage(sDestructibleEntity, sDamageableComponent, 0); // No new thresholds reached from healing - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise brute damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * 2, true); // No new thresholds reached - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise burn damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, burnDamage * 2, true); // No new thresholds reached as triggers once is set to true and it already triggered before - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Destructible/DestructibleDamageTypeTest.cs b/Content.IntegrationTests/Tests/Destructible/DestructibleDamageTypeTest.cs index 3cc917add90..8352585a393 100644 --- a/Content.IntegrationTests/Tests/Destructible/DestructibleDamageTypeTest.cs +++ b/Content.IntegrationTests/Tests/Destructible/DestructibleDamageTypeTest.cs @@ -1,11 +1,7 @@ -using System.Threading.Tasks; using Content.Server.Destructible.Thresholds.Triggers; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Map; using Robust.Shared.Prototypes; using static Content.IntegrationTests.Tests.Destructible.DestructibleTestPrototypes; @@ -19,7 +15,11 @@ public sealed class DestructibleDamageTypeTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -48,7 +48,7 @@ await server.WaitPost(() => await server.WaitAssertion(() => { - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); }); await server.WaitAssertion(() => @@ -56,41 +56,47 @@ await server.WaitAssertion(() => var bluntDamageType = protoManager.Index("TestBlunt"); var slashDamageType = protoManager.Index("TestSlash"); - var bluntDamage = new DamageSpecifier(bluntDamageType,5); - var slashDamage = new DamageSpecifier(slashDamageType,5); + var bluntDamage = new DamageSpecifier(bluntDamageType, 5); + var slashDamage = new DamageSpecifier(slashDamageType, 5); // Raise blunt damage to 5 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // No thresholds reached yet, the earliest one is at 10 damage - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise blunt damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // No threshold reached, slash needs to be 10 as well - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise slash damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true); // One threshold reached, blunt 10 + slash 10 - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); // Threshold blunt 10 + slash 10 var msg = sTestThresholdListenerSystem.ThresholdsReached[0]; var threshold = msg.Threshold; // Check that it matches the YAML prototype - Assert.That(threshold.Behaviors, Is.Empty); - Assert.NotNull(threshold.Trigger); - Assert.That(threshold.Triggered, Is.True); - Assert.IsInstanceOf(threshold.Trigger); + Assert.Multiple(() => + { + Assert.That(threshold.Behaviors, Is.Empty); + Assert.That(threshold.Trigger, Is.Not.Null); + Assert.That(threshold.Triggered, Is.True); + Assert.That(threshold.Trigger, Is.InstanceOf()); + }); var trigger = (AndTrigger) threshold.Trigger; - Assert.IsInstanceOf(trigger.Triggers[0]); - Assert.IsInstanceOf(trigger.Triggers[1]); + Assert.Multiple(() => + { + Assert.That(trigger.Triggers[0], Is.InstanceOf()); + Assert.That(trigger.Triggers[1], Is.InstanceOf()); + }); sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -98,25 +104,25 @@ await server.WaitAssertion(() => sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true); // No new thresholds reached - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise slash damage to 20 sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true); // No new thresholds reached - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Lower blunt damage to 0 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * -4, true); // No new thresholds reached, healing should not trigger it - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise blunt damage back up to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true); // 10 blunt + 10 slash threshold reached, blunt was healed and brought back to its threshold amount and slash stayed the same - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -125,34 +131,40 @@ await server.WaitAssertion(() => sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * -4, true); // No new thresholds reached, healing should not trigger it - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise blunt damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true); // No new thresholds reached - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise slash damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true); // Both types of damage were healed and then raised again, the threshold should have been reached as triggers once is default false - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); // Threshold blunt 10 + slash 10 msg = sTestThresholdListenerSystem.ThresholdsReached[0]; threshold = msg.Threshold; // Check that it matches the YAML prototype - Assert.That(threshold.Behaviors, Is.Empty); - Assert.NotNull(threshold.Trigger); - Assert.That(threshold.Triggered, Is.True); - Assert.IsInstanceOf(threshold.Trigger); + Assert.Multiple(() => + { + Assert.That(threshold.Behaviors, Is.Empty); + Assert.That(threshold.Trigger, Is.Not.Null); + Assert.That(threshold.Triggered, Is.True); + Assert.That(threshold.Trigger, Is.InstanceOf()); + }); trigger = (AndTrigger) threshold.Trigger; - Assert.IsInstanceOf(trigger.Triggers[0]); - Assert.IsInstanceOf(trigger.Triggers[1]); + Assert.Multiple(() => + { + Assert.That(trigger.Triggers[0], Is.InstanceOf()); + Assert.That(trigger.Triggers[1], Is.InstanceOf()); + }); sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -164,19 +176,19 @@ await server.WaitAssertion(() => sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * -2, true); // No new thresholds reached from healing - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise blunt damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true); // No new thresholds reached - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Raise slash damage to 10 sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true); // No new thresholds reached as triggers once is set to true and it already triggered before - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Destructible/DestructibleDestructionTest.cs b/Content.IntegrationTests/Tests/Destructible/DestructibleDestructionTest.cs index c8a38734e76..0373f0d5edc 100644 --- a/Content.IntegrationTests/Tests/Destructible/DestructibleDestructionTest.cs +++ b/Content.IntegrationTests/Tests/Destructible/DestructibleDestructionTest.cs @@ -1,13 +1,9 @@ using System.Linq; -using System.Threading.Tasks; using Content.Server.Destructible.Thresholds; using Content.Server.Destructible.Thresholds.Behaviors; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Map; using Robust.Shared.Prototypes; using static Content.IntegrationTests.Tests.Destructible.DestructibleTestPrototypes; @@ -18,7 +14,11 @@ public sealed class DestructibleDestructionTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -43,27 +43,35 @@ await server.WaitAssertion(() => { var coordinates = sEntityManager.GetComponent(sDestructibleEntity).Coordinates; var bruteDamageGroup = sPrototypeManager.Index("TestBrute"); - DamageSpecifier bruteDamage = new(bruteDamageGroup,50); + DamageSpecifier bruteDamage = new(bruteDamageGroup, 50); +#pragma warning disable NUnit2045 // Interdependent assertions. Assert.DoesNotThrow(() => { - EntitySystem.Get().TryChangeDamage(sDestructibleEntity, bruteDamage, true); + sEntityManager.System().TryChangeDamage(sDestructibleEntity, bruteDamage, true); }); - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); +#pragma warning restore NUnit2045 var threshold = sTestThresholdListenerSystem.ThresholdsReached[0].Threshold; - Assert.That(threshold.Triggered, Is.True); - Assert.That(threshold.Behaviors.Count, Is.EqualTo(3)); + Assert.Multiple(() => + { + Assert.That(threshold.Triggered, Is.True); + Assert.That(threshold.Behaviors, Has.Count.EqualTo(3)); + }); var spawnEntitiesBehavior = (SpawnEntitiesBehavior) threshold.Behaviors.Single(b => b is SpawnEntitiesBehavior); - Assert.That(spawnEntitiesBehavior.Spawn.Count, Is.EqualTo(1)); - Assert.That(spawnEntitiesBehavior.Spawn.Keys.Single(), Is.EqualTo(SpawnedEntityId)); - Assert.That(spawnEntitiesBehavior.Spawn.Values.Single(), Is.EqualTo(new MinMax {Min = 1, Max = 1})); + Assert.Multiple(() => + { + Assert.That(spawnEntitiesBehavior.Spawn, Has.Count.EqualTo(1)); + Assert.That(spawnEntitiesBehavior.Spawn.Keys.Single(), Is.EqualTo(SpawnedEntityId)); + Assert.That(spawnEntitiesBehavior.Spawn.Values.Single(), Is.EqualTo(new MinMax { Min = 1, Max = 1 })); + }); - var entitiesInRange = EntitySystem.Get().GetEntitiesInRange(coordinates, 2); + var entitiesInRange = sEntityManager.System().GetEntitiesInRange(coordinates, 2); var found = false; foreach (var entity in entitiesInRange) diff --git a/Content.IntegrationTests/Tests/Destructible/DestructibleThresholdActivationTest.cs b/Content.IntegrationTests/Tests/Destructible/DestructibleThresholdActivationTest.cs index 863a0df31c5..519040ab465 100644 --- a/Content.IntegrationTests/Tests/Destructible/DestructibleThresholdActivationTest.cs +++ b/Content.IntegrationTests/Tests/Destructible/DestructibleThresholdActivationTest.cs @@ -1,5 +1,4 @@ using System.Linq; -using System.Threading.Tasks; using Content.Server.Destructible; using Content.Server.Destructible.Thresholds; using Content.Server.Destructible.Thresholds.Behaviors; @@ -7,10 +6,7 @@ using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Map; using Robust.Shared.Prototypes; using static Content.IntegrationTests.Tests.Destructible.DestructibleTestPrototypes; @@ -24,7 +20,11 @@ public sealed class DestructibleThresholdActivationTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var sEntityManager = server.ResolveDependency(); @@ -58,7 +58,7 @@ await server.WaitPost(() => await server.WaitAssertion(() => { - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); }); await server.WaitAssertion(() => @@ -68,28 +68,31 @@ await server.WaitAssertion(() => sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // No thresholds reached yet, the earliest one is at 20 damage - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // Only one threshold reached, 20 - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); // Threshold 20 var msg = sTestThresholdListenerSystem.ThresholdsReached[0]; var threshold = msg.Threshold; // Check that it matches the YAML prototype - Assert.That(threshold.Behaviors, Is.Empty); - Assert.NotNull(threshold.Trigger); - Assert.That(threshold.Triggered, Is.True); + Assert.Multiple(() => + { + Assert.That(threshold.Behaviors, Is.Empty); + Assert.That(threshold.Trigger, Is.Not.Null); + Assert.That(threshold.Triggered, Is.True); + }); sTestThresholdListenerSystem.ThresholdsReached.Clear(); - sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*3, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 3, true); // One threshold reached, 50, since 20 already triggered before and it has not been healed below that amount - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); // Threshold 50 msg = sTestThresholdListenerSystem.ThresholdsReached[0]; @@ -102,37 +105,40 @@ await server.WaitAssertion(() => var spawnThreshold = (SpawnEntitiesBehavior) threshold.Behaviors[1]; var actsThreshold = (DoActsBehavior) threshold.Behaviors[2]; - Assert.That(actsThreshold.Acts, Is.EqualTo(ThresholdActs.Breakage)); - Assert.That(audio.GetSound(soundThreshold.Sound), Is.EqualTo("/Audio/Effects/woodhit.ogg")); - Assert.That(spawnThreshold.Spawn, Is.Not.Null); - Assert.That(spawnThreshold.Spawn, Has.Count.EqualTo(1)); - Assert.That(spawnThreshold.Spawn.Single().Key, Is.EqualTo(SpawnedEntityId)); - Assert.That(spawnThreshold.Spawn.Single().Value.Min, Is.EqualTo(1)); - Assert.That(spawnThreshold.Spawn.Single().Value.Max, Is.EqualTo(1)); - Assert.NotNull(threshold.Trigger); - Assert.That(threshold.Triggered, Is.True); + Assert.Multiple(() => + { + Assert.That(actsThreshold.Acts, Is.EqualTo(ThresholdActs.Breakage)); + Assert.That(audio.GetSound(soundThreshold.Sound), Is.EqualTo("/Audio/Effects/woodhit.ogg")); + Assert.That(spawnThreshold.Spawn, Is.Not.Null); + Assert.That(spawnThreshold.Spawn, Has.Count.EqualTo(1)); + Assert.That(spawnThreshold.Spawn.Single().Key, Is.EqualTo(SpawnedEntityId)); + Assert.That(spawnThreshold.Spawn.Single().Value.Min, Is.EqualTo(1)); + Assert.That(spawnThreshold.Spawn.Single().Value.Max, Is.EqualTo(1)); + Assert.That(threshold.Trigger, Is.Not.Null); + Assert.That(threshold.Triggered, Is.True); + }); sTestThresholdListenerSystem.ThresholdsReached.Clear(); // Damage for 50 again, up to 100 now - sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*5, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 5, true); // No thresholds reached as they weren't healed below the trigger amount - Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Set damage to 0 sDamageableSystem.SetAllDamage(sDestructibleEntity, sDamageableComponent, 0); // Damage for 100, up to 100 - sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*10, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 10, true); // Two thresholds reached as damage increased past the previous, 20 and 50 - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(2)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(2)); sTestThresholdListenerSystem.ThresholdsReached.Clear(); // Heal the entity for 40 damage, down to 60 - sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*-4, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * -4, true); // ThresholdsLookup don't work backwards Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); @@ -144,7 +150,7 @@ await server.WaitAssertion(() => Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Heal by 30, down to 40 - sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*-3, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * -3, true); // ThresholdsLookup don't work backwards Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); @@ -153,7 +159,7 @@ await server.WaitAssertion(() => sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // The 50 threshold should have triggered again, after being healed - Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Count.EqualTo(1)); msg = sTestThresholdListenerSystem.ThresholdsReached[0]; threshold = msg.Threshold; @@ -166,15 +172,18 @@ await server.WaitAssertion(() => actsThreshold = (DoActsBehavior) threshold.Behaviors[2]; // Check that it matches the YAML prototype - Assert.That(actsThreshold.Acts, Is.EqualTo(ThresholdActs.Breakage)); - Assert.That(audio.GetSound(soundThreshold.Sound), Is.EqualTo("/Audio/Effects/woodhit.ogg")); - Assert.That(spawnThreshold.Spawn, Is.Not.Null); - Assert.That(spawnThreshold.Spawn.Count, Is.EqualTo(1)); - Assert.That(spawnThreshold.Spawn.Single().Key, Is.EqualTo(SpawnedEntityId)); - Assert.That(spawnThreshold.Spawn.Single().Value.Min, Is.EqualTo(1)); - Assert.That(spawnThreshold.Spawn.Single().Value.Max, Is.EqualTo(1)); - Assert.NotNull(threshold.Trigger); - Assert.That(threshold.Triggered, Is.True); + Assert.Multiple(() => + { + Assert.That(actsThreshold.Acts, Is.EqualTo(ThresholdActs.Breakage)); + Assert.That(audio.GetSound(soundThreshold.Sound), Is.EqualTo("/Audio/Effects/woodhit.ogg")); + Assert.That(spawnThreshold.Spawn, Is.Not.Null); + Assert.That(spawnThreshold.Spawn, Has.Count.EqualTo(1)); + Assert.That(spawnThreshold.Spawn.Single().Key, Is.EqualTo(SpawnedEntityId)); + Assert.That(spawnThreshold.Spawn.Single().Value.Min, Is.EqualTo(1)); + Assert.That(spawnThreshold.Spawn.Single().Value.Max, Is.EqualTo(1)); + Assert.That(threshold.Trigger, Is.Not.Null); + Assert.That(threshold.Triggered, Is.True); + }); // Reset thresholds reached sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -183,19 +192,25 @@ await server.WaitAssertion(() => sDamageableSystem.SetAllDamage(sDestructibleEntity, sDamageableComponent, 0); // Damage up to 50 - sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*5, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 5, true); - // Check that the total damage matches - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(50))); + Assert.Multiple(() => + { + // Check that the total damage matches + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(50))); - // Both thresholds should have triggered - Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Exactly(2).Items); + // Both thresholds should have triggered + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Has.Exactly(2).Items); + }); // Verify the first one, should be the lowest one (20) msg = sTestThresholdListenerSystem.ThresholdsReached[0]; var trigger = (DamageTrigger) msg.Threshold.Trigger; - Assert.NotNull(trigger); - Assert.That(trigger.Damage, Is.EqualTo(20)); + Assert.Multiple(() => + { + Assert.That(trigger, Is.Not.Null); + Assert.That(trigger.Damage, Is.EqualTo(20)); + }); threshold = msg.Threshold; @@ -205,8 +220,11 @@ await server.WaitAssertion(() => // Verify the second one, should be the highest one (50) msg = sTestThresholdListenerSystem.ThresholdsReached[1]; trigger = (DamageTrigger) msg.Threshold.Trigger; - Assert.NotNull(trigger); - Assert.That(trigger.Damage, Is.EqualTo(50)); + Assert.Multiple(() => + { + Assert.That(trigger, Is.Not.Null); + Assert.That(trigger.Damage, Is.EqualTo(50)); + }); threshold = msg.Threshold; @@ -217,15 +235,18 @@ await server.WaitAssertion(() => actsThreshold = (DoActsBehavior) threshold.Behaviors[2]; // Check that it matches the YAML prototype - Assert.That(actsThreshold.Acts, Is.EqualTo(ThresholdActs.Breakage)); - Assert.That(soundThreshold.Sound.GetSound(), Is.EqualTo("/Audio/Effects/woodhit.ogg")); - Assert.That(spawnThreshold.Spawn, Is.Not.Null); - Assert.That(spawnThreshold.Spawn, Has.Count.EqualTo(1)); - Assert.That(spawnThreshold.Spawn.Single().Key, Is.EqualTo(SpawnedEntityId)); - Assert.That(spawnThreshold.Spawn.Single().Value.Min, Is.EqualTo(1)); - Assert.That(spawnThreshold.Spawn.Single().Value.Max, Is.EqualTo(1)); - Assert.NotNull(threshold.Trigger); - Assert.That(threshold.Triggered, Is.True); + Assert.Multiple(() => + { + Assert.That(actsThreshold.Acts, Is.EqualTo(ThresholdActs.Breakage)); + Assert.That(audio.GetSound(soundThreshold.Sound), Is.EqualTo("/Audio/Effects/woodhit.ogg")); + Assert.That(spawnThreshold.Spawn, Is.Not.Null); + Assert.That(spawnThreshold.Spawn, Has.Count.EqualTo(1)); + Assert.That(spawnThreshold.Spawn.Single().Key, Is.EqualTo(SpawnedEntityId)); + Assert.That(spawnThreshold.Spawn.Single().Value.Min, Is.EqualTo(1)); + Assert.That(spawnThreshold.Spawn.Single().Value.Max, Is.EqualTo(1)); + Assert.That(threshold.Trigger, Is.Not.Null); + Assert.That(threshold.Triggered, Is.True); + }); // Reset thresholds reached sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -239,31 +260,37 @@ await server.WaitAssertion(() => // Set both thresholds to only trigger once foreach (var destructibleThreshold in sDestructibleComponent.Thresholds) { - Assert.NotNull(destructibleThreshold.Trigger); + Assert.That(destructibleThreshold.Trigger, Is.Not.Null); destructibleThreshold.TriggersOnce = true; } // Damage the entity up to 50 damage again - sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*5, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 5, true); - // Check that the total damage matches - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(50))); + Assert.Multiple(() => + { + // Check that the total damage matches + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(50))); - // No thresholds should have triggered as they were already triggered before, and they are set to only trigger once - Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); + // No thresholds should have triggered as they were already triggered before, and they are set to only trigger once + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); + }); // Set both thresholds to trigger multiple times foreach (var destructibleThreshold in sDestructibleComponent.Thresholds) { - Assert.NotNull(destructibleThreshold.Trigger); + Assert.That(destructibleThreshold.Trigger, Is.Not.Null); destructibleThreshold.TriggersOnce = false; } - // Check that the total damage matches - Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(50))); + Assert.Multiple(() => + { + // Check that the total damage matches + Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(50))); - // They shouldn't have been triggered by changing TriggersOnce - Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); + // They shouldn't have been triggered by changing TriggersOnce + Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); + }); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/DeviceNetwork/DeviceNetworkTest.cs b/Content.IntegrationTests/Tests/DeviceNetwork/DeviceNetworkTest.cs index ec62e716795..7c53522b5e7 100644 --- a/Content.IntegrationTests/Tests/DeviceNetwork/DeviceNetworkTest.cs +++ b/Content.IntegrationTests/Tests/DeviceNetwork/DeviceNetworkTest.cs @@ -1,8 +1,6 @@ -using System.Threading.Tasks; using Content.Server.DeviceNetwork; using Content.Server.DeviceNetwork.Components; using Content.Server.DeviceNetwork.Systems; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -51,7 +49,11 @@ public sealed class DeviceNetworkTest [Test] public async Task NetworkDeviceSendAndReceive() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); @@ -73,20 +75,27 @@ public async Task NetworkDeviceSendAndReceive() ["testbool"] = true }; - await server.WaitAssertion(() => { + await server.WaitAssertion(() => + { device1 = entityManager.SpawnEntity("DummyNetworkDevice", MapCoordinates.Nullspace); Assert.That(entityManager.TryGetComponent(device1, out networkComponent1), Is.True); - Assert.That(networkComponent1.ReceiveFrequency != null, Is.True); - Assert.That(networkComponent1.Address, Is.Not.EqualTo(string.Empty)); + Assert.Multiple(() => + { + Assert.That(networkComponent1.ReceiveFrequency, Is.Not.Null); + Assert.That(networkComponent1.Address, Is.Not.EqualTo(string.Empty)); + }); device2 = entityManager.SpawnEntity("DummyNetworkDevice", MapCoordinates.Nullspace); Assert.That(entityManager.TryGetComponent(device2, out networkComponent2), Is.True); - Assert.That(networkComponent1.ReceiveFrequency != null, Is.True); - Assert.That(networkComponent2.Address, Is.Not.EqualTo(string.Empty)); + Assert.Multiple(() => + { + Assert.That(networkComponent1.ReceiveFrequency, Is.Not.Null); + Assert.That(networkComponent2.Address, Is.Not.EqualTo(string.Empty)); - Assert.That(networkComponent1.Address, Is.Not.EqualTo(networkComponent2.Address)); + Assert.That(networkComponent1.Address, Is.Not.EqualTo(networkComponent2.Address)); + }); deviceNetSystem.QueuePacket(device1, networkComponent2.Address, payload, networkComponent2.ReceiveFrequency.Value); }); @@ -94,7 +103,8 @@ await server.WaitAssertion(() => { await server.WaitRunTicks(2); await server.WaitIdleAsync(); - await server.WaitAssertion(() => { + await server.WaitAssertion(() => + { CollectionAssert.AreEquivalent(deviceNetTestSystem.LastPayload, payload); }); await pairTracker.CleanReturnAsync(); @@ -103,7 +113,11 @@ await server.WaitAssertion(() => { [Test] public async Task WirelessNetworkDeviceSendAndReceive() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); var coordinates = testMap.GridCoords; @@ -127,21 +141,32 @@ public async Task WirelessNetworkDeviceSendAndReceive() ["testbool"] = true }; - await server.WaitAssertion(() => { + await server.WaitAssertion(() => + { device1 = entityManager.SpawnEntity("DummyWirelessNetworkDevice", coordinates); - Assert.That(entityManager.TryGetComponent(device1, out networkComponent1), Is.True); - Assert.That(entityManager.TryGetComponent(device1, out wirelessNetworkComponent), Is.True); - Assert.That(networkComponent1.ReceiveFrequency != null, Is.True); - Assert.That(networkComponent1.Address, Is.Not.EqualTo(string.Empty)); + Assert.Multiple(() => + { + Assert.That(entityManager.TryGetComponent(device1, out networkComponent1), Is.True); + Assert.That(entityManager.TryGetComponent(device1, out wirelessNetworkComponent), Is.True); + }); + Assert.Multiple(() => + { + Assert.That(networkComponent1.ReceiveFrequency, Is.Not.Null); + Assert.That(networkComponent1.Address, Is.Not.EqualTo(string.Empty)); + }); - device2 = entityManager.SpawnEntity("DummyWirelessNetworkDevice", new MapCoordinates(new Robust.Shared.Maths.Vector2(0,50), testMap.MapId)); + device2 = entityManager.SpawnEntity("DummyWirelessNetworkDevice", new MapCoordinates(new Robust.Shared.Maths.Vector2(0, 50), testMap.MapId)); Assert.That(entityManager.TryGetComponent(device2, out networkComponent2), Is.True); - Assert.That(networkComponent2.ReceiveFrequency != null, Is.True); - Assert.That(networkComponent2.Address, Is.Not.EqualTo(string.Empty)); + Assert.Multiple(() => + { + Assert.That(networkComponent2.ReceiveFrequency, Is.Not.Null); + Assert.That(networkComponent2.Address, Is.Not.EqualTo(string.Empty)); + + Assert.That(networkComponent1.Address, Is.Not.EqualTo(networkComponent2.Address)); + }); - Assert.That(networkComponent1.Address, Is.Not.EqualTo(networkComponent2.Address)); deviceNetSystem.QueuePacket(device1, networkComponent2.Address, payload, networkComponent2.ReceiveFrequency.Value); }); @@ -149,7 +174,8 @@ await server.WaitAssertion(() => { await server.WaitRunTicks(2); await server.WaitIdleAsync(); - await server.WaitAssertion(() => { + await server.WaitAssertion(() => + { CollectionAssert.AreEqual(deviceNetTestSystem.LastPayload, payload); payload = new NetworkPayload @@ -165,7 +191,8 @@ await server.WaitAssertion(() => { await server.WaitRunTicks(1); await server.WaitIdleAsync(); - await server.WaitAssertion(() => { + await server.WaitAssertion(() => + { CollectionAssert.AreNotEqual(deviceNetTestSystem.LastPayload, payload); }); @@ -175,7 +202,11 @@ await server.WaitAssertion(() => { [Test] public async Task WiredNetworkDeviceSendAndReceive() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); var coordinates = testMap.GridCoords; @@ -190,7 +221,7 @@ public async Task WiredNetworkDeviceSendAndReceive() DeviceNetworkComponent networkComponent1 = null; DeviceNetworkComponent networkComponent2 = null; WiredNetworkComponent wiredNetworkComponent = null; - MapGridComponent grid = testMap.MapGrid; + var grid = testMap.MapGrid; var testValue = "test"; var payload = new NetworkPayload @@ -203,21 +234,31 @@ public async Task WiredNetworkDeviceSendAndReceive() await server.WaitRunTicks(2); await server.WaitIdleAsync(); - await server.WaitAssertion(() => { + await server.WaitAssertion(() => + { device1 = entityManager.SpawnEntity("DummyWiredNetworkDevice", coordinates); - Assert.That(entityManager.TryGetComponent(device1, out networkComponent1), Is.True); - Assert.That(entityManager.TryGetComponent(device1, out wiredNetworkComponent), Is.True); - Assert.That(networkComponent1.ReceiveFrequency != null, Is.True); - Assert.That(networkComponent1.Address, Is.Not.EqualTo(string.Empty)); + Assert.Multiple(() => + { + Assert.That(entityManager.TryGetComponent(device1, out networkComponent1), Is.True); + Assert.That(entityManager.TryGetComponent(device1, out wiredNetworkComponent), Is.True); + }); + Assert.Multiple(() => + { + Assert.That(networkComponent1.ReceiveFrequency, Is.Not.Null); + Assert.That(networkComponent1.Address, Is.Not.EqualTo(string.Empty)); + }); device2 = entityManager.SpawnEntity("DummyWiredNetworkDevice", coordinates); Assert.That(entityManager.TryGetComponent(device2, out networkComponent2), Is.True); - Assert.That(networkComponent2.ReceiveFrequency != null, Is.True); - Assert.That(networkComponent2.Address, Is.Not.EqualTo(string.Empty)); + Assert.Multiple(() => + { + Assert.That(networkComponent2.ReceiveFrequency, Is.Not.Null); + Assert.That(networkComponent2.Address, Is.Not.EqualTo(string.Empty)); - Assert.That(networkComponent1.Address, Is.Not.EqualTo(networkComponent2.Address)); + Assert.That(networkComponent1.Address, Is.Not.EqualTo(networkComponent2.Address)); + }); deviceNetSystem.QueuePacket(device1, networkComponent2.Address, payload, networkComponent2.ReceiveFrequency.Value); }); @@ -225,7 +266,8 @@ await server.WaitAssertion(() => { await server.WaitRunTicks(1); await server.WaitIdleAsync(); - await server.WaitAssertion(() => { + await server.WaitAssertion(() => + { //CollectionAssert.AreNotEqual(deviceNetTestSystem.LastPayload, payload); entityManager.SpawnEntity("CableApcExtension", coordinates); @@ -236,7 +278,8 @@ await server.WaitAssertion(() => { await server.WaitRunTicks(1); await server.WaitIdleAsync(); - await server.WaitAssertion(() => { + await server.WaitAssertion(() => + { CollectionAssert.AreEqual(deviceNetTestSystem.LastPayload, payload); }); diff --git a/Content.IntegrationTests/Tests/Disposal/DisposalUnitTest.cs b/Content.IntegrationTests/Tests/Disposal/DisposalUnitTest.cs index cd7da1fbd27..948252e5cc4 100644 --- a/Content.IntegrationTests/Tests/Disposal/DisposalUnitTest.cs +++ b/Content.IntegrationTests/Tests/Disposal/DisposalUnitTest.cs @@ -1,6 +1,5 @@ #nullable enable annotations using System.Linq; -using System.Threading.Tasks; using Content.Server.Disposal.Tube.Components; using Content.Server.Disposal.Unit.Components; using Content.Server.Disposal.Unit.EntitySystems; diff --git a/Content.IntegrationTests/Tests/DoAfter/DoAfterCancellationTests.cs b/Content.IntegrationTests/Tests/DoAfter/DoAfterCancellationTests.cs index d52a3d94979..29cb6426c94 100644 --- a/Content.IntegrationTests/Tests/DoAfter/DoAfterCancellationTests.cs +++ b/Content.IntegrationTests/Tests/DoAfter/DoAfterCancellationTests.cs @@ -1,10 +1,8 @@ using System.Linq; -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Construction.Interaction; using Content.IntegrationTests.Tests.Interaction; using Content.IntegrationTests.Tests.Weldable; using Content.Server.Tools.Components; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.DoAfter; @@ -18,7 +16,7 @@ public sealed class DoAfterCancellationTests : InteractionTest public async Task CancelWallDeconstruct() { await StartDeconstruction(WallConstruction.WallSolid); - await Interact(Weld, awaitDoAfters:false); + await Interact(Weld, awaitDoAfters: false); // Failed do-after has no effect await CancelDoAfters(); @@ -30,7 +28,7 @@ public async Task CancelWallDeconstruct() // Repeat for wrenching interaction AssertAnchored(); - await Interact(Wrench, awaitDoAfters:false); + await Interact(Wrench, awaitDoAfters: false); await CancelDoAfters(); AssertAnchored(); AssertPrototype(WallConstruction.Girder); @@ -39,7 +37,7 @@ public async Task CancelWallDeconstruct() // Repeat for screwdriver interaction. AssertDeleted(false); - await Interact(Screw, awaitDoAfters:false); + await Interact(Screw, awaitDoAfters: false); await CancelDoAfters(); AssertDeleted(false); await Interact(Screw); @@ -50,13 +48,13 @@ public async Task CancelWallDeconstruct() public async Task CancelWallConstruct() { await StartConstruction(WallConstruction.Wall); - await Interact(Steel, 5, awaitDoAfters:false); + await Interact(Steel, 5, awaitDoAfters: false); await CancelDoAfters(); Assert.That(Target.HasValue && Target.Value.IsClientSide()); await Interact(Steel, 5); AssertPrototype(WallConstruction.Girder); - await Interact(Steel, 5, awaitDoAfters:false); + await Interact(Steel, 5, awaitDoAfters: false); await CancelDoAfters(); AssertPrototype(WallConstruction.Girder); @@ -68,7 +66,7 @@ public async Task CancelWallConstruct() public async Task CancelTilePry() { await SetTile(Floor); - await Interact(Pry, awaitDoAfters:false); + await Interact(Pry, awaitDoAfters: false); await CancelDoAfters(); await AssertTile(Floor); @@ -80,7 +78,7 @@ public async Task CancelTilePry() public async Task CancelRepeatedTilePry() { await SetTile(Floor); - await Interact(Pry, awaitDoAfters:false); + await Interact(Pry, awaitDoAfters: false); await RunTicks(1); Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1)); await AssertTile(Floor); @@ -102,35 +100,56 @@ public async Task CancelRepeatedWeld() await SpawnTarget(WeldableTests.Locker); var comp = Comp(); - Assert.That(comp.Weldable, Is.True); - Assert.That(comp.IsWelded, Is.False); + Assert.Multiple(() => + { + Assert.That(comp.Weldable, Is.True); + Assert.That(comp.IsWelded, Is.False); + }); - await Interact(Weld, awaitDoAfters:false); + await Interact(Weld, awaitDoAfters: false); await RunTicks(1); - Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1)); - Assert.That(comp.IsWelded, Is.False); + Assert.Multiple(() => + { + Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1)); + Assert.That(comp.IsWelded, Is.False); + }); // Second DoAfter cancels the first. // Not using helper, because it runs too many ticks & causes the do-after to finish. await Server.WaitPost(() => InteractSys.UserInteraction(Player, TargetCoords, Target)); - Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0)); - Assert.That(comp.IsWelded, Is.False); + Assert.Multiple(() => + { + Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0)); + Assert.That(comp.IsWelded, Is.False); + }); // Third do after will work fine await Interact(Weld); - Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0)); - Assert.That(comp.IsWelded, Is.True); + Assert.Multiple(() => + { + Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0)); + Assert.That(comp.IsWelded, Is.True); + }); // Repeat test for un-welding - await Interact(Weld, awaitDoAfters:false); + await Interact(Weld, awaitDoAfters: false); await RunTicks(1); - Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1)); - Assert.That(comp.IsWelded, Is.True); + Assert.Multiple(() => + { + Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1)); + Assert.That(comp.IsWelded, Is.True); + }); await Server.WaitPost(() => InteractSys.UserInteraction(Player, TargetCoords, Target)); - Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0)); - Assert.That(comp.IsWelded, Is.True); + Assert.Multiple(() => + { + Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0)); + Assert.That(comp.IsWelded, Is.True); + }); await Interact(Weld); - Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0)); - Assert.That(comp.IsWelded, Is.False); + Assert.Multiple(() => + { + Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0)); + Assert.That(comp.IsWelded, Is.False); + }); } } diff --git a/Content.IntegrationTests/Tests/DoAfter/DoAfterServerTest.cs b/Content.IntegrationTests/Tests/DoAfter/DoAfterServerTest.cs index 390bdff8d3a..efcf12e3dba 100644 --- a/Content.IntegrationTests/Tests/DoAfter/DoAfterServerTest.cs +++ b/Content.IntegrationTests/Tests/DoAfter/DoAfterServerTest.cs @@ -1,9 +1,5 @@ -using System; -using System.Threading.Tasks; using Content.Shared.DoAfter; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Reflection; using Robust.Shared.Serialization; @@ -35,7 +31,7 @@ public override DoAfterEvent Clone() [Test] public async Task TestSerializable() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); var refMan = server.ResolveDependency(); @@ -62,7 +58,11 @@ await server.WaitPost(() => [Test] public async Task TestFinished() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); @@ -77,8 +77,10 @@ await server.WaitPost(() => var tickTime = 1.0f / timing.TickRate; var mob = entityManager.SpawnEntity("Dummy", MapCoordinates.Nullspace); var args = new DoAfterArgs(mob, tickTime / 2, ev, null) { Broadcast = true }; +#pragma warning disable NUnit2045 // Interdependent assertions. Assert.That(doAfterSystem.TryStartDoAfter(args)); Assert.That(ev.Cancelled, Is.False); +#pragma warning restore NUnit2045 }); await server.WaitRunTicks(1); @@ -90,12 +92,15 @@ await server.WaitPost(() => [Test] public async Task TestCancelled() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var entityManager = server.ResolveDependency(); var timing = server.ResolveDependency(); var doAfterSystem = entityManager.EntitySysManager.GetEntitySystem(); - DoAfterId? id; var ev = new TestDoAfterEvent(); await server.WaitPost(() => @@ -105,7 +110,7 @@ await server.WaitPost(() => var mob = entityManager.SpawnEntity("Dummy", MapCoordinates.Nullspace); var args = new DoAfterArgs(mob, tickTime * 2, ev, null) { Broadcast = true }; - if (!doAfterSystem.TryStartDoAfter(args, out id)) + if (!doAfterSystem.TryStartDoAfter(args, out var id)) { Assert.Fail(); return; diff --git a/Content.IntegrationTests/Tests/Doors/AirlockTest.cs b/Content.IntegrationTests/Tests/Doors/AirlockTest.cs index b61eaf46218..b856169d99c 100644 --- a/Content.IntegrationTests/Tests/Doors/AirlockTest.cs +++ b/Content.IntegrationTests/Tests/Doors/AirlockTest.cs @@ -1,12 +1,8 @@ -using System; -using System.Threading.Tasks; using Content.Server.Doors.Systems; using Content.Shared.Doors.Components; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Maths; -using Robust.Shared.Physics; using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Systems; @@ -55,7 +51,11 @@ public sealed class AirlockTest [Test] public async Task OpenCloseDestroyTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var entityManager = server.ResolveDependency(); @@ -68,8 +68,10 @@ await server.WaitAssertion(() => { airlock = entityManager.SpawnEntity("AirlockDummy", MapCoordinates.Nullspace); - Assert.True(entityManager.TryGetComponent(airlock, out doorComponent)); +#pragma warning disable NUnit2045 // Interdependent assertions. + Assert.That(entityManager.TryGetComponent(airlock, out doorComponent), Is.True); Assert.That(doorComponent.State, Is.EqualTo(DoorState.Closed)); +#pragma warning restore NUnit2045 }); await server.WaitIdleAsync(); @@ -112,7 +114,11 @@ await server.WaitAssertion(() => [Test] public async Task AirlockBlockTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); @@ -120,6 +126,7 @@ public async Task AirlockBlockTest() var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); var physicsSystem = entityManager.System(); + var xformSystem = entityManager.System(); PhysicsComponent physBody = null; EntityUid physicsDummy = default; @@ -137,9 +144,11 @@ await server.WaitAssertion(() => airlock = entityManager.SpawnEntity("AirlockDummy", new MapCoordinates((0, 0), mapId)); - Assert.True(entityManager.TryGetComponent(physicsDummy, out physBody)); - - Assert.True(entityManager.TryGetComponent(airlock, out doorComponent)); + Assert.Multiple(() => + { + Assert.That(entityManager.TryGetComponent(physicsDummy, out physBody), Is.True); + Assert.That(entityManager.TryGetComponent(airlock, out doorComponent), Is.True); + }); Assert.That(doorComponent.State, Is.EqualTo(DoorState.Closed)); }); @@ -171,7 +180,10 @@ await server.WaitPost(() => // Assert.That(physicsDummy.Transform.MapPosition.X, Is.GreaterThan(physicsDummyStartingX)); // Blocked by the airlock - await server.WaitAssertion(() => Assert.That(Math.Abs(entityManager.GetComponent(physicsDummy).MapPosition.X - 1) > 0.01f)); + await server.WaitAssertion(() => + { + Assert.That(Math.Abs(xformSystem.GetWorldPosition(physicsDummy).X - 1), Is.GreaterThan(0.01f)); + }); await pairTracker.CleanReturnAsync(); } } diff --git a/Content.IntegrationTests/Tests/DummyIconTest.cs b/Content.IntegrationTests/Tests/DummyIconTest.cs index d51da122d44..56a183a42cd 100644 --- a/Content.IntegrationTests/Tests/DummyIconTest.cs +++ b/Content.IntegrationTests/Tests/DummyIconTest.cs @@ -1,10 +1,7 @@ #nullable enable using System.Linq; -using System.Threading.Tasks; -using NUnit.Framework; using Robust.Client.GameObjects; using Robust.Client.ResourceManagement; -using Robust.Shared.IoC; using Robust.Shared.Prototypes; namespace Content.IntegrationTests.Tests diff --git a/Content.IntegrationTests/Tests/EncryptionKeys/RemoveEncryptionKeys.cs b/Content.IntegrationTests/Tests/EncryptionKeys/RemoveEncryptionKeys.cs index f25564a4fcc..742a968d2d0 100644 --- a/Content.IntegrationTests/Tests/EncryptionKeys/RemoveEncryptionKeys.cs +++ b/Content.IntegrationTests/Tests/EncryptionKeys/RemoveEncryptionKeys.cs @@ -1,9 +1,7 @@ using System.Linq; -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Shared.Radio.Components; using Content.Shared.Wires; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.EncryptionKeys; @@ -15,26 +13,35 @@ public async Task HeadsetKeys() await SpawnTarget("ClothingHeadsetGrey"); var comp = Comp(); - Assert.That(comp.KeyContainer.ContainedEntities.Count, Is.EqualTo(1)); - Assert.That(comp.DefaultChannel, Is.EqualTo("Common")); - Assert.That(comp.Channels.Count, Is.EqualTo(1)); - Assert.That(comp.Channels.First(), Is.EqualTo("Common")); + Assert.Multiple(() => + { + Assert.That(comp.KeyContainer.ContainedEntities, Has.Count.EqualTo(1)); + Assert.That(comp.DefaultChannel, Is.EqualTo("Common")); + Assert.That(comp.Channels, Has.Count.EqualTo(1)); + Assert.That(comp.Channels.First(), Is.EqualTo("Common")); + }); // Remove the key await Interact(Screw); - Assert.That(comp.KeyContainer.ContainedEntities.Count, Is.EqualTo(0)); - Assert.IsNull(comp.DefaultChannel); - Assert.That(comp.Channels.Count, Is.EqualTo(0)); + Assert.Multiple(() => + { + Assert.That(comp.KeyContainer.ContainedEntities, Has.Count.EqualTo(0)); + Assert.That(comp.DefaultChannel, Is.Null); + Assert.That(comp.Channels, Has.Count.EqualTo(0)); + }); // Checkl that the key was ejected and not just deleted or something. await AssertEntityLookup(("EncryptionKeyCommon", 1)); // Re-insert a key. await Interact("EncryptionKeyCentCom"); - Assert.That(comp.KeyContainer.ContainedEntities.Count, Is.EqualTo(1)); - Assert.That(comp.DefaultChannel, Is.EqualTo("CentCom")); - Assert.That(comp.Channels.Count, Is.EqualTo(1)); - Assert.That(comp.Channels.First(), Is.EqualTo("CentCom")); + Assert.Multiple(() => + { + Assert.That(comp.KeyContainer.ContainedEntities, Has.Count.EqualTo(1)); + Assert.That(comp.DefaultChannel, Is.EqualTo("CentCom")); + Assert.That(comp.Channels, Has.Count.EqualTo(1)); + Assert.That(comp.Channels.First(), Is.EqualTo("CentCom")); + }); } [Test] @@ -44,40 +51,58 @@ public async Task CommsServerKeys() var comp = Comp(); var panel = Comp(); - Assert.That(comp.KeyContainer.ContainedEntities.Count, Is.GreaterThan(0)); - Assert.That(comp.Channels.Count, Is.GreaterThan(0)); - Assert.That(panel.Open, Is.False); + Assert.Multiple(() => + { + Assert.That(comp.KeyContainer.ContainedEntities, Has.Count.GreaterThan(0)); + Assert.That(comp.Channels, Has.Count.GreaterThan(0)); + Assert.That(panel.Open, Is.False); + }); // cannot remove keys without opening panel await Interact(Pry); - Assert.That(comp.KeyContainer.ContainedEntities.Count, Is.GreaterThan(0)); - Assert.That(comp.Channels.Count, Is.GreaterThan(0)); - Assert.That(panel.Open, Is.False); + Assert.Multiple(() => + { + Assert.That(comp.KeyContainer.ContainedEntities, Has.Count.GreaterThan(0)); + Assert.That(comp.Channels, Has.Count.GreaterThan(0)); + Assert.That(panel.Open, Is.False); + }); // Open panel await Interact(Screw); - Assert.That(panel.Open, Is.True); + Assert.Multiple(() => + { + Assert.That(panel.Open, Is.True); - // Keys are still here - Assert.That(comp.KeyContainer.ContainedEntities.Count, Is.GreaterThan(0)); - Assert.That(comp.Channels.Count, Is.GreaterThan(0)); + // Keys are still here + Assert.That(comp.KeyContainer.ContainedEntities, Has.Count.GreaterThan(0)); + Assert.That(comp.Channels, Has.Count.GreaterThan(0)); + }); // Now remove the keys await Interact(Pry); - Assert.That(comp.KeyContainer.ContainedEntities.Count, Is.EqualTo(0)); - Assert.That(comp.Channels.Count, Is.EqualTo(0)); + Assert.Multiple(() => + { + Assert.That(comp.KeyContainer.ContainedEntities, Has.Count.EqualTo(0)); + Assert.That(comp.Channels, Has.Count.EqualTo(0)); + }); // Reinsert a key await Interact("EncryptionKeyCentCom"); - Assert.That(comp.KeyContainer.ContainedEntities.Count, Is.EqualTo(1)); - Assert.That(comp.DefaultChannel, Is.EqualTo("CentCom")); - Assert.That(comp.Channels.Count, Is.EqualTo(1)); - Assert.That(comp.Channels.First(), Is.EqualTo("CentCom")); + Assert.Multiple(() => + { + Assert.That(comp.KeyContainer.ContainedEntities, Has.Count.EqualTo(1)); + Assert.That(comp.DefaultChannel, Is.EqualTo("CentCom")); + Assert.That(comp.Channels, Has.Count.EqualTo(1)); + Assert.That(comp.Channels.First(), Is.EqualTo("CentCom")); + }); // Remove it again await Interact(Pry); - Assert.That(comp.KeyContainer.ContainedEntities.Count, Is.EqualTo(0)); - Assert.That(comp.Channels.Count, Is.EqualTo(0)); + Assert.Multiple(() => + { + Assert.That(comp.KeyContainer.ContainedEntities, Has.Count.EqualTo(0)); + Assert.That(comp.Channels, Has.Count.EqualTo(0)); + }); // Prying again will start deconstructing the machine. AssertPrototype("TelecomServerFilled"); @@ -85,4 +110,3 @@ public async Task CommsServerKeys() AssertPrototype("MachineFrame"); } } - diff --git a/Content.IntegrationTests/Tests/EntityTest.cs b/Content.IntegrationTests/Tests/EntityTest.cs index 50ab2eb400f..2516decf725 100644 --- a/Content.IntegrationTests/Tests/EntityTest.cs +++ b/Content.IntegrationTests/Tests/EntityTest.cs @@ -1,14 +1,9 @@ -using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; -using Content.Shared.CCVar; using Content.Shared.Coordinates; -using NUnit.Framework; using Robust.Shared; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Map.Components; @@ -24,7 +19,7 @@ public sealed class EntityTest [Test] public async Task SpawnAndDeleteAllEntitiesOnDifferentMaps() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, Destructive = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, Destructive = true }); var server = pairTracker.Pair.Server; var entityMan = server.ResolveDependency(); @@ -35,7 +30,7 @@ await server.WaitPost(() => { var protoIds = prototypeMan .EnumeratePrototypes() - .Where(p=>!p.Abstract) + .Where(p => !p.Abstract) .Where(p => !p.Components.ContainsKey("MapGrid")) // This will smash stuff otherwise. .Select(p => p.ID) .ToList(); @@ -52,11 +47,19 @@ await server.WaitPost(() => await server.WaitPost(() => { - var entityMetas = entityMan.EntityQuery(true).ToList(); - foreach (var meta in entityMetas) + static IEnumerable<(EntityUid, TComp)> Query(IEntityManager entityMan) + where TComp : Component { - if(!meta.EntityDeleted) - entityMan.DeleteEntity(meta.Owner); + var query = entityMan.AllEntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var meta)) + yield return (uid, meta); + }; + + var entityMetas = Query(entityMan).ToList(); + foreach (var (uid, meta) in entityMetas) + { + if (!meta.EntityDeleted) + entityMan.DeleteEntity(uid); } Assert.That(entityMan.EntityCount, Is.Zero); @@ -68,7 +71,7 @@ await server.WaitPost(() => [Test] public async Task SpawnAndDeleteAllEntitiesInTheSameSpot() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, Destructive = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, Destructive = true }); var server = pairTracker.Pair.Server; var map = await PoolManager.CreateTestMap(pairTracker); @@ -80,7 +83,7 @@ await server.WaitPost(() => var protoIds = prototypeMan .EnumeratePrototypes() - .Where(p=>!p.Abstract) + .Where(p => !p.Abstract) .Where(p => !p.Components.ContainsKey("MapGrid")) // This will smash stuff otherwise. .Select(p => p.ID) .ToList(); @@ -92,11 +95,19 @@ await server.WaitPost(() => await server.WaitRunTicks(15); await server.WaitPost(() => { - var entityMetas = entityMan.EntityQuery(true).ToList(); - foreach (var meta in entityMetas) + static IEnumerable<(EntityUid, TComp)> Query(IEntityManager entityMan) + where TComp : Component + { + var query = entityMan.AllEntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var meta)) + yield return (uid, meta); + }; + + var entityMetas = Query(entityMan).ToList(); + foreach (var (uid, meta) in entityMetas) { - if(!meta.EntityDeleted) - entityMan.DeleteEntity(meta.Owner); + if (!meta.EntityDeleted) + entityMan.DeleteEntity(uid); } Assert.That(entityMan.EntityCount, Is.Zero); @@ -132,7 +143,7 @@ public async Task SpawnAndDirtyAllEntities() // for whatever reason, stealth boxes are breaking this test. Surplus crates have a chance of spawning them. // TODO fix whatever is going wrong here. - HashSet ignored = new() {"GhostBox", "StealthBox", "CrateSyndicateSurplusBundle", "CrateSyndicateSuperSurplusBundle"}; + HashSet ignored = new() { "GhostBox", "StealthBox", "CrateSyndicateSurplusBundle", "CrateSyndicateSuperSurplusBundle" }; await server.WaitPost(() => { @@ -159,11 +170,19 @@ await server.WaitPost(() => await server.WaitPost(() => { - var entityMetas = sEntMan.EntityQuery(true).ToList(); - foreach (var meta in entityMetas) + static IEnumerable<(EntityUid, TComp)> Query(IEntityManager entityMan) + where TComp : Component + { + var query = entityMan.AllEntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var meta)) + yield return (uid, meta); + }; + + var entityMetas = Query(sEntMan).ToList(); + foreach (var (uid, meta) in entityMetas) { if (!meta.EntityDeleted) - sEntMan.DeleteEntity(meta.Owner); + sEntMan.DeleteEntity(uid); } Assert.That(sEntMan.EntityCount, Is.Zero); @@ -196,13 +215,14 @@ public async Task AllComponentsOneToOneDeleteTest() - type: entity id: AllComponentsOneToOneDeleteTestEntity"; - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = testEntity}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = testEntity }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); var componentFactory = server.ResolveDependency(); var tileDefinitionManager = server.ResolveDependency(); + var logmill = server.ResolveDependency().GetSawmill("EntityTest"); MapGridComponent grid = default; @@ -255,8 +275,7 @@ await server.WaitAssertion(() => } component.Owner = entity; - - Logger.LogS(LogLevel.Debug, "EntityTest", $"Adding component: {name}"); + logmill.Debug($"Adding component: {name}"); Assert.DoesNotThrow(() => { @@ -296,13 +315,14 @@ public async Task AllComponentsOneEntityDeleteTest() - type: entity id: AllComponentsOneEntityDeleteTestEntity"; - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = testEntity}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = testEntity }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); var componentFactory = server.ResolveDependency(); var tileDefinitionManager = server.ResolveDependency(); + var logmill = server.ResolveDependency().GetSawmill("EntityTest"); MapGridComponent grid = default; @@ -335,9 +355,9 @@ await server.WaitPost(() => for (var i = 0; i < distinctComponents.Count; i++) { - var distinct = distinctComponents[i]; + var (components, references) = distinctComponents[i]; - if (distinct.references.Intersect(registration.References).Any()) + if (references.Intersect(registration.References).Any()) { // Ensure the next list if this one has conflicting references if (i + 1 >= distinctComponents.Count) @@ -349,8 +369,8 @@ await server.WaitPost(() => } // Add the component and its references if no conflicting references were found - distinct.components.Add(registration.Idx); - distinct.references.AddRange(registration.References); + components.Add(registration.Idx); + references.AddRange(registration.References); } } @@ -361,14 +381,14 @@ await server.WaitAssertion(() => { Assert.Multiple(() => { - foreach (var distinct in distinctComponents) + foreach (var (components, _) in distinctComponents) { var testLocation = grid.ToCoordinates(); var entity = entityManager.SpawnEntity("AllComponentsOneEntityDeleteTestEntity", testLocation); Assert.That(entityManager.GetComponent(entity).EntityInitialized); - foreach (var type in distinct.components) + foreach (var type in components) { var component = (Component) componentFactory.GetComponent(type); @@ -385,7 +405,7 @@ await server.WaitAssertion(() => continue; component.Owner = entity; - Logger.LogS(LogLevel.Debug, "EntityTest", $"Adding component: {name}"); + logmill.Debug($"Adding component: {name}"); // Note for the future coder: if an exception occurs where a component reference // was already occupied it might be because some component is ensuring another // initialize. diff --git a/Content.IntegrationTests/Tests/Fluids/FluidSpillTest.cs b/Content.IntegrationTests/Tests/Fluids/FluidSpillTest.cs index 8d3417c90f7..734d3cc9cac 100644 --- a/Content.IntegrationTests/Tests/Fluids/FluidSpillTest.cs +++ b/Content.IntegrationTests/Tests/Fluids/FluidSpillTest.cs @@ -1,14 +1,9 @@ #nullable enable -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Content.Server.Fluids.Components; using Content.Server.Fluids.EntitySystems; using Content.Server.Spreader; using Content.Shared.Chemistry.Components; using Content.Shared.FixedPoint; using Content.Shared.Fluids.Components; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Map.Components; @@ -75,8 +70,10 @@ await server.WaitAssertion(() => var grid = mapManager.GetGrid(gridId); var solution = new Solution("Blood", FixedPoint2.New(100)); var tileRef = grid.GetTileRef(puddleOrigin); +#pragma warning disable NUnit2045 // Interdependent tests Assert.That(puddleSystem.TrySpillAt(tileRef, solution, out _), Is.True); Assert.That(GetPuddle(entityManager, grid, puddleOrigin), Is.Not.Null); +#pragma warning restore NUnit2045 }); var sTimeToWait = (int) Math.Ceiling(2f * gameTiming.TickRate); @@ -87,8 +84,11 @@ await server.WaitAssertion(() => var grid = mapManager.GetGrid(gridId); var puddle = GetPuddle(entityManager, grid, puddleOrigin); + +#pragma warning disable NUnit2045 // Interdependent tests Assert.That(puddle, Is.Not.Null); Assert.That(puddleSystem.CurrentVolume(puddle!.Owner, puddle), Is.EqualTo(FixedPoint2.New(100))); +#pragma warning restore NUnit2045 for (var x = 0; x < 3; x++) { diff --git a/Content.IntegrationTests/Tests/Fluids/PuddleTest.cs b/Content.IntegrationTests/Tests/Fluids/PuddleTest.cs index 8e534da6933..8aaec0b55a2 100644 --- a/Content.IntegrationTests/Tests/Fluids/PuddleTest.cs +++ b/Content.IntegrationTests/Tests/Fluids/PuddleTest.cs @@ -1,16 +1,11 @@ -using System; -using System.Threading.Tasks; -using Content.Server.Fluids.Components; using Content.Server.Fluids.EntitySystems; using Content.Shared.Chemistry.Components; using Content.Shared.Coordinates; using Content.Shared.FixedPoint; using Content.Shared.Fluids.Components; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Map.Components; -using Robust.Shared.Timing; namespace Content.IntegrationTests.Tests.Fluids { @@ -21,7 +16,7 @@ public sealed class PuddleTest [Test] public async Task TilePuddleTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -36,9 +31,8 @@ await server.WaitAssertion(() => var gridUid = tile.GridUid; var (x, y) = tile.GridIndices; var coordinates = new EntityCoordinates(gridUid, x, y); - var puddle = spillSystem.TrySpillAt(coordinates, solution, out _); - Assert.True(puddle); + Assert.That(spillSystem.TrySpillAt(coordinates, solution, out _), Is.True); }); await PoolManager.RunTicksSync(pairTracker.Pair, 5); @@ -48,7 +42,7 @@ await server.WaitAssertion(() => [Test] public async Task SpaceNoPuddleTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -75,8 +69,8 @@ await server.WaitAssertion(() => { var coordinates = grid.ToCoordinates(); var solution = new Solution("Water", FixedPoint2.New(20)); - var puddle = spillSystem.TrySpillAt(coordinates, solution, out _); - Assert.False(puddle); + + Assert.That(spillSystem.TrySpillAt(coordinates, solution, out _), Is.False); }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/FollowerSystemTest.cs b/Content.IntegrationTests/Tests/FollowerSystemTest.cs index ceef0f35b6a..ba286b88e95 100644 --- a/Content.IntegrationTests/Tests/FollowerSystemTest.cs +++ b/Content.IntegrationTests/Tests/FollowerSystemTest.cs @@ -1,10 +1,5 @@ -using System; -using System.Linq; -using System.Threading.Tasks; using Content.Shared.Follower; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Map; @@ -19,7 +14,7 @@ public sealed class FollowerSystemTest [Test] public async Task FollowerMapDeleteTest() { - await using var pairTracker = await PoolManager.GetServerClient(new (){NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new() { NoClient = true }); var server = pairTracker.Pair.Server; var entMan = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/GameObjects/Components/ActionBlocking/HandCuffTest.cs b/Content.IntegrationTests/Tests/GameObjects/Components/ActionBlocking/HandCuffTest.cs index 478972d3ea5..10ddc528db1 100644 --- a/Content.IntegrationTests/Tests/GameObjects/Components/ActionBlocking/HandCuffTest.cs +++ b/Content.IntegrationTests/Tests/GameObjects/Components/ActionBlocking/HandCuffTest.cs @@ -1,13 +1,10 @@ #nullable enable -using System.Threading.Tasks; using Content.Server.Cuffs; using Content.Shared.Body.Components; using Content.Shared.Cuffs.Components; using Content.Shared.Hands.Components; -using NUnit.Framework; using Robust.Server.Console; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -39,15 +36,18 @@ public sealed class HandCuffTest public async Task Test() { await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings - {NoClient = true, ExtraPrototypes = Prototypes}); + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; EntityUid human; EntityUid otherHuman; EntityUid cuffs; EntityUid secondCuffs; - CuffableComponent cuffed; - HandsComponent hands; + CuffableComponent cuffed = default!; + HandsComponent hands = default!; var entityManager = server.ResolveDependency(); var mapManager = server.ResolveDependency(); @@ -59,6 +59,8 @@ await server.WaitAssertion(() => var coordinates = new MapCoordinates(Vector2.Zero, mapId); var cuffableSys = entityManager.System(); + var xformSys = entityManager.System(); + var xformQuery = entityManager.GetEntityQuery(); // Spawn the entities human = entityManager.SpawnEntity("HumanDummy", coordinates); @@ -66,38 +68,42 @@ await server.WaitAssertion(() => cuffs = entityManager.SpawnEntity("HandcuffsDummy", coordinates); secondCuffs = entityManager.SpawnEntity("HandcuffsDummy", coordinates); - entityManager.GetComponent(human).WorldPosition = - entityManager.GetComponent(otherHuman).WorldPosition; + var coords = xformSys.GetWorldPosition(otherHuman, xformQuery); + xformSys.SetWorldPosition(human, coords, xformQuery); // Test for components existing - Assert.True(entityManager.TryGetComponent(human, out cuffed!), - $"Human has no {nameof(CuffableComponent)}"); - Assert.True(entityManager.TryGetComponent(human, out hands!), $"Human has no {nameof(HandsComponent)}"); - Assert.True(entityManager.TryGetComponent(human, out BodyComponent? _), $"Human has no {nameof(BodyComponent)}"); - Assert.True(entityManager.TryGetComponent(cuffs, out HandcuffComponent? _), $"Handcuff has no {nameof(HandcuffComponent)}"); - Assert.True(entityManager.TryGetComponent(secondCuffs, out HandcuffComponent? _), $"Second handcuffs has no {nameof(HandcuffComponent)}"); + Assert.Multiple(() => + { + Assert.That(entityManager.TryGetComponent(human, out cuffed!), $"Human has no {nameof(CuffableComponent)}"); + Assert.That(entityManager.TryGetComponent(human, out hands!), $"Human has no {nameof(HandsComponent)}"); + Assert.That(entityManager.TryGetComponent(human, out BodyComponent? _), $"Human has no {nameof(BodyComponent)}"); + Assert.That(entityManager.TryGetComponent(cuffs, out HandcuffComponent? _), $"Handcuff has no {nameof(HandcuffComponent)}"); + Assert.That(entityManager.TryGetComponent(secondCuffs, out HandcuffComponent? _), $"Second handcuffs has no {nameof(HandcuffComponent)}"); + }); // Test to ensure cuffed players register the handcuffs cuffableSys.TryAddNewCuffs(human, human, cuffs, cuffed); - Assert.True(cuffed.CuffedHandCount > 0, - "Handcuffing a player did not result in their hands being cuffed"); + Assert.That(cuffed.CuffedHandCount, Is.GreaterThan(0), "Handcuffing a player did not result in their hands being cuffed"); // Test to ensure a player with 4 hands will still only have 2 hands cuffed AddHand(human, host); AddHand(human, host); - Assert.That(cuffed.CuffedHandCount, Is.EqualTo(2)); - Assert.That(hands.SortedHands.Count, Is.EqualTo(4)); + Assert.Multiple(() => + { + Assert.That(cuffed.CuffedHandCount, Is.EqualTo(2)); + Assert.That(hands.SortedHands, Has.Count.EqualTo(4)); + }); // Test to give a player with 4 hands 2 sets of cuffs cuffableSys.TryAddNewCuffs(human, human, secondCuffs, cuffed); - Assert.True(cuffed.CuffedHandCount == 4, "Player doesn't have correct amount of hands cuffed"); + Assert.That(cuffed.CuffedHandCount, Is.EqualTo(4), "Player doesn't have correct amount of hands cuffed"); }); await pairTracker.CleanReturnAsync(); } - private void AddHand(EntityUid to, IServerConsoleHost host) + private static void AddHand(EntityUid to, IServerConsoleHost host) { host.ExecuteCommand(null, $"addhand {to}"); } diff --git a/Content.IntegrationTests/Tests/GameObjects/Components/EntityPrototypeComponentsTest.cs b/Content.IntegrationTests/Tests/GameObjects/Components/EntityPrototypeComponentsTest.cs index 30006d59dca..fb537877683 100644 --- a/Content.IntegrationTests/Tests/GameObjects/Components/EntityPrototypeComponentsTest.cs +++ b/Content.IntegrationTests/Tests/GameObjects/Components/EntityPrototypeComponentsTest.cs @@ -1,10 +1,7 @@ -using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; -using System.Threading.Tasks; -using NUnit.Framework; using Robust.Shared.ContentPack; using Robust.Shared.GameObjects; using Robust.Shared.Utility; @@ -103,16 +100,16 @@ public async Task PrototypesHaveKnownComponents() var message = new StringBuilder(); - foreach (var unknownComponent in unknownComponentsClient) + foreach (var (entityId, component) in unknownComponentsClient) { message.Append( - $"CLIENT: Unknown component {unknownComponent.component} in prototype {unknownComponent.entityId}\n"); + $"CLIENT: Unknown component {component} in prototype {entityId}\n"); } - foreach (var unknownComponent in unknownComponentsServer) + foreach (var (entityId, component) in unknownComponentsServer) { message.Append( - $"SERVER: Unknown component {unknownComponent.component} in prototype {unknownComponent.entityId}\n"); + $"SERVER: Unknown component {component} in prototype {entityId}\n"); } Assert.Fail(message.ToString()); @@ -140,7 +137,7 @@ public async Task IgnoredComponentsExistInTheCorrectPlaces() failureMessages = $"{failureMessages}\nComponent {serverIgnored} was ignored on server, but does not exist on client"; } } - Assert.IsEmpty(failureMessages); + Assert.That(failureMessages, Is.Empty); await pairTracker.CleanReturnAsync(); } } diff --git a/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/AlertsComponentTests.cs b/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/AlertsComponentTests.cs index 7d8c45e68a6..bda249dda88 100644 --- a/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/AlertsComponentTests.cs +++ b/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/AlertsComponentTests.cs @@ -1,9 +1,7 @@ using System.Linq; -using System.Threading.Tasks; using Content.Client.UserInterface.Systems.Alerts.Controls; using Content.Client.UserInterface.Systems.Alerts.Widgets; using Content.Shared.Alert; -using NUnit.Framework; using Robust.Client.UserInterface; using Robust.Server.Player; using Robust.Shared.GameObjects; @@ -34,12 +32,14 @@ public async Task AlertsTest() await server.WaitAssertion(() => { playerUid = serverPlayerManager.Sessions.Single().AttachedEntity.GetValueOrDefault(); - Assert.That(playerUid != default); +#pragma warning disable NUnit2045 // Interdependent assertions. + Assert.That(playerUid, Is.Not.EqualTo(default)); // Making sure it exists Assert.That(entManager.HasComponent(playerUid)); +#pragma warning restore NUnit2045 var alerts = alertsSystem.GetActiveAlerts(playerUid); - Assert.IsNotNull(alerts); + Assert.That(alerts, Is.Not.Null); var alertCount = alerts.Count; alertsSystem.ShowAlert(playerUid, AlertType.Debug1); @@ -54,18 +54,20 @@ await server.WaitAssertion(() => await client.WaitAssertion(() => { var local = clientPlayerMgr.LocalPlayer; - Assert.NotNull(local); + Assert.That(local, Is.Not.Null); var controlled = local.ControlledEntity; - Assert.NotNull(controlled); +#pragma warning disable NUnit2045 // Interdependent assertions. + Assert.That(controlled, Is.Not.Null); // Making sure it exists Assert.That(clientEntManager.HasComponent(controlled.Value)); +#pragma warning restore Nunit2045 // find the alertsui clientAlertsUI = FindAlertsUI(clientUIMgr.ActiveScreen); - Assert.NotNull(clientAlertsUI); + Assert.That(clientAlertsUI, Is.Not.Null); - AlertsUI FindAlertsUI(Control control) + static AlertsUI FindAlertsUI(Control control) { if (control is AlertsUI alertUI) return alertUI; @@ -83,7 +85,7 @@ AlertsUI FindAlertsUI(Control control) Assert.That(clientAlertsUI.AlertContainer.ChildCount, Is.GreaterThanOrEqualTo(3)); var alertControls = clientAlertsUI.AlertContainer.Children.Select(c => (AlertControl) c); var alertIDs = alertControls.Select(ac => ac.Alert.AlertType).ToArray(); - var expectedIDs = new [] {AlertType.HumanHealth, AlertType.Debug1, AlertType.Debug2}; + var expectedIDs = new[] { AlertType.HumanHealth, AlertType.Debug1, AlertType.Debug2 }; Assert.That(alertIDs, Is.SupersetOf(expectedIDs)); }); @@ -100,7 +102,7 @@ await client.WaitAssertion(() => Assert.That(clientAlertsUI.AlertContainer.ChildCount, Is.GreaterThanOrEqualTo(2)); var alertControls = clientAlertsUI.AlertContainer.Children.Select(c => (AlertControl) c); var alertIDs = alertControls.Select(ac => ac.Alert.AlertType).ToArray(); - var expectedIDs = new [] {AlertType.HumanHealth, AlertType.Debug2}; + var expectedIDs = new[] { AlertType.HumanHealth, AlertType.Debug2 }; Assert.That(alertIDs, Is.SupersetOf(expectedIDs)); }); diff --git a/Content.IntegrationTests/Tests/GameRules/RuleMaxTimeRestartTest.cs b/Content.IntegrationTests/Tests/GameRules/RuleMaxTimeRestartTest.cs index d4f85486bc4..0174fcbb1f5 100644 --- a/Content.IntegrationTests/Tests/GameRules/RuleMaxTimeRestartTest.cs +++ b/Content.IntegrationTests/Tests/GameRules/RuleMaxTimeRestartTest.cs @@ -1,11 +1,8 @@ -using System; -using System.Threading.Tasks; -using Content.Server.GameTicking; +using Content.Server.GameTicking; using Content.Server.GameTicking.Commands; using Content.Server.GameTicking.Rules; using Content.Server.GameTicking.Rules.Components; using Content.Shared.CCVar; -using NUnit.Framework; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; using Robust.Shared.Timing; diff --git a/Content.IntegrationTests/Tests/GameRules/SecretStartsTest.cs b/Content.IntegrationTests/Tests/GameRules/SecretStartsTest.cs index 9fa3fedeea8..466aaa6163c 100644 --- a/Content.IntegrationTests/Tests/GameRules/SecretStartsTest.cs +++ b/Content.IntegrationTests/Tests/GameRules/SecretStartsTest.cs @@ -1,7 +1,5 @@ using System.Linq; -using System.Threading.Tasks; using Content.Server.GameTicking; -using NUnit.Framework; using Robust.Shared.GameObjects; namespace Content.IntegrationTests.Tests.GameRules; @@ -37,7 +35,7 @@ await server.WaitAssertion(() => { foreach (var rule in gameTicker.GetAddedGameRules()) { - Assert.That(gameTicker.GetActiveGameRules().Contains(rule)); + Assert.That(gameTicker.GetActiveGameRules(), Does.Contain(rule)); } // End all rules diff --git a/Content.IntegrationTests/Tests/GameRules/StartEndGameRulesTest.cs b/Content.IntegrationTests/Tests/GameRules/StartEndGameRulesTest.cs index 4309311b8cf..38cf03901da 100644 --- a/Content.IntegrationTests/Tests/GameRules/StartEndGameRulesTest.cs +++ b/Content.IntegrationTests/Tests/GameRules/StartEndGameRulesTest.cs @@ -1,9 +1,6 @@ -using System; using System.Linq; -using System.Threading.Tasks; using Content.Server.GameTicking; using Content.Shared.CCVar; -using NUnit.Framework; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; diff --git a/Content.IntegrationTests/Tests/Gravity/WeightlessStatusTests.cs b/Content.IntegrationTests/Tests/Gravity/WeightlessStatusTests.cs index 4f02e1dbb0f..5af8861c561 100644 --- a/Content.IntegrationTests/Tests/Gravity/WeightlessStatusTests.cs +++ b/Content.IntegrationTests/Tests/Gravity/WeightlessStatusTests.cs @@ -1,11 +1,6 @@ -using System.Threading.Tasks; using Content.Server.Gravity; using Content.Shared.Alert; -using Content.Shared.Coordinates; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Map; namespace Content.IntegrationTests.Tests.Gravity { @@ -37,7 +32,11 @@ public sealed class WeightlessStatusTests [Test] public async Task WeightlessStatusTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var entityManager = server.ResolveDependency(); @@ -51,7 +50,7 @@ await server.WaitAssertion(() => { human = entityManager.SpawnEntity("HumanDummy", testMap.GridCoords); - Assert.True(entityManager.TryGetComponent(human, out AlertsComponent alerts)); + Assert.That(entityManager.TryGetComponent(human, out AlertsComponent alerts)); }); // Let WeightlessSystem and GravitySystem tick @@ -60,7 +59,7 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { // No gravity without a gravity generator - Assert.True(alertsSystem.IsShowingAlert(human, AlertType.Weightless)); + Assert.That(alertsSystem.IsShowingAlert(human, AlertType.Weightless)); generatorUid = entityManager.SpawnEntity("GravityGeneratorDummy", entityManager.GetComponent(human).Coordinates); }); @@ -70,7 +69,7 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.False(alertsSystem.IsShowingAlert(human, AlertType.Weightless)); + Assert.That(alertsSystem.IsShowingAlert(human, AlertType.Weightless), Is.False); // This should kill gravity entityManager.DeleteEntity(generatorUid); @@ -80,7 +79,7 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.True(alertsSystem.IsShowingAlert(human, AlertType.Weightless)); + Assert.That(alertsSystem.IsShowingAlert(human, AlertType.Weightless)); }); await PoolManager.RunTicksSync(pairTracker.Pair, 10); diff --git a/Content.IntegrationTests/Tests/GravityGridTest.cs b/Content.IntegrationTests/Tests/GravityGridTest.cs index b1ea932b9ec..62df17d49fe 100644 --- a/Content.IntegrationTests/Tests/GravityGridTest.cs +++ b/Content.IntegrationTests/Tests/GravityGridTest.cs @@ -1,9 +1,7 @@ -using System.Threading.Tasks; using Content.Server.Gravity; using Content.Server.Power.Components; using Content.Shared.Coordinates; using Content.Shared.Gravity; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -31,7 +29,11 @@ public sealed class GravityGridTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -42,6 +44,8 @@ public async Task Test() MapGridComponent grid1 = null; MapGridComponent grid2 = null; + EntityUid grid1Entity = default!; + EntityUid grid2Entity = default!; // Create grids await server.WaitAssertion(() => @@ -49,10 +53,15 @@ await server.WaitAssertion(() => var mapId = testMap.MapId; grid1 = mapMan.CreateGrid(mapId); grid2 = mapMan.CreateGrid(mapId); + grid1Entity = grid1.Owner; + grid2Entity = grid2.Owner; generator = entityMan.SpawnEntity("GravityGeneratorDummy", grid2.ToCoordinates()); - Assert.That(entityMan.HasComponent(generator)); - Assert.That(entityMan.HasComponent(generator)); + Assert.Multiple(() => + { + Assert.That(entityMan.HasComponent(generator)); + Assert.That(entityMan.HasComponent(generator)); + }); var powerComponent = entityMan.GetComponent(generator); powerComponent.NeedsPower = false; @@ -65,13 +74,12 @@ await server.WaitAssertion(() => var generatorComponent = entityMan.GetComponent(generator); var powerComponent = entityMan.GetComponent(generator); - Assert.That(generatorComponent.GravityActive, Is.True); - - var grid1Entity = grid1.Owner; - var grid2Entity = grid2.Owner; - - Assert.That(!entityMan.GetComponent(grid1Entity).EnabledVV); - Assert.That(entityMan.GetComponent(grid2Entity).EnabledVV); + Assert.Multiple(() => + { + Assert.That(generatorComponent.GravityActive, Is.True); + Assert.That(!entityMan.GetComponent(grid1Entity).EnabledVV); + Assert.That(entityMan.GetComponent(grid2Entity).EnabledVV); + }); // Re-enable needs power so it turns off again. // Charge rate is ridiculously high so it finishes in one tick. @@ -84,11 +92,11 @@ await server.WaitAssertion(() => { var generatorComponent = entityMan.GetComponent(generator); - Assert.That(generatorComponent.GravityActive, Is.False); - - var grid2Entity = grid2.Owner; - - Assert.That(entityMan.GetComponent(grid2Entity).EnabledVV, Is.False); + Assert.Multiple(() => + { + Assert.That(generatorComponent.GravityActive, Is.False); + Assert.That(entityMan.GetComponent(grid2Entity).EnabledVV, Is.False); + }); }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/Guidebook/DocumentParsingTest.cs b/Content.IntegrationTests/Tests/Guidebook/DocumentParsingTest.cs index b556d54594b..edc19b531e8 100644 --- a/Content.IntegrationTests/Tests/Guidebook/DocumentParsingTest.cs +++ b/Content.IntegrationTests/Tests/Guidebook/DocumentParsingTest.cs @@ -1,10 +1,8 @@ #nullable enable using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Threading.Tasks; using Content.Client.Guidebook; using Content.Client.Guidebook.Richtext; -using NUnit.Framework; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; @@ -19,13 +17,13 @@ public sealed class DocumentParsingTest { public string TestDocument = @"multiple - lines - separated by -only single newlines + lines + separated by +only single newlines make a single rich text control -unless there is a double newline. Also -whitespace before newlines are ignored. +unless there is a double newline. Also +whitespace before newlines are ignored. @@ -36,10 +34,10 @@ some text with a nested control - - + \\>=\""=<-_?*3.0//""> "; @@ -64,12 +62,15 @@ await client.WaitPost(() => var richText1 = ctrl.GetChild(0) as RichTextLabel; var richText2 = ctrl.GetChild(1) as RichTextLabel; - Assert.NotNull(richText1); - Assert.NotNull(richText2); + Assert.Multiple(() => + { + Assert.That(richText1, Is.Not.Null); + Assert.That(richText2, Is.Not.Null); + }); // uhh.. WTF. rich text has no means of getting the contents!?!? // TODO assert text content is correct after fixing that bullshit. - //Assert.That(richText1?.Text, Is.EqualTo("multiple lines separated by only single newlines make a single rich text control")); + // Assert.That(richText1?.Text, Is.EqualTo("multiple lines separated by only single newlines make a single rich text control")); // Assert.That(richText2?.Text, Is.EqualTo("unless there is a double newline. Also whitespace before newlines are ignored.")); var test1 = ctrl.GetChild(2) as TestControl; @@ -78,45 +79,56 @@ await client.WaitPost(() => var test4 = ctrl.GetChild(5) as TestControl; var test5 = ctrl.GetChild(6) as TestControl; - Assert.NotNull(test1); - Assert.NotNull(test2); - Assert.NotNull(test3); - Assert.NotNull(test4); - Assert.NotNull(test5); + Assert.Multiple(() => + { + Assert.That(test1, Is.Not.Null); + Assert.That(test2, Is.Not.Null); + Assert.That(test3, Is.Not.Null); + Assert.That(test4, Is.Not.Null); + Assert.That(test5, Is.Not.Null); + }); - Assert.That(test1!.ChildCount, Is.EqualTo(0)); - Assert.That(test2!.ChildCount, Is.EqualTo(0)); - Assert.That(test3!.ChildCount, Is.EqualTo(2)); - Assert.That(test4!.ChildCount, Is.EqualTo(0)); - Assert.That(test5!.ChildCount, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(test1!.ChildCount, Is.EqualTo(0)); + Assert.That(test2!.ChildCount, Is.EqualTo(0)); + Assert.That(test3!.ChildCount, Is.EqualTo(2)); + Assert.That(test4!.ChildCount, Is.EqualTo(0)); + Assert.That(test5!.ChildCount, Is.EqualTo(1)); + }); - var subText = test3.GetChild(0) as RichTextLabel; + var subText = test3!.GetChild(0) as RichTextLabel; var subTest = test3.GetChild(1) as TestControl; - Assert.NotNull(subText); + +#pragma warning disable NUnit2045 + Assert.That(subText, Is.Not.Null); //Assert.That(subText?.Text, Is.EqualTo("some text with a nested control")); - Assert.NotNull(subTest); + Assert.That(subTest, Is.Not.Null); Assert.That(subTest?.ChildCount, Is.EqualTo(0)); +#pragma warning restore NUnit2045 - var subTest2 = test5.GetChild(0) as TestControl; - Assert.NotNull(subTest2); + var subTest2 = test5!.GetChild(0) as TestControl; + Assert.That(subTest2, Is.Not.Null); Assert.That(subTest2!.ChildCount, Is.EqualTo(0)); - Assert.That(test1.Params.Count, Is.EqualTo(0)); - Assert.That(test2.Params.Count, Is.EqualTo(0)); - Assert.That(test3.Params.Count, Is.EqualTo(0)); - Assert.That(test4.Params.Count, Is.EqualTo(3)); - Assert.That(test5.Params.Count, Is.EqualTo(0)); - Assert.That(subTest2.Params.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(test1!.Params, Has.Count.EqualTo(0)); + Assert.That(test2!.Params, Has.Count.EqualTo(0)); + Assert.That(test3.Params, Has.Count.EqualTo(0)); + Assert.That(test4!.Params, Has.Count.EqualTo(3)); + Assert.That(test5.Params, Has.Count.EqualTo(0)); + Assert.That(subTest2.Params, Has.Count.EqualTo(1)); + }); - string? val; - test4.Params.TryGetValue("key1", out val); + test4!.Params.TryGetValue("key1", out var val); Assert.That(val, Is.EqualTo("value1")); test4.Params.TryGetValue("key2", out val); Assert.That(val, Is.EqualTo("value2 with spaces")); test4.Params.TryGetValue("key3", out val); - Assert.That(val, Is.EqualTo(@"value3 with a + Assert.That(val, Is.EqualTo(@"value3 with a newline")); subTest2.Params.TryGetValue("k", out val); diff --git a/Content.IntegrationTests/Tests/Guidebook/GuideEntryPrototypeTests.cs b/Content.IntegrationTests/Tests/Guidebook/GuideEntryPrototypeTests.cs index 73fa2defe40..e8686c097d7 100644 --- a/Content.IntegrationTests/Tests/Guidebook/GuideEntryPrototypeTests.cs +++ b/Content.IntegrationTests/Tests/Guidebook/GuideEntryPrototypeTests.cs @@ -1,10 +1,8 @@ using Content.Client.Guidebook; using Content.Client.Guidebook.Richtext; -using NUnit.Framework; using Robust.Shared.ContentPack; using Robust.Shared.Prototypes; using System.Linq; -using System.Threading.Tasks; namespace Content.IntegrationTests.Tests.Guidebook; diff --git a/Content.IntegrationTests/Tests/Hands/HandTests.cs b/Content.IntegrationTests/Tests/Hands/HandTests.cs index aadec1c079d..1115ea1ad6a 100644 --- a/Content.IntegrationTests/Tests/Hands/HandTests.cs +++ b/Content.IntegrationTests/Tests/Hands/HandTests.cs @@ -1,8 +1,6 @@ using System.Linq; -using System.Threading.Tasks; using Content.Shared.Hands.Components; using Content.Shared.Hands.EntitySystems; -using NUnit.Framework; using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.Map; @@ -40,7 +38,7 @@ await server.WaitPost(() => // run ticks here is important, as errors may happen within the container system's frame update methods. await PoolManager.RunTicksSync(pairTracker.Pair, 5); - Assert.That(hands.ActiveHandEntity == item); + Assert.That(hands.ActiveHandEntity, Is.EqualTo(item)); await server.WaitPost(() => { @@ -48,7 +46,7 @@ await server.WaitPost(() => }); await PoolManager.RunTicksSync(pairTracker.Pair, 5); - Assert.That(hands.ActiveHandEntity == null); + Assert.That(hands.ActiveHandEntity, Is.Null); await server.WaitPost(() => mapMan.DeleteMap(data.MapId)); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/HumanInventoryUniformSlotsTest.cs b/Content.IntegrationTests/Tests/HumanInventoryUniformSlotsTest.cs index 9aa19d8d4fe..df5ad790999 100644 --- a/Content.IntegrationTests/Tests/HumanInventoryUniformSlotsTest.cs +++ b/Content.IntegrationTests/Tests/HumanInventoryUniformSlotsTest.cs @@ -1,9 +1,5 @@ -using System.Threading.Tasks; using Content.Shared.Inventory; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Map; namespace Content.IntegrationTests.Tests { @@ -58,7 +54,7 @@ public sealed class HumanInventoryUniformSlotsTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); var coordinates = testMap.GridCoords; @@ -82,21 +78,32 @@ await server.WaitAssertion(() => var tooBigItem = entityMan.SpawnEntity("ToolboxDummy", coordinates); - Assert.That(invSystem.CanEquip(human, uniform, "jumpsuit", out _)); + Assert.Multiple(() => + { + Assert.That(invSystem.CanEquip(human, uniform, "jumpsuit", out _)); - // Can't equip any of these since no uniform! - Assert.That(invSystem.CanEquip(human, idCard, "id", out _), Is.False); - Assert.That(invSystem.CanEquip(human, pocketItem, "pocket1", out _), Is.False); - Assert.That(invSystem.CanEquip(human, tooBigItem, "pocket2", out _), Is.False); // This one fails either way. + // Can't equip any of these since no uniform! + Assert.That(invSystem.CanEquip(human, idCard, "id", out _), Is.False); + Assert.That(invSystem.CanEquip(human, pocketItem, "pocket1", out _), Is.False); + Assert.That(invSystem.CanEquip(human, tooBigItem, "pocket2", out _), Is.False); // This one fails either way. + }); - Assert.That(invSystem.TryEquip(human, uniform, "jumpsuit")); + Assert.Multiple(() => + { + Assert.That(invSystem.TryEquip(human, uniform, "jumpsuit")); + Assert.That(invSystem.TryEquip(human, idCard, "id")); + }); - Assert.That(invSystem.TryEquip(human, idCard, "id")); +#pragma warning disable NUnit2045 Assert.That(invSystem.CanEquip(human, tooBigItem, "pocket1", out _), Is.False); // Still failing! Assert.That(invSystem.TryEquip(human, pocketItem, "pocket1")); +#pragma warning restore NUnit2045 - Assert.That(IsDescendant(idCard, human, entityMan)); - Assert.That(IsDescendant(pocketItem, human, entityMan)); + Assert.Multiple(() => + { + Assert.That(IsDescendant(idCard, human, entityMan)); + Assert.That(IsDescendant(pocketItem, human, entityMan)); + }); // Now drop the jumpsuit. Assert.That(invSystem.TryUnequip(human, "jumpsuit")); @@ -106,15 +113,18 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // Items have been dropped! - Assert.That(IsDescendant(uniform, human, entityMan), Is.False); - Assert.That(IsDescendant(idCard, human, entityMan), Is.False); - Assert.That(IsDescendant(pocketItem, human, entityMan), Is.False); - - // Ensure everything null here. - Assert.That(!invSystem.TryGetSlotEntity(human, "jumpsuit", out _)); - Assert.That(!invSystem.TryGetSlotEntity(human, "id", out _)); - Assert.That(!invSystem.TryGetSlotEntity(human, "pocket1", out _)); + Assert.Multiple(() => + { + // Items have been dropped! + Assert.That(IsDescendant(uniform, human, entityMan), Is.False); + Assert.That(IsDescendant(idCard, human, entityMan), Is.False); + Assert.That(IsDescendant(pocketItem, human, entityMan), Is.False); + + // Ensure everything null here. + Assert.That(!invSystem.TryGetSlotEntity(human, "jumpsuit", out _)); + Assert.That(!invSystem.TryGetSlotEntity(human, "id", out _)); + Assert.That(!invSystem.TryGetSlotEntity(human, "pocket1", out _)); + }); }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/Interaction/Click/InteractionSystemTests.cs b/Content.IntegrationTests/Tests/Interaction/Click/InteractionSystemTests.cs index 174fe62721c..ff1466fbfaa 100644 --- a/Content.IntegrationTests/Tests/Interaction/Click/InteractionSystemTests.cs +++ b/Content.IntegrationTests/Tests/Interaction/Click/InteractionSystemTests.cs @@ -1,11 +1,9 @@ #nullable enable annotations -using System.Threading.Tasks; using Content.Server.Interaction; using Content.Shared.Hands.Components; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction; using Content.Shared.Item; -using NUnit.Framework; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Map; @@ -39,7 +37,11 @@ public sealed class InteractionSystemTests [Test] public async Task InteractionTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); @@ -73,19 +75,28 @@ await server.WaitAssertion(() => await server.WaitRunTicks(1); var entitySystemManager = server.ResolveDependency(); - Assert.That(entitySystemManager.TryGetEntitySystem(out var interactionSystem)); - Assert.That(entitySystemManager.TryGetEntitySystem(out var testInteractionSystem)); + InteractionSystem interactionSystem = default!; + TestInteractionSystem testInteractionSystem = default!; + + Assert.Multiple(() => + { + Assert.That(entitySystemManager.TryGetEntitySystem(out interactionSystem)); + Assert.That(entitySystemManager.TryGetEntitySystem(out testInteractionSystem)); + }); var interactUsing = false; var interactHand = false; await server.WaitAssertion(() => { - testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; - testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; + testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; + testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); - Assert.That(interactUsing, Is.False); - Assert.That(interactHand); + Assert.Multiple(() => + { + Assert.That(interactUsing, Is.False); + Assert.That(interactHand); + }); Assert.That(handSys.TryPickup(user, item)); @@ -100,7 +111,11 @@ await server.WaitAssertion(() => [Test] public async Task InteractionObstructionTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); @@ -136,19 +151,27 @@ await server.WaitAssertion(() => await server.WaitRunTicks(1); var entitySystemManager = server.ResolveDependency(); - Assert.That(entitySystemManager.TryGetEntitySystem(out var interactionSystem)); - Assert.That(entitySystemManager.TryGetEntitySystem(out var testInteractionSystem)); + InteractionSystem interactionSystem = default!; + TestInteractionSystem testInteractionSystem = default!; + Assert.Multiple(() => + { + Assert.That(entitySystemManager.TryGetEntitySystem(out interactionSystem)); + Assert.That(entitySystemManager.TryGetEntitySystem(out testInteractionSystem)); + }); var interactUsing = false; var interactHand = false; await server.WaitAssertion(() => { - testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; - testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; + testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; + testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); - Assert.That(interactUsing, Is.False); - Assert.That(interactHand, Is.False); + Assert.Multiple(() => + { + Assert.That(interactUsing, Is.False); + Assert.That(interactHand, Is.False); + }); Assert.That(handSys.TryPickup(user, item)); @@ -163,7 +186,7 @@ await server.WaitAssertion(() => [Test] public async Task InteractionInRangeTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); @@ -197,19 +220,27 @@ await server.WaitAssertion(() => await server.WaitRunTicks(1); var entitySystemManager = server.ResolveDependency(); - Assert.That(entitySystemManager.TryGetEntitySystem(out var interactionSystem)); - Assert.That(entitySystemManager.TryGetEntitySystem(out var testInteractionSystem)); + InteractionSystem interactionSystem = default!; + TestInteractionSystem testInteractionSystem = default!; + Assert.Multiple(() => + { + Assert.That(entitySystemManager.TryGetEntitySystem(out interactionSystem)); + Assert.That(entitySystemManager.TryGetEntitySystem(out testInteractionSystem)); + }); var interactUsing = false; var interactHand = false; await server.WaitAssertion(() => { - testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; - testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; + testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; + testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); - Assert.That(interactUsing, Is.False); - Assert.That(interactHand); + Assert.Multiple(() => + { + Assert.That(interactUsing, Is.False); + Assert.That(interactHand); + }); Assert.That(handSys.TryPickup(user, item)); @@ -225,7 +256,7 @@ await server.WaitAssertion(() => [Test] public async Task InteractionOutOfRangeTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); @@ -259,19 +290,27 @@ await server.WaitAssertion(() => await server.WaitRunTicks(1); var entitySystemManager = server.ResolveDependency(); - Assert.That(entitySystemManager.TryGetEntitySystem(out var interactionSystem)); - Assert.That(entitySystemManager.TryGetEntitySystem(out var testInteractionSystem)); + InteractionSystem interactionSystem = default!; + TestInteractionSystem testInteractionSystem = default!; + Assert.Multiple(() => + { + Assert.That(entitySystemManager.TryGetEntitySystem(out interactionSystem)); + Assert.That(entitySystemManager.TryGetEntitySystem(out testInteractionSystem)); + }); var interactUsing = false; var interactHand = false; await server.WaitAssertion(() => { - testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; - testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; + testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; + testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); - Assert.That(interactUsing, Is.False); - Assert.That(interactHand, Is.False); + Assert.Multiple(() => + { + Assert.That(interactUsing, Is.False); + Assert.That(interactHand, Is.False); + }); Assert.That(handSys.TryPickup(user, item)); @@ -286,7 +325,7 @@ await server.WaitAssertion(() => [Test] public async Task InsideContainerInteractionBlockTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); @@ -325,8 +364,13 @@ await server.WaitAssertion(() => await server.WaitRunTicks(1); var entitySystemManager = server.ResolveDependency(); - Assert.That(entitySystemManager.TryGetEntitySystem(out var interactionSystem)); - Assert.That(entitySystemManager.TryGetEntitySystem(out var testInteractionSystem)); + InteractionSystem interactionSystem = default!; + TestInteractionSystem testInteractionSystem = default!; + Assert.Multiple(() => + { + Assert.That(entitySystemManager.TryGetEntitySystem(out interactionSystem)); + Assert.That(entitySystemManager.TryGetEntitySystem(out testInteractionSystem)); + }); await server.WaitIdleAsync(); @@ -334,19 +378,27 @@ await server.WaitAssertion(() => var interactHand = false; await server.WaitAssertion(() => { +#pragma warning disable NUnit2045 // Interdependent assertions. Assert.That(container.Insert(user)); Assert.That(sEntities.GetComponent(user).ParentUid, Is.EqualTo(containerEntity)); +#pragma warning restore NUnit2045 - testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactUsing = true; }; - testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactHand = true; }; + testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactUsing = true; }; + testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactHand = true; }; interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); - Assert.That(interactUsing, Is.False); - Assert.That(interactHand, Is.False); + Assert.Multiple(() => + { + Assert.That(interactUsing, Is.False); + Assert.That(interactHand, Is.False); + }); interactionSystem.UserInteraction(user, sEntities.GetComponent(containerEntity).Coordinates, containerEntity); - Assert.That(interactUsing, Is.False); - Assert.That(interactHand); + Assert.Multiple(() => + { + Assert.That(interactUsing, Is.False); + Assert.That(interactHand); + }); Assert.That(handSys.TryPickup(user, item)); diff --git a/Content.IntegrationTests/Tests/Interaction/InRangeUnobstructed.cs b/Content.IntegrationTests/Tests/Interaction/InRangeUnobstructed.cs index 385658b3c59..f7b77f454e2 100644 --- a/Content.IntegrationTests/Tests/Interaction/InRangeUnobstructed.cs +++ b/Content.IntegrationTests/Tests/Interaction/InRangeUnobstructed.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; using Content.Shared.Interaction; -using NUnit.Framework; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Map; @@ -27,7 +25,7 @@ public sealed class InRangeUnobstructed [Test] public async Task EntityEntityTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); @@ -51,50 +49,61 @@ await server.WaitAssertion(() => await server.WaitIdleAsync(); - var interactionSys = server.ResolveDependency().GetEntitySystem(); + var interactionSys = sEntities.System(); + var xformSys = sEntities.System(); + var xform = sEntities.GetComponent(origin); await server.WaitAssertion(() => { - // Entity <-> Entity - Assert.True(interactionSys.InRangeUnobstructed(origin, other)); - Assert.True(interactionSys.InRangeUnobstructed(other, origin)); + Assert.Multiple(() => + { + // Entity <-> Entity + Assert.That(interactionSys.InRangeUnobstructed(origin, other)); + Assert.That(interactionSys.InRangeUnobstructed(other, origin)); - // Entity <-> MapCoordinates - Assert.True(interactionSys.InRangeUnobstructed(origin, mapCoordinates)); - Assert.True(interactionSys.InRangeUnobstructed(mapCoordinates, origin)); + // Entity <-> MapCoordinates + Assert.That(interactionSys.InRangeUnobstructed(origin, mapCoordinates)); + Assert.That(interactionSys.InRangeUnobstructed(mapCoordinates, origin)); + }); // Move them slightly apart - sEntities.GetComponent(origin).LocalPosition += _interactionRangeDivided15X; + xformSys.SetLocalPosition(origin, xform.LocalPosition + _interactionRangeDivided15X, xform); - // Entity <-> Entity - // Entity <-> Entity - Assert.True(interactionSys.InRangeUnobstructed(origin, other)); - Assert.True(interactionSys.InRangeUnobstructed(other, origin)); + Assert.Multiple(() => + { + // Entity <-> Entity + // Entity <-> Entity + Assert.That(interactionSys.InRangeUnobstructed(origin, other)); + Assert.That(interactionSys.InRangeUnobstructed(other, origin)); - // Entity <-> MapCoordinates - Assert.True(interactionSys.InRangeUnobstructed(origin, mapCoordinates)); - Assert.True(interactionSys.InRangeUnobstructed(mapCoordinates, origin)); + // Entity <-> MapCoordinates + Assert.That(interactionSys.InRangeUnobstructed(origin, mapCoordinates)); + Assert.That(interactionSys.InRangeUnobstructed(mapCoordinates, origin)); + }); // Move them out of range - sEntities.GetComponent(origin).LocalPosition += new Vector2(InteractionRangeDivided15 + HumanRadius * 2f, 0f); + xformSys.SetLocalPosition(origin, xform.LocalPosition + new Vector2(InteractionRangeDivided15 + HumanRadius * 2f, 0f), xform); - // Entity <-> Entity - Assert.False(interactionSys.InRangeUnobstructed(origin, other)); - Assert.False(interactionSys.InRangeUnobstructed(other, origin)); + Assert.Multiple(() => + { + // Entity <-> Entity + Assert.That(interactionSys.InRangeUnobstructed(origin, other), Is.False); + Assert.That(interactionSys.InRangeUnobstructed(other, origin), Is.False); - // Entity <-> MapCoordinates - Assert.False(interactionSys.InRangeUnobstructed(origin, mapCoordinates)); - Assert.False(interactionSys.InRangeUnobstructed(mapCoordinates, origin)); + // Entity <-> MapCoordinates + Assert.That(interactionSys.InRangeUnobstructed(origin, mapCoordinates), Is.False); + Assert.That(interactionSys.InRangeUnobstructed(mapCoordinates, origin), Is.False); - // Checks with increased range + // Checks with increased range - // Entity <-> Entity - Assert.True(interactionSys.InRangeUnobstructed(origin, other, InteractionRangeDivided15Times3)); - Assert.True(interactionSys.InRangeUnobstructed(other, origin, InteractionRangeDivided15Times3)); + // Entity <-> Entity + Assert.That(interactionSys.InRangeUnobstructed(origin, other, InteractionRangeDivided15Times3)); + Assert.That(interactionSys.InRangeUnobstructed(other, origin, InteractionRangeDivided15Times3)); - // Entity <-> MapCoordinates - Assert.True(interactionSys.InRangeUnobstructed(origin, mapCoordinates, InteractionRangeDivided15Times3)); - Assert.True(interactionSys.InRangeUnobstructed(mapCoordinates, origin, InteractionRangeDivided15Times3)); + // Entity <-> MapCoordinates + Assert.That(interactionSys.InRangeUnobstructed(origin, mapCoordinates, InteractionRangeDivided15Times3)); + Assert.That(interactionSys.InRangeUnobstructed(mapCoordinates, origin, InteractionRangeDivided15Times3)); + }); }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/Interaction/InteractionTest.EntitySpecifier.cs b/Content.IntegrationTests/Tests/Interaction/InteractionTest.EntitySpecifier.cs index 2e8314ec975..86aaa68c822 100644 --- a/Content.IntegrationTests/Tests/Interaction/InteractionTest.EntitySpecifier.cs +++ b/Content.IntegrationTests/Tests/Interaction/InteractionTest.EntitySpecifier.cs @@ -1,7 +1,5 @@ #nullable enable -using System.Threading.Tasks; using Content.Shared.Stacks; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Prototypes; @@ -41,7 +39,7 @@ protected sealed class EntitySpecifier public EntitySpecifier(string prototype, int quantity, bool converted = false) { - Assert.That(quantity > 0); + Assert.That(quantity, Is.GreaterThan(0)); Prototype = prototype; Quantity = quantity; Converted = converted; @@ -109,7 +107,7 @@ await Server.WaitPost(() => } Assert.That(spec.Quantity, Is.EqualTo(1), "SpawnEntity only supports returning a singular entity"); - await Server.WaitPost(() => uid = SEntMan.SpawnEntity(spec.Prototype, coords));; + await Server.WaitPost(() => uid = SEntMan.SpawnEntity(spec.Prototype, coords)); return uid; } @@ -120,11 +118,11 @@ await Server.WaitPost(() => protected EntitySpecifier ToEntitySpecifier(EntityUid uid) { if (SEntMan.TryGetComponent(uid, out StackComponent? stack)) - return new EntitySpecifier(stack.StackTypeId, stack.Count) {Converted = true}; + return new EntitySpecifier(stack.StackTypeId, stack.Count) { Converted = true }; var meta = SEntMan.GetComponent(uid); - Assert.NotNull(meta.EntityPrototype); + Assert.That(meta.EntityPrototype, Is.Not.Null); - return new (meta.EntityPrototype!.ID, 1) { Converted = true }; + return new(meta.EntityPrototype!.ID, 1) { Converted = true }; } } diff --git a/Content.IntegrationTests/Tests/Interaction/InteractionTest.EntitySpecifierCollection.cs b/Content.IntegrationTests/Tests/Interaction/InteractionTest.EntitySpecifierCollection.cs index 9b6b0af8dc8..0af2747662c 100644 --- a/Content.IntegrationTests/Tests/Interaction/InteractionTest.EntitySpecifierCollection.cs +++ b/Content.IntegrationTests/Tests/Interaction/InteractionTest.EntitySpecifierCollection.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using Content.Shared.Stacks; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Prototypes; using Robust.Shared.Utility; @@ -53,10 +52,14 @@ public static implicit operator EntitySpecifierCollection((string, int) tuple) } public void Remove(EntitySpecifier spec) - => Add(new EntitySpecifier(spec.Prototype, -spec.Quantity, spec.Converted)); + { + Add(new EntitySpecifier(spec.Prototype, -spec.Quantity, spec.Converted)); + } public void Add(EntitySpecifier spec) - => Add(spec.Prototype, spec.Quantity, spec.Converted); + { + Add(spec.Prototype, spec.Quantity, spec.Converted); + } public void Add(string id, int quantity, bool converted = false) { diff --git a/Content.IntegrationTests/Tests/Interaction/InteractionTest.Helpers.cs b/Content.IntegrationTests/Tests/Interaction/InteractionTest.Helpers.cs index 1f9727fa24e..7fccab140df 100644 --- a/Content.IntegrationTests/Tests/Interaction/InteractionTest.Helpers.cs +++ b/Content.IntegrationTests/Tests/Interaction/InteractionTest.Helpers.cs @@ -1,12 +1,8 @@ #nullable enable -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Linq.Expressions; using System.Reflection; -using System.Threading.Tasks; -using Content.Client.Chemistry.UI; using Content.Client.Construction; using Content.Server.Atmos; using Content.Server.Atmos.Components; @@ -19,15 +15,11 @@ using Content.Shared.Construction.Prototypes; using Content.Shared.Gravity; using Content.Shared.Item; -using NUnit.Framework; -using OpenToolkit.GraphicsLibraryFramework; using Robust.Client.GameObjects; using Robust.Client.UserInterface; -using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; using Robust.Shared.GameObjects; using Robust.Shared.Input; -using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Map.Components; using Robust.Shared.Maths; @@ -67,7 +59,7 @@ protected async Task CraftItem(string prototype, bool shouldSucceed = true) Assert.That(ProtoMan.Index(prototype).Type, Is.EqualTo(ConstructionType.Item)); // Please someone purge async construction code - Task task =default!; + Task task = default!; await Server.WaitPost(() => task = SConstruction.TryStartItemConstruction(prototype, Player)); Task? tickTask = null; @@ -119,18 +111,18 @@ protected async Task StartDeconstruction(string prototype) /// protected async Task DeleteHeldEntity() { - if (Hands.ActiveHandEntity is {} held) + if (Hands.ActiveHandEntity is { } held) { await Server.WaitPost(() => { Assert.That(HandSys.TryDrop(Player, null, false, true, Hands)); SEntMan.DeleteEntity(held); - Logger.Debug($"Deleting held entity"); + SLogger.Debug($"Deleting held entity"); }); } await RunTicks(1); - Assert.That(Hands.ActiveHandEntity == null); + Assert.That(Hands.ActiveHandEntity, Is.Null); } /// @@ -140,7 +132,9 @@ await Server.WaitPost(() => /// Automatically enables welders. /// protected async Task PlaceInHands(string? id, int quantity = 1, bool enableWelder = true) - => await PlaceInHands(id == null ? null : (id, quantity), enableWelder); + { + return await PlaceInHands(id == null ? null : (id, quantity), enableWelder); + } /// /// Place an entity prototype into the players hand. Deletes any currently held entity. @@ -161,12 +155,12 @@ await Server.WaitPost(() => if (entity == null || string.IsNullOrWhiteSpace(entity.Prototype)) { await RunTicks(1); - Assert.That(Hands.ActiveHandEntity == null); + Assert.That(Hands.ActiveHandEntity, Is.Null); return null; } // spawn and pick up the new item - EntityUid item = await SpawnEntity(entity, PlayerCoords); + var item = await SpawnEntity(entity, PlayerCoords); WelderComponent? welder = null; await Server.WaitPost(() => @@ -234,7 +228,7 @@ await Server.WaitPost(() => }); await RunTicks(1); - Assert.IsNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Null); } #region Interact @@ -244,7 +238,7 @@ await Server.WaitPost(() => /// protected async Task UseInHand() { - if (Hands.ActiveHandEntity is not {} target) + if (Hands.ActiveHandEntity is not { } target) { Assert.Fail("Not holding any entity"); return; @@ -263,7 +257,9 @@ await Server.WaitPost(() => /// Empty strings imply empty hands. /// protected async Task Interact(string id, int quantity = 1, bool shouldSucceed = true, bool awaitDoAfters = true) - => await Interact((id, quantity), shouldSucceed, awaitDoAfters); + { + await Interact((id, quantity), shouldSucceed, awaitDoAfters); + } /// /// Place an entity prototype into the players hand and interact with the given entity (or target position) @@ -406,7 +402,7 @@ protected async Task CheckTargetChange(bool shouldSucceed) Assert.That(CTestSystem.Ghosts.TryGetValue(ConstructionGhostId, out newTarget), $"Failed to get construction entity from ghost Id"); - await Client.WaitPost(() => Logger.Debug($"Construction ghost {ConstructionGhostId} became entity {newTarget}")); + await Client.WaitPost(() => CLogger.Debug($"Construction ghost {ConstructionGhostId} became entity {newTarget}")); Target = newTarget; } } @@ -414,7 +410,7 @@ protected async Task CheckTargetChange(bool shouldSucceed) if (STestSystem.EntChanges.TryGetValue(Target.Value, out newTarget)) { await Server.WaitPost( - () => Logger.Debug($"Construction entity {Target.Value} changed to {newTarget}")); + () => SLogger.Debug($"Construction entity {Target.Value} changed to {newTarget}")); Target = newTarget; } @@ -449,8 +445,12 @@ protected void AssertAnchored(bool anchored = true, EntityUid? target = null) var sXform = SEntMan.GetComponent(target.Value); var cXform = CEntMan.GetComponent(target.Value); - Assert.That(sXform.Anchored, Is.EqualTo(anchored)); - Assert.That(cXform.Anchored, Is.EqualTo(anchored)); + + Assert.Multiple(() => + { + Assert.That(sXform.Anchored, Is.EqualTo(anchored)); + Assert.That(cXform.Anchored, Is.EqualTo(anchored)); + }); } protected void AssertDeleted(bool deleted = true, EntityUid? target = null) @@ -462,8 +462,11 @@ protected void AssertDeleted(bool deleted = true, EntityUid? target = null) return; } - Assert.That(SEntMan.Deleted(target), Is.EqualTo(deleted)); - Assert.That(CEntMan.Deleted(target), Is.EqualTo(deleted)); + Assert.Multiple(() => + { + Assert.That(SEntMan.Deleted(target), Is.EqualTo(deleted)); + Assert.That(CEntMan.Deleted(target), Is.EqualTo(deleted)); + }); } /// @@ -490,7 +493,7 @@ protected async Task AssertTile(string? proto, EntityCoordinates? coords = null) ? Tile.Empty : new Tile(TileMan[proto].TileId); - Tile tile = Tile.Empty; + var tile = Tile.Empty; var pos = (coords ?? TargetCoords).ToMap(SEntMan, Transform); await Server.WaitPost(() => { @@ -685,7 +688,7 @@ await Server.WaitPost(() => await AssertTile(proto, coords); } - protected async Task Delete(EntityUid uid) + protected async Task Delete(EntityUid uid) { await Server.WaitPost(() => SEntMan.DeleteEntity(uid)); await RunTicks(5); @@ -699,10 +702,14 @@ protected async Task RunTicks(int ticks) } protected int SecondsToTicks(float seconds) - => (int) Math.Ceiling(seconds / TickPeriod); + { + return (int) Math.Ceiling(seconds / TickPeriod); + } protected async Task RunSeconds(float seconds) - => await RunTicks(SecondsToTicks(seconds)); + { + await RunTicks(SecondsToTicks(seconds)); + } #endregion @@ -710,7 +717,7 @@ protected async Task RunSeconds(float seconds) /// /// Sends a bui message using the given bui key. /// - protected async Task SendBui(Enum key, BoundUserInterfaceMessage msg, EntityUid? target = null) + protected async Task SendBui(Enum key, BoundUserInterfaceMessage msg, EntityUid? _ = null) { if (!TryGetBui(key, out var bui)) return; @@ -724,7 +731,7 @@ protected async Task SendBui(Enum key, BoundUserInterfaceMessage msg, EntityUid? /// /// Sends a bui message using the given bui key. /// - protected async Task CloseBui(Enum key, EntityUid? target = null) + protected async Task CloseBui(Enum key, EntityUid? _ = null) { if (!TryGetBui(key, out var bui)) return; @@ -782,11 +789,11 @@ protected async Task ClickControl(string name) where TWindow : BaseWind protected async Task ClickControl(Control control) { var screenCoords = new ScreenCoordinates( - control.GlobalPixelPosition + control.PixelSize/2, + control.GlobalPixelPosition + control.PixelSize / 2, control.Window?.Id ?? default); var relativePos = screenCoords.Position / control.UIScale - control.GlobalPosition; - var relativePixelPos = screenCoords.Position - control.GlobalPixelPosition; + var relativePixelPos = screenCoords.Position - control.GlobalPixelPosition; var args = new GUIBoundKeyEventArgs( EngineKeyFunctions.UIClick, @@ -836,9 +843,9 @@ protected Control GetControl(string name) where TWindow : BaseWindow } var window = GetWindow(); - var control = (field?.GetValue(window) ?? prop?.GetValue(window)) as Control; + var fieldOrProp = field?.GetValue(window) ?? prop?.GetValue(window); - if (control == null) + if (fieldOrProp is not Control control) { Assert.Fail($"{name} was null or was not a control."); return default!; diff --git a/Content.IntegrationTests/Tests/Interaction/InteractionTest.cs b/Content.IntegrationTests/Tests/Interaction/InteractionTest.cs index 597c063dc7e..d18fa415ef9 100644 --- a/Content.IntegrationTests/Tests/Interaction/InteractionTest.cs +++ b/Content.IntegrationTests/Tests/Interaction/InteractionTest.cs @@ -1,11 +1,9 @@ #nullable enable using System.Linq; -using System.Threading.Tasks; using Content.Client.Construction; using Content.Client.Examine; using Content.Server.Body.Systems; using Content.Server.Mind; -using Content.Server.Mind.Components; using Content.Server.Players; using Content.Server.Stack; using Content.Server.Tools; @@ -14,12 +12,12 @@ using Content.Shared.Hands.Components; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction; -using NUnit.Framework; -using Robust.Client.GameObjects; using Robust.Client.Input; using Robust.Client.UserInterface; +using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Players; using Robust.Shared.Prototypes; @@ -99,22 +97,25 @@ public abstract partial class InteractionTest protected ToolSystem ToolSys = default!; protected InteractionTestSystem STestSystem = default!; protected SharedTransformSystem Transform = default!; + protected ActorSystem Actor = default!; + protected ISawmill SLogger = default!; // CLIENT dependencies protected IEntityManager CEntMan = default!; protected IGameTiming CTiming = default!; protected IUserInterfaceManager UiMan = default!; protected IInputManager InputManager = default!; - protected InputSystem InputSystem = default!; + protected Robust.Client.GameObjects.InputSystem InputSystem = default!; protected ConstructionSystem CConSys = default!; protected ExamineSystem ExamineSys = default!; protected InteractionTestSystem CTestSystem = default!; + protected ISawmill CLogger = default!; // player components protected HandsComponent Hands = default!; protected DoAfterComponent DoAfters = default!; - public float TickPeriod => (float)STiming.TickPeriod.TotalSeconds; + public float TickPeriod => (float) STiming.TickPeriod.TotalSeconds; // Simple mob that has one hand and can perform misc interactions. @@ -137,7 +138,7 @@ public abstract partial class InteractionTest [SetUp] public virtual async Task Setup() { - PairTracker = await PoolManager.GetServerClient(new PoolSettings{ExtraPrototypes = TestPrototypes}); + PairTracker = await PoolManager.GetServerClient(new PoolSettings { ExtraPrototypes = TestPrototypes }); // server dependencies SEntMan = Server.ResolveDependency(); @@ -151,19 +152,22 @@ public virtual async Task Setup() ToolSys = SEntMan.System(); DoAfterSys = SEntMan.System(); Transform = SEntMan.System(); - SConstruction = SEntMan.System(); + SConstruction = SEntMan.System(); STestSystem = SEntMan.System(); Stack = SEntMan.System(); + Actor = SEntMan.System(); + SLogger = Server.ResolveDependency().RootSawmill; // client dependencies CEntMan = Client.ResolveDependency(); UiMan = Client.ResolveDependency(); CTiming = Client.ResolveDependency(); InputManager = Client.ResolveDependency(); - InputSystem = CEntMan.System(); + InputSystem = CEntMan.System(); CTestSystem = CEntMan.System(); CConSys = CEntMan.System(); ExamineSys = CEntMan.System(); + CLogger = Client.ResolveDependency().RootSawmill; // Setup map. MapData = await PoolManager.CreateTestMap(PairTracker); @@ -189,7 +193,7 @@ await Server.WaitPost(() => old = cPlayerMan.LocalPlayer.ControlledEntity; Player = SEntMan.SpawnEntity(PlayerPrototype, PlayerCoords); - ServerSession.AttachToEntity(Player); + Actor.Attach(Player, ServerSession); Hands = SEntMan.GetComponent(Player); DoAfters = SEntMan.GetComponent(Player); }); @@ -220,8 +224,11 @@ await Server.WaitPost(() => // Final player asserts/checks. await PoolManager.ReallyBeIdle(PairTracker.Pair, 5); - Assert.That(cPlayerMan.LocalPlayer.ControlledEntity, Is.EqualTo(Player)); - Assert.That(sPlayerMan.GetSessionByUserId(ClientSession.UserId).AttachedEntity, Is.EqualTo(Player)); + Assert.Multiple(() => + { + Assert.That(cPlayerMan.LocalPlayer.ControlledEntity, Is.EqualTo(Player)); + Assert.That(sPlayerMan.GetSessionByUserId(ClientSession.UserId).AttachedEntity, Is.EqualTo(Player)); + }); } [TearDown] @@ -231,4 +238,3 @@ public virtual async Task Cleanup() await PairTracker.CleanReturnAsync(); } } - diff --git a/Content.IntegrationTests/Tests/Interaction/MovementTest.cs b/Content.IntegrationTests/Tests/Interaction/MovementTest.cs index 6ecd1aec2ee..3fb37b0081c 100644 --- a/Content.IntegrationTests/Tests/Interaction/MovementTest.cs +++ b/Content.IntegrationTests/Tests/Interaction/MovementTest.cs @@ -1,9 +1,5 @@ #nullable enable -using System; -using System.Threading.Tasks; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.Maths; namespace Content.IntegrationTests.Tests.Interaction; @@ -32,14 +28,14 @@ public override async Task Setup() await base.Setup(); for (var i = -Tiles; i <= Tiles; i++) { - await SetTile(Plating, PlayerCoords.Offset((i,0)), MapData.MapGrid); + await SetTile(Plating, PlayerCoords.Offset((i, 0)), MapData.MapGrid); } AssertGridCount(1); if (AddWalls) { - await SpawnEntity("WallSolid", PlayerCoords.Offset((-Tiles,0))); - await SpawnEntity("WallSolid", PlayerCoords.Offset((Tiles,0))); + await SpawnEntity("WallSolid", PlayerCoords.Offset((-Tiles, 0))); + await SpawnEntity("WallSolid", PlayerCoords.Offset((Tiles, 0))); } await AddGravity(); @@ -58,7 +54,7 @@ protected float Delta(EntityUid? target = null, EntityUid? other = null) return 0; } - var delta = Transform.GetWorldPosition(target.Value) - Transform.GetWorldPosition(other ?? Player); + var delta = Transform.GetWorldPosition(target.Value) - Transform.GetWorldPosition(other ?? Player); return delta.X; } } diff --git a/Content.IntegrationTests/Tests/InventoryHelpersTest.cs b/Content.IntegrationTests/Tests/InventoryHelpersTest.cs index 71670ffe78c..7dff61355d4 100644 --- a/Content.IntegrationTests/Tests/InventoryHelpersTest.cs +++ b/Content.IntegrationTests/Tests/InventoryHelpersTest.cs @@ -1,8 +1,5 @@ -using System; -using System.Threading.Tasks; -using Content.Server.Stunnable; +using Content.Server.Stunnable; using Content.Shared.Inventory; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -43,7 +40,7 @@ public sealed class InventoryHelpersTest [Test] public async Task SpawnItemInSlotTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; var sEntities = server.ResolveDependency(); @@ -54,21 +51,27 @@ await server.WaitAssertion(() => var human = sEntities.SpawnEntity("InventoryStunnableDummy", MapCoordinates.Nullspace); var invSystem = systemMan.GetEntitySystem(); - // Can't do the test if this human doesn't have the slots for it. - Assert.That(invSystem.HasSlot(human, "jumpsuit")); - Assert.That(invSystem.HasSlot(human, "id")); + Assert.Multiple(() => + { + // Can't do the test if this human doesn't have the slots for it. + Assert.That(invSystem.HasSlot(human, "jumpsuit")); + Assert.That(invSystem.HasSlot(human, "id")); + }); Assert.That(invSystem.SpawnItemInSlot(human, "jumpsuit", "InventoryJumpsuitJanitorDummy", true)); +#pragma warning disable NUnit2045 // Do we actually have the uniform equipped? Assert.That(invSystem.TryGetSlotEntity(human, "jumpsuit", out var uniform)); Assert.That(sEntities.GetComponent(uniform.Value).EntityPrototype is { ID: "InventoryJumpsuitJanitorDummy" }); +#pragma warning restore NUnit2045 systemMan.GetEntitySystem().TryStun(human, TimeSpan.FromSeconds(1f), true); +#pragma warning disable NUnit2045 // Since the mob is stunned, they can't equip this. Assert.That(invSystem.SpawnItemInSlot(human, "id", "InventoryIDCardDummy", true), Is.False); @@ -82,6 +85,7 @@ await server.WaitAssertion(() => { ID: "InventoryIDCardDummy" }); +#pragma warning restore NUnit2045 }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Lobby/CharacterCreationTest.cs b/Content.IntegrationTests/Tests/Lobby/CharacterCreationTest.cs index fc236c18966..50e340c1558 100644 --- a/Content.IntegrationTests/Tests/Lobby/CharacterCreationTest.cs +++ b/Content.IntegrationTests/Tests/Lobby/CharacterCreationTest.cs @@ -1,10 +1,7 @@ -using System; -using System.Threading.Tasks; using Content.Client.Lobby; using Content.Client.Preferences; using Content.Server.Preferences.Managers; using Content.Shared.Preferences; -using NUnit.Framework; using Robust.Client.State; using Robust.Shared.Network; @@ -18,7 +15,7 @@ public sealed class CharacterCreationTest [Test] public async Task CreateDeleteCreateTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{InLobby = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { InLobby = true }); var server = pairTracker.Pair.Server; var client = pairTracker.Pair.Client; @@ -34,7 +31,7 @@ public async Task CreateDeleteCreateTest() await PoolManager.WaitUntil(client, () => clientStateManager.CurrentState is LobbyState, 600); - Assert.NotNull(clientNetManager.ServerChannel); + Assert.That(clientNetManager.ServerChannel, Is.Not.Null); var clientNetId = clientNetManager.ServerChannel.UserId; HumanoidCharacterProfile profile = null; @@ -45,9 +42,12 @@ await client.WaitAssertion(() => var clientCharacters = clientPrefManager.Preferences?.Characters; Assert.That(clientCharacters, Is.Not.Null); - Assert.That(clientCharacters.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(clientCharacters, Has.Count.EqualTo(1)); - Assert.That(clientStateManager.CurrentState, Is.TypeOf()); + Assert.That(clientStateManager.CurrentState, Is.TypeOf()); + }); profile = HumanoidCharacterProfile.Random(); clientPrefManager.CreateCharacter(profile); @@ -55,7 +55,7 @@ await client.WaitAssertion(() => clientCharacters = clientPrefManager.Preferences?.Characters; Assert.That(clientCharacters, Is.Not.Null); - Assert.That(clientCharacters.Count, Is.EqualTo(2)); + Assert.That(clientCharacters, Has.Count.EqualTo(2)); Assert.That(clientCharacters[1].MemberwiseEquals(profile)); }); @@ -65,7 +65,7 @@ await server.WaitAssertion(() => { var serverCharacters = serverPrefManager.GetPreferences(clientNetId).Characters; - Assert.That(serverCharacters.Count, Is.EqualTo(2)); + Assert.That(serverCharacters, Has.Count.EqualTo(2)); Assert.That(serverCharacters[1].MemberwiseEquals(profile)); }); @@ -96,7 +96,7 @@ await client.WaitAssertion(() => var clientCharacters = clientPrefManager.Preferences?.Characters; Assert.That(clientCharacters, Is.Not.Null); - Assert.That(clientCharacters.Count, Is.EqualTo(2)); + Assert.That(clientCharacters, Has.Count.EqualTo(2)); Assert.That(clientCharacters[1].MemberwiseEquals(profile)); }); @@ -106,7 +106,7 @@ await server.WaitAssertion(() => { var serverCharacters = serverPrefManager.GetPreferences(clientNetId).Characters; - Assert.That(serverCharacters.Count, Is.EqualTo(2)); + Assert.That(serverCharacters, Has.Count.EqualTo(2)); Assert.That(serverCharacters[1].MemberwiseEquals(profile)); }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/Lobby/ServerReloginTest.cs b/Content.IntegrationTests/Tests/Lobby/ServerReloginTest.cs index 2e2cfa4f58d..98a7cbb5840 100644 --- a/Content.IntegrationTests/Tests/Lobby/ServerReloginTest.cs +++ b/Content.IntegrationTests/Tests/Lobby/ServerReloginTest.cs @@ -1,10 +1,7 @@ using System.Linq; -using System.Threading.Tasks; using Content.Shared.CCVar; -using NUnit.Framework; using Robust.Server.Player; using Robust.Shared.Configuration; -using Robust.Shared.IoC; using Robust.Shared.Network; namespace Content.IntegrationTests.Tests.Lobby; @@ -16,7 +13,7 @@ public async Task Relogin() await using var pairTracker = await PoolManager.GetServerClient(); var server = pairTracker.Pair.Server; var client = pairTracker.Pair.Client; - int originalMaxPlayers = 0; + var originalMaxPlayers = 0; string username = null; var serverConfig = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/LogErrorTest.cs b/Content.IntegrationTests/Tests/LogErrorTest.cs index 17ae6e5f973..733d6d3b821 100644 --- a/Content.IntegrationTests/Tests/LogErrorTest.cs +++ b/Content.IntegrationTests/Tests/LogErrorTest.cs @@ -1,5 +1,3 @@ -using System.Threading.Tasks; -using NUnit.Framework; using Robust.Shared.Configuration; using Robust.Shared.Log; using Robust.UnitTesting; @@ -19,15 +17,16 @@ public async Task TestLogErrorCausesTestFailure() var client = pairTracker.Pair.Client; var cfg = server.ResolveDependency(); + var logmill = server.ResolveDependency().RootSawmill; // Default cvar is properly configured Assert.That(cfg.GetCVar(RTCVars.FailureLogLevel), Is.EqualTo(LogLevel.Error)); // Warnings don't cause tests to fail. - await server.WaitPost(() => Logger.Warning("test")); + await server.WaitPost(() => logmill.Warning("test")); // But errors do - await server.WaitPost(() => Assert.Throws(() => Logger.Error("test"))); - await client.WaitPost(() => Assert.Throws(() => Logger.Error("test"))); + await server.WaitPost(() => Assert.Throws(() => logmill.Error("test"))); + await client.WaitPost(() => Assert.Throws(() => logmill.Error("test"))); } } diff --git a/Content.IntegrationTests/Tests/MachineBoardTest.cs b/Content.IntegrationTests/Tests/MachineBoardTest.cs index 5ffe0cf91c1..a2c3d7b1515 100644 --- a/Content.IntegrationTests/Tests/MachineBoardTest.cs +++ b/Content.IntegrationTests/Tests/MachineBoardTest.cs @@ -1,9 +1,7 @@ using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Content.Server.Construction.Components; using Content.Shared.Construction.Components; -using NUnit.Framework; using Robust.Shared.Prototypes; namespace Content.IntegrationTests.Tests; diff --git a/Content.IntegrationTests/Tests/MaterialArbitrageTest.cs b/Content.IntegrationTests/Tests/MaterialArbitrageTest.cs index e0894debd6d..e37f486ea0d 100644 --- a/Content.IntegrationTests/Tests/MaterialArbitrageTest.cs +++ b/Content.IntegrationTests/Tests/MaterialArbitrageTest.cs @@ -9,13 +9,10 @@ using Content.Shared.Lathe; using Content.Shared.Research.Prototypes; using Content.Shared.Stacks; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Prototypes; -using System; using System.Collections.Generic; -using System.Threading.Tasks; using Content.Shared.Chemistry.Reagent; using Content.Shared.Construction.Components; using Content.Shared.FixedPoint; @@ -33,7 +30,7 @@ public sealed class MaterialArbitrageTest [Test] public async Task NoMaterialArbitrage() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings {NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -186,7 +183,7 @@ public async Task NoMaterialArbitrage() var spawnedPrice = await GetSpawnedPrice(spawnedEnts); var price = await GetPrice(id); if (spawnedPrice > 0 && price > 0) - Assert.LessOrEqual(spawnedPrice, price, $"{id} increases in price after being destroyed"); + Assert.That(spawnedPrice, Is.LessThanOrEqualTo(price), $"{id} increases in price after being destroyed"); // Check lathe production if (latheRecipes.TryGetValue(id, out var recipe)) @@ -195,7 +192,7 @@ public async Task NoMaterialArbitrage() { var actualAmount = SharedLatheSystem.AdjustMaterial(amount, recipe.ApplyMaterialDiscount, multiplier); if (spawnedMats.TryGetValue(matId, out var numSpawned)) - Assert.LessOrEqual(numSpawned, actualAmount, $"destroying a {id} spawns more {matId} than required to produce via an (upgraded) lathe."); + Assert.That(numSpawned, Is.LessThanOrEqualTo(actualAmount), $"destroying a {id} spawns more {matId} than required to produce via an (upgraded) lathe."); } } @@ -205,7 +202,7 @@ public async Task NoMaterialArbitrage() foreach (var (matId, amount) in constructionMats) { if (spawnedMats.TryGetValue(matId, out var numSpawned)) - Assert.LessOrEqual(numSpawned, amount, $"destroying a {id} spawns more {matId} than required to construct it."); + Assert.That(numSpawned, Is.LessThanOrEqualTo(amount), $"destroying a {id} spawns more {matId} than required to construct it."); } } } @@ -263,7 +260,7 @@ public async Task NoMaterialArbitrage() var deconstructedPrice = await GetDeconstructedPrice(deconstructedMats); var price = await GetPrice(id); if (deconstructedPrice > 0 && price > 0) - Assert.LessOrEqual(deconstructedPrice, price, $"{id} increases in price after being deconstructed"); + Assert.That(deconstructedPrice, Is.LessThanOrEqualTo(price), $"{id} increases in price after being deconstructed"); // Check lathe production if (latheRecipes.TryGetValue(id, out var recipe)) @@ -272,7 +269,7 @@ public async Task NoMaterialArbitrage() { var actualAmount = SharedLatheSystem.AdjustMaterial(amount, recipe.ApplyMaterialDiscount, multiplier); if (deconstructedMats.TryGetValue(matId, out var numSpawned)) - Assert.LessOrEqual(numSpawned, actualAmount, $"deconstructing {id} spawns more {matId} than required to produce via an (upgraded) lathe."); + Assert.That(numSpawned, Is.LessThanOrEqualTo(actualAmount), $"deconstructing {id} spawns more {matId} than required to produce via an (upgraded) lathe."); } } @@ -282,7 +279,7 @@ public async Task NoMaterialArbitrage() foreach (var (matId, amount) in constructionMats) { if (deconstructedMats.TryGetValue(matId, out var numSpawned)) - Assert.LessOrEqual(numSpawned, amount, $"deconstructing a {id} spawns more {matId} than required to construct it."); + Assert.That(numSpawned, Is.LessThanOrEqualTo(amount), $"deconstructing a {id} spawns more {matId} than required to construct it."); } } } @@ -315,7 +312,7 @@ public async Task NoMaterialArbitrage() var sumPrice = materialPrice + chemicalPrice; var price = await GetPrice(id); if (sumPrice > 0 && price > 0) - Assert.LessOrEqual(sumPrice, price, $"{id} increases in price after decomposed into raw materials"); + Assert.That(sumPrice, Is.LessThanOrEqualTo(price), $"{id} increases in price after decomposed into raw materials"); // Check lathe production if (latheRecipes.TryGetValue(id, out var recipe)) @@ -324,7 +321,7 @@ public async Task NoMaterialArbitrage() { var actualAmount = SharedLatheSystem.AdjustMaterial(amount, recipe.ApplyMaterialDiscount, multiplier); if (compositionComponent.MaterialComposition.TryGetValue(matId, out var numSpawned)) - Assert.LessOrEqual(numSpawned, actualAmount, $"The physical composition of {id} has more {matId} than required to produce via an (upgraded) lathe."); + Assert.That(numSpawned, Is.LessThanOrEqualTo(actualAmount), $"The physical composition of {id} has more {matId} than required to produce via an (upgraded) lathe."); } } @@ -334,7 +331,7 @@ public async Task NoMaterialArbitrage() foreach (var (matId, amount) in constructionMats) { if (compositionComponent.MaterialComposition.TryGetValue(matId, out var numSpawned)) - Assert.LessOrEqual(numSpawned, amount, $"The physical composition of {id} has more {matId} than required to construct it."); + Assert.That(numSpawned, Is.LessThanOrEqualTo(amount), $"The physical composition of {id} has more {matId} than required to construct it."); } } } @@ -369,7 +366,7 @@ await server.WaitPost(() => return price; } - +#pragma warning disable CS1998 async Task GetDeconstructedPrice(Dictionary mats) { double price = 0; @@ -380,8 +377,9 @@ async Task GetDeconstructedPrice(Dictionary mats) } return price; } +#pragma warning restore CS1998 - +#pragma warning disable CS1998 async Task GetChemicalCompositionPrice(Dictionary mats) { double price = 0; @@ -392,5 +390,6 @@ async Task GetChemicalCompositionPrice(Dictionary m } return price; } +#pragma warning restore CS1998 } } diff --git a/Content.IntegrationTests/Tests/Materials/MaterialTests.cs b/Content.IntegrationTests/Tests/Materials/MaterialTests.cs index b144d382cad..1bf679704f3 100644 --- a/Content.IntegrationTests/Tests/Materials/MaterialTests.cs +++ b/Content.IntegrationTests/Tests/Materials/MaterialTests.cs @@ -1,6 +1,4 @@ #nullable enable -using NUnit.Framework; -using System.Threading.Tasks; using Content.Server.Stack; using Content.Shared.Stacks; using Content.Shared.Materials; @@ -22,7 +20,7 @@ public sealed class MaterialPrototypeSpawnsStackMaterialTest [Test] public async Task MaterialPrototypeSpawnsStackMaterial() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); diff --git a/Content.IntegrationTests/Tests/Minds/GhostRoleTests.cs b/Content.IntegrationTests/Tests/Minds/GhostRoleTests.cs index cb6f2246281..e58d3a4ec4e 100644 --- a/Content.IntegrationTests/Tests/Minds/GhostRoleTests.cs +++ b/Content.IntegrationTests/Tests/Minds/GhostRoleTests.cs @@ -1,11 +1,9 @@ #nullable enable using System.Linq; -using System.Threading.Tasks; using Content.Server.Ghost.Roles; using Content.Server.Ghost.Roles.Components; using Content.Server.Mind; using Content.Server.Players; -using NUnit.Framework; using Robust.Shared.Console; using Robust.Shared.GameObjects; using Robust.Shared.Map; @@ -31,7 +29,7 @@ public sealed class GhostRoleTests [Test] public async Task TakeRoleAndReturn() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings {ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; var client = pairTracker.Pair.Client; diff --git a/Content.IntegrationTests/Tests/Minds/MindTests.EntityDeletion.cs b/Content.IntegrationTests/Tests/Minds/MindTests.EntityDeletion.cs index f2922412321..c0ff4f197a7 100644 --- a/Content.IntegrationTests/Tests/Minds/MindTests.EntityDeletion.cs +++ b/Content.IntegrationTests/Tests/Minds/MindTests.EntityDeletion.cs @@ -1,9 +1,7 @@ using System.Linq; -using System.Threading.Tasks; using Content.Server.Ghost.Components; using Content.Server.Mind; using Content.Server.Players; -using NUnit.Framework; using Robust.Server.Console; using Robust.Server.GameObjects; using Robust.Server.Player; @@ -45,17 +43,22 @@ await server.WaitAssertion(() => mindSystem.TransferTo(mind, playerEnt); mindSystem.Visit(mind, visitEnt); - Assert.That(player.AttachedEntity, Is.EqualTo(visitEnt)); - Assert.That(mind.VisitingEntity, Is.EqualTo(visitEnt)); + Assert.Multiple(() => + { + Assert.That(player.AttachedEntity, Is.EqualTo(visitEnt)); + Assert.That(mind.VisitingEntity, Is.EqualTo(visitEnt)); + }); }); await PoolManager.RunTicksSync(pairTracker.Pair, 5); await server.WaitPost(() => entMan.DeleteEntity(visitEnt)); await PoolManager.RunTicksSync(pairTracker.Pair, 5); - Assert.IsNull(mind.VisitingEntity); +#pragma warning disable NUnit2045 // Interdependent assertions. + Assert.That(mind.VisitingEntity, Is.Null); Assert.That(entMan.EntityExists(mind.OwnedEntity)); Assert.That(mind.OwnedEntity, Is.EqualTo(playerEnt)); +#pragma warning restore NUnit2045 // This used to throw so make sure it doesn't. await server.WaitPost(() => entMan.DeleteEntity(mind.OwnedEntity!.Value)); @@ -97,8 +100,10 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(entMan.EntityExists(mind.CurrentEntity!.Value), Is.True); +#pragma warning disable NUnit2045 // Interdependent assertions. + Assert.That(entMan.EntityExists(mind.CurrentEntity), Is.True); Assert.That(mind.CurrentEntity, Is.Not.EqualTo(playerEnt)); +#pragma warning restore NUnit2045 }); await pairTracker.CleanReturnAsync(); @@ -119,7 +124,7 @@ public async Task TestGhostOnDelete() var entMan = server.ResolveDependency(); var playerMan = server.ResolveDependency(); - IPlayerSession player = playerMan.ServerSessions.Single(); + var player = playerMan.ServerSessions.Single(); Assert.That(!entMan.HasComponent(player.AttachedEntity), "Player was initially a ghost?"); @@ -154,8 +159,10 @@ public async Task TestOriginalDeletedWhileGhostingKeepsGhost() var mind = GetMind(pairTracker.Pair); var player = playerMan.ServerSessions.Single(); - Assert.NotNull(player.AttachedEntity); +#pragma warning disable NUnit2045 // Interdependent assertions. + Assert.That(player.AttachedEntity, Is.Not.Null); Assert.That(entMan.EntityExists(player.AttachedEntity)); +#pragma warning restore NUnit2045 var originalEntity = player.AttachedEntity.Value; EntityUid ghost = default!; @@ -165,10 +172,13 @@ await server.WaitAssertion(() => mindSystem.Visit(mind, ghost); }); - Assert.That(player.AttachedEntity, Is.EqualTo(ghost)); - Assert.That(entMan.HasComponent(player.AttachedEntity), "player is not a ghost"); - Assert.That(mind.VisitingEntity, Is.EqualTo(player.AttachedEntity)); - Assert.That(mind.OwnedEntity, Is.EqualTo(originalEntity)); + Assert.Multiple(() => + { + Assert.That(player.AttachedEntity, Is.EqualTo(ghost)); + Assert.That(entMan.HasComponent(player.AttachedEntity), "player is not a ghost"); + Assert.That(mind.VisitingEntity, Is.EqualTo(player.AttachedEntity)); + Assert.That(mind.OwnedEntity, Is.EqualTo(originalEntity)); + }); await PoolManager.RunTicksSync(pairTracker.Pair, 5); await server.WaitAssertion(() => entMan.DeleteEntity(originalEntity)); @@ -178,10 +188,13 @@ await server.WaitAssertion(() => // Check that the player is still in control of the ghost mind = GetMind(pairTracker.Pair); Assert.That(!entMan.Deleted(ghost), "ghost has been deleted"); - Assert.That(player.AttachedEntity, Is.EqualTo(ghost)); - Assert.That(entMan.HasComponent(player.AttachedEntity)); - Assert.IsNull(mind.VisitingEntity); - Assert.That(mind.OwnedEntity, Is.EqualTo(ghost)); + Assert.Multiple(() => + { + Assert.That(player.AttachedEntity, Is.EqualTo(ghost)); + Assert.That(entMan.HasComponent(player.AttachedEntity)); + Assert.That(mind.VisitingEntity, Is.Null); + Assert.That(mind.OwnedEntity, Is.EqualTo(ghost)); + }); await pairTracker.CleanReturnAsync(); } @@ -213,13 +226,16 @@ public async Task TestGhostToAghost() await PoolManager.RunTicksSync(pairTracker.Pair, 5); Assert.That(entMan.Deleted(ghost), "old ghost was not deleted"); - Assert.That(player.AttachedEntity, Is.Not.EqualTo(ghost), "Player is still attached to the old ghost"); - Assert.That(entMan.HasComponent(player.AttachedEntity!.Value), "Player did not become a new ghost"); - Assert.That(entMan.GetComponent(player.AttachedEntity.Value).EntityPrototype?.ID, Is.EqualTo("AdminObserver")); + Assert.Multiple(() => + { + Assert.That(player.AttachedEntity, Is.Not.EqualTo(ghost), "Player is still attached to the old ghost"); + Assert.That(entMan.HasComponent(player.AttachedEntity), "Player did not become a new ghost"); + Assert.That(entMan.GetComponent(player.AttachedEntity!.Value).EntityPrototype?.ID, Is.EqualTo("AdminObserver")); + }); var mind = player.ContentData()?.Mind; - Assert.NotNull(mind); - Assert.Null(mind.VisitingEntity); + Assert.That(mind, Is.Not.Null); + Assert.That(mind.VisitingEntity, Is.Null); await pairTracker.CleanReturnAsync(); } @@ -241,7 +257,7 @@ public async Task TestGhostDeletedSpawnsNewGhost() var playerMan = server.ResolveDependency(); var serverConsole = server.ResolveDependency(); - IPlayerSession player = playerMan.ServerSessions.Single(); + var player = playerMan.ServerSessions.Single(); EntityUid ghost = default!; @@ -272,9 +288,11 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { +#pragma warning disable NUnit2045 // Interdependent assertions. Assert.That(entMan.Deleted(ghost)); Assert.That(player.AttachedEntity, Is.Not.EqualTo(ghost)); Assert.That(entMan.HasComponent(player.AttachedEntity!.Value)); +#pragma warning restore NUnit2045 }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/Minds/MindTests.Helpers.cs b/Content.IntegrationTests/Tests/Minds/MindTests.Helpers.cs index f3fed7ea7bb..21447bb7f70 100644 --- a/Content.IntegrationTests/Tests/Minds/MindTests.Helpers.cs +++ b/Content.IntegrationTests/Tests/Minds/MindTests.Helpers.cs @@ -1,9 +1,7 @@ using System.Linq; -using System.Threading.Tasks; using Content.Server.Ghost.Components; using Content.Server.Mind; using Content.Server.Players; -using NUnit.Framework; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Enums; @@ -25,7 +23,7 @@ public sealed partial class MindTests /// the player's mind's current entity, likely because some previous test directly changed the players attached /// entity. /// - public async Task SetupPair() + private static async Task SetupPair() { var pairTracker = await PoolManager.GetServerClient(); var pair = pairTracker.Pair; @@ -47,15 +45,18 @@ await pair.Server.WaitPost(() => await PoolManager.RunTicksSync(pair, 5); - Assert.That(player.ContentData()?.Mind, Is.EqualTo(mind)); - Assert.That(player.AttachedEntity, Is.EqualTo(entity)); - Assert.That(player.AttachedEntity, Is.EqualTo(mind.CurrentEntity), "Player is not attached to the mind's current entity."); - Assert.That(entMan.EntityExists(mind.OwnedEntity), "The mind's current entity does not exist"); - Assert.That(mind.VisitingEntity == null || entMan.EntityExists(mind.VisitingEntity), "The minds visited entity does not exist."); + Assert.Multiple(() => + { + Assert.That(player.ContentData()?.Mind, Is.EqualTo(mind)); + Assert.That(player.AttachedEntity, Is.EqualTo(entity)); + Assert.That(player.AttachedEntity, Is.EqualTo(mind.CurrentEntity), "Player is not attached to the mind's current entity."); + Assert.That(entMan.EntityExists(mind.OwnedEntity), "The mind's current entity does not exist"); + Assert.That(mind.VisitingEntity == null || entMan.EntityExists(mind.VisitingEntity), "The minds visited entity does not exist."); + }); return pairTracker; } - public async Task BecomeGhost(Pair pair, bool visit = false) + private static async Task BecomeGhost(Pair pair, bool visit = false) { var entMan = pair.Server.ResolveDependency(); var playerMan = pair.Server.ResolveDependency(); @@ -69,7 +70,7 @@ await pair.Server.WaitAssertion(() => var oldUid = player.AttachedEntity; ghostUid = entMan.SpawnEntity("MobObserver", MapCoordinates.Nullspace); mind = mindSys.GetMind(player.UserId); - Assert.NotNull(mind); + Assert.That(mind, Is.Not.Null); if (visit) { @@ -84,17 +85,20 @@ await pair.Server.WaitAssertion(() => }); await PoolManager.RunTicksSync(pair, 5); - Assert.That(entMan.HasComponent(ghostUid)); - Assert.That(player.AttachedEntity == ghostUid); - Assert.That(mind.CurrentEntity == ghostUid); + Assert.Multiple(() => + { + Assert.That(entMan.HasComponent(ghostUid)); + Assert.That(player.AttachedEntity, Is.EqualTo(ghostUid)); + Assert.That(mind.CurrentEntity, Is.EqualTo(ghostUid)); + }); if (!visit) - Assert.Null(mind.VisitingEntity); + Assert.That(mind.VisitingEntity, Is.Null); return ghostUid; } - public async Task VisitGhost(Pair pair, bool visit = false) + private static async Task VisitGhost(Pair pair, bool _ = false) { return await BecomeGhost(pair, visit: true); } @@ -102,23 +106,26 @@ public async Task VisitGhost(Pair pair, bool visit = false) /// /// Get the player's current mind and check that the entities exists. /// - public Mind GetMind(Pair pair) + private static Mind GetMind(Pair pair) { var playerMan = pair.Server.ResolveDependency(); var entMan = pair.Server.ResolveDependency(); var player = playerMan.ServerSessions.SingleOrDefault(); - Assert.NotNull(player); + Assert.That(player, Is.Not.Null); var mind = player.ContentData()!.Mind; - Assert.NotNull(mind); - Assert.That(player.AttachedEntity, Is.EqualTo(mind.CurrentEntity), "Player is not attached to the mind's current entity."); - Assert.That(entMan.EntityExists(mind.OwnedEntity), "The mind's current entity does not exist"); - Assert.That(mind.VisitingEntity == null || entMan.EntityExists(mind.VisitingEntity), "The minds visited entity does not exist."); + Assert.That(mind, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(player.AttachedEntity, Is.EqualTo(mind.CurrentEntity), "Player is not attached to the mind's current entity."); + Assert.That(entMan.EntityExists(mind.OwnedEntity), "The mind's current entity does not exist"); + Assert.That(mind.VisitingEntity == null || entMan.EntityExists(mind.VisitingEntity), "The minds visited entity does not exist."); + }); return mind; } - public async Task Disconnect(Pair pair) + private static async Task Disconnect(Pair pair) { var netManager = pair.Client.ResolveDependency(); var playerMan = pair.Server.ResolveDependency(); @@ -131,12 +138,15 @@ await pair.Client.WaitAssertion(() => }); await PoolManager.RunTicksSync(pair, 5); - Assert.That(player.Status == SessionStatus.Disconnected); - Assert.NotNull(mind.UserId); - Assert.Null(mind.Session); + Assert.Multiple(() => + { + Assert.That(player.Status, Is.EqualTo(SessionStatus.Disconnected)); + Assert.That(mind.UserId, Is.Not.Null); + Assert.That(mind.Session, Is.Null); + }); } - public async Task Connect(Pair pair, string username) + private static async Task Connect(Pair pair, string username) { var netManager = pair.Client.ResolveDependency(); var playerMan = pair.Server.ResolveDependency(); @@ -148,10 +158,10 @@ public async Task Connect(Pair pair, string username) await PoolManager.RunTicksSync(pair, 5); var player = playerMan.ServerSessions.Single(); - Assert.That(player.Status == SessionStatus.InGame); + Assert.That(player.Status, Is.EqualTo(SessionStatus.InGame)); } - public async Task DisconnectReconnect(Pair pair) + private static async Task DisconnectReconnect(Pair pair) { var playerMan = pair.Server.ResolveDependency(); var player = playerMan.ServerSessions.Single(); @@ -163,8 +173,11 @@ public async Task DisconnectReconnect(Pair pair) // Session has changed var newSession = playerMan.ServerSessions.Single(); - Assert.That(newSession != player); - Assert.That(newSession.UserId == id); + Assert.Multiple(() => + { + Assert.That(newSession, Is.Not.EqualTo(player)); + Assert.That(newSession.UserId, Is.EqualTo(id)); + }); return newSession; } diff --git a/Content.IntegrationTests/Tests/Minds/MindTests.ReconnectTests.cs b/Content.IntegrationTests/Tests/Minds/MindTests.ReconnectTests.cs index b9727a7d233..49158e06e30 100644 --- a/Content.IntegrationTests/Tests/Minds/MindTests.ReconnectTests.cs +++ b/Content.IntegrationTests/Tests/Minds/MindTests.ReconnectTests.cs @@ -1,8 +1,6 @@ using System.Linq; -using System.Threading.Tasks; using Content.Server.Ghost.Components; using Content.Server.Mind; -using NUnit.Framework; using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.Map; @@ -28,10 +26,13 @@ public async Task TestGhostsCanReconnect() await DisconnectReconnect(pair); // Player in control of a new ghost, but with the same mind - Assert.That(GetMind(pair) == mind); - Assert.That(entMan.Deleted(ghost)); - Assert.That(entMan.HasComponent(mind.OwnedEntity)); - Assert.Null(mind.VisitingEntity); + Assert.Multiple(() => + { + Assert.That(GetMind(pair), Is.EqualTo(mind)); + Assert.That(entMan.Deleted(ghost)); + Assert.That(entMan.HasComponent(mind.OwnedEntity)); + Assert.That(mind.VisitingEntity, Is.Null); + }); await pairTracker.CleanReturnAsync(); } @@ -53,7 +54,7 @@ public async Task TestDeletedCanReconnect() var player = playerMan.ServerSessions.Single(); var name = player.Name; var user = player.UserId; - Assert.NotNull(mind.OwnedEntity); + Assert.That(mind.OwnedEntity, Is.Not.Null); var entity = mind.OwnedEntity.Value; // Player is not a ghost @@ -65,18 +66,24 @@ public async Task TestDeletedCanReconnect() // Delete entity Assert.That(entMan.EntityExists(entity)); await pair.Server.WaitPost(() => entMan.DeleteEntity(entity)); - Assert.That(entMan.Deleted(entity)); - Assert.IsNull(mind.OwnedEntity); + Assert.Multiple(() => + { + Assert.That(entMan.Deleted(entity)); + Assert.That(mind.OwnedEntity, Is.Null); + }); // Reconnect await Connect(pair, name); player = playerMan.ServerSessions.Single(); - Assert.That(user, Is.EqualTo(player.UserId)); + Assert.Multiple(() => + { + Assert.That(user, Is.EqualTo(player.UserId)); - // Player is now a new ghost entity - Assert.That(GetMind(pair), Is.EqualTo(mind)); - Assert.That(mind.OwnedEntity, Is.Not.EqualTo(entity)); - Assert.That(entMan.HasComponent(mind.OwnedEntity)); + // Player is now a new ghost entity + Assert.That(GetMind(pair), Is.EqualTo(mind)); + Assert.That(mind.OwnedEntity, Is.Not.EqualTo(entity)); + Assert.That(entMan.HasComponent(mind.OwnedEntity)); + }); await pairTracker.CleanReturnAsync(); } @@ -99,10 +106,13 @@ public async Task TestVisitingGhostReconnect() await DisconnectReconnect(pair); // Player now controls their original mob, mind was preserved - Assert.That(mind, Is.EqualTo(GetMind(pair))); - Assert.That(mind.CurrentEntity, Is.EqualTo(original)); - Assert.That(!entMan.Deleted(original)); - Assert.That(entMan.Deleted(ghost)); + Assert.Multiple(() => + { + Assert.That(mind, Is.EqualTo(GetMind(pair))); + Assert.That(mind.CurrentEntity, Is.EqualTo(original)); + Assert.That(entMan.Deleted(original), Is.False); + Assert.That(entMan.Deleted(ghost)); + }); await pairTracker.CleanReturnAsync(); } @@ -134,11 +144,13 @@ await pair.Server.WaitAssertion(() => await DisconnectReconnect(pair); // Player is back in control of the visited mob, mind was preserved - Assert.That(mind == GetMind(pair)); - Assert.That(!entMan.Deleted(original)); - Assert.That(!entMan.Deleted(visiting)); - Assert.That(mind.CurrentEntity == visiting); - Assert.That(mind.CurrentEntity == visiting); + Assert.Multiple(() => + { + Assert.That(GetMind(pair), Is.EqualTo(mind)); + Assert.That(entMan.Deleted(original), Is.False); + Assert.That(entMan.Deleted(visiting), Is.False); + Assert.That(mind.CurrentEntity, Is.EqualTo(visiting)); + }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Minds/MindTests.cs b/Content.IntegrationTests/Tests/Minds/MindTests.cs index e1c07850efe..446c9be017c 100644 --- a/Content.IntegrationTests/Tests/Minds/MindTests.cs +++ b/Content.IntegrationTests/Tests/Minds/MindTests.cs @@ -1,7 +1,5 @@ #nullable enable -using System; using System.Linq; -using System.Threading.Tasks; using Content.Server.Ghost; using Content.Server.Ghost.Roles; using Content.Server.Mind; @@ -9,19 +7,15 @@ using Content.Server.Mind.Components; using Content.Server.Players; using Content.Server.Roles; -using Content.Server.Traitor; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; using Content.Shared.Roles; -using NUnit.Framework; using Robust.Server.Console; using Robust.Server.GameObjects; -using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; -using Robust.Shared.Network; using Robust.Shared.Prototypes; using IPlayerManager = Robust.Server.Player.IPlayerManager; @@ -59,7 +53,7 @@ public sealed partial class MindTests [Test] public async Task TestCreateAndTransferMindToNewEntity() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{ NoClient = true }); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var entMan = server.ResolveDependency(); @@ -85,7 +79,7 @@ await server.WaitAssertion(() => [Test] public async Task TestReplaceMind() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{ NoClient = true }); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var entMan = server.ResolveDependency(); @@ -103,8 +97,11 @@ await server.WaitAssertion(() => var mind2 = mindSystem.CreateMind(null); mindSystem.TransferTo(mind2, entity); - Assert.That(mindSystem.GetMind(entity, mindComp), Is.EqualTo(mind2)); - Assert.That(mind.OwnedEntity != entity); + Assert.Multiple(() => + { + Assert.That(mindSystem.GetMind(entity, mindComp), Is.EqualTo(mind2)); + Assert.That(mind.OwnedEntity, Is.Not.EqualTo(entity)); + }); }); await pairTracker.CleanReturnAsync(); @@ -113,7 +110,7 @@ await server.WaitAssertion(() => [Test] public async Task TestEntityDeadWhenGibbed() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{ NoClient = true, ExtraPrototypes = Prototypes }); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; var entMan = server.ResolveDependency(); @@ -133,8 +130,11 @@ await server.WaitAssertion(() => mind = mindSystem.CreateMind(null); mindSystem.TransferTo(mind, entity); - Assert.That(mindSystem.GetMind(entity, mindContainerComp), Is.EqualTo(mind)); - Assert.That(!mindSystem.IsCharacterDeadPhysically(mind)); + Assert.Multiple(() => + { + Assert.That(mindSystem.GetMind(entity, mindContainerComp), Is.EqualTo(mind)); + Assert.That(!mindSystem.IsCharacterDeadPhysically(mind)); + }); }); await PoolManager.RunTicksSync(pairTracker.Pair, 5); @@ -164,7 +164,7 @@ await server.WaitAssertion(() => [Test] public async Task TestMindTransfersToOtherEntity() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{ NoClient = true }); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var entMan = server.ResolveDependency(); @@ -185,8 +185,11 @@ await server.WaitAssertion(() => Assert.That(mindSystem.GetMind(entity, mindComp), Is.EqualTo(mind)); mindSystem.TransferTo(mind, targetEntity); - Assert.That(mindSystem.GetMind(entity, mindComp), Is.EqualTo(null)); - Assert.That(mindSystem.GetMind(targetEntity), Is.EqualTo(mind)); + Assert.Multiple(() => + { + Assert.That(mindSystem.GetMind(entity, mindComp), Is.EqualTo(null)); + Assert.That(mindSystem.GetMind(targetEntity), Is.EqualTo(mind)); + }); }); await pairTracker.CleanReturnAsync(); @@ -214,8 +217,11 @@ await server.WaitAssertion(() => mind = mindSystem.CreateMind(null); mindSystem.TransferTo(mind, entity); - Assert.That(mindSystem.GetMind(entity, mindComp), Is.EqualTo(mind)); - Assert.That(mindComp.HasMind); + Assert.Multiple(() => + { + Assert.That(mindSystem.GetMind(entity, mindComp), Is.EqualTo(mind)); + Assert.That(mindComp.HasMind); + }); }); await PoolManager.RunTicksSync(pairTracker.Pair, 5); @@ -223,12 +229,18 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { mindSystem.SetUserId(mind, userId); - Assert.That(mind.UserId, Is.EqualTo(userId)); - Assert.That(originalMind.UserId, Is.EqualTo(null)); + Assert.Multiple(() => + { + Assert.That(mind.UserId, Is.EqualTo(userId)); + Assert.That(originalMind.UserId, Is.EqualTo(null)); + }); mindSystem.SetUserId(originalMind, userId); - Assert.That(mind.UserId, Is.EqualTo(null)); - Assert.That(originalMind.UserId, Is.EqualTo(userId)); + Assert.Multiple(() => + { + Assert.That(mind.UserId, Is.EqualTo(null)); + Assert.That(originalMind.UserId, Is.EqualTo(userId)); + }); }); await PoolManager.RunTicksSync(pairTracker.Pair, 5); @@ -239,7 +251,7 @@ await server.WaitAssertion(() => [Test] public async Task TestAddRemoveHasRoles() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{ NoClient = true }); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var entMan = server.ResolveDependency(); @@ -258,32 +270,47 @@ await server.WaitAssertion(() => mindSystem.TransferTo(mind, entity); Assert.That(mindSystem.GetMind(entity, mindComp), Is.EqualTo(mind)); - Assert.That(!mindSystem.HasRole(mind)); - Assert.That(!mindSystem.HasRole(mind)); + Assert.Multiple(() => + { + Assert.That(mindSystem.HasRole(mind), Is.False); + Assert.That(mindSystem.HasRole(mind), Is.False); + }); var traitorRole = new TraitorRole(mind, new AntagPrototype()); mindSystem.AddRole(mind, traitorRole); - Assert.That(mindSystem.HasRole(mind)); - Assert.That(!mindSystem.HasRole(mind)); + Assert.Multiple(() => + { + Assert.That(mindSystem.HasRole(mind)); + Assert.That(mindSystem.HasRole(mind), Is.False); + }); var jobRole = new Job(mind, new JobPrototype()); mindSystem.AddRole(mind, jobRole); - Assert.That(mindSystem.HasRole(mind)); - Assert.That(mindSystem.HasRole(mind)); + Assert.Multiple(() => + { + Assert.That(mindSystem.HasRole(mind)); + Assert.That(mindSystem.HasRole(mind)); + }); mindSystem.RemoveRole(mind, traitorRole); - Assert.That(!mindSystem.HasRole(mind)); - Assert.That(mindSystem.HasRole(mind)); + Assert.Multiple(() => + { + Assert.That(mindSystem.HasRole(mind), Is.False); + Assert.That(mindSystem.HasRole(mind)); + }); mindSystem.RemoveRole(mind, jobRole); - Assert.That(!mindSystem.HasRole(mind)); - Assert.That(!mindSystem.HasRole(mind)); + Assert.Multiple(() => + { + Assert.That(mindSystem.HasRole(mind), Is.False); + Assert.That(mindSystem.HasRole(mind), Is.False); + }); }); await pairTracker.CleanReturnAsync(); @@ -304,7 +331,7 @@ public async Task TestPlayerCanGhost() EntityUid entity = default!; Mind mind = default!; - IPlayerSession player = playerMan.ServerSessions.Single(); + var player = playerMan.ServerSessions.Single(); await server.WaitAssertion(() => { @@ -333,7 +360,7 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(mind.OwnedEntity != null); + Assert.That(mind.OwnedEntity, Is.Not.Null); mob = entMan.SpawnEntity(null, new MapCoordinates()); @@ -349,9 +376,12 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { var m = player.ContentData()?.Mind; - Assert.That(m, Is.Not.EqualTo(null)); - Assert.That(m!.OwnedEntity, Is.EqualTo(mob)); - Assert.That(m, Is.Not.EqualTo(mind)); + Assert.That(m, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(m!.OwnedEntity, Is.EqualTo(mob)); + Assert.That(m, Is.Not.EqualTo(mind)); + }); }); await pairTracker.CleanReturnAsync(); @@ -376,11 +406,11 @@ public async Task TestGhostDoesNotInfiniteLoop() var mindSystem = entMan.EntitySysManager.GetEntitySystem(); - EntityUid entity = default!; + //EntityUid entity = default!; EntityUid mouse = default!; EntityUid ghost = default!; Mind mind = default!; - IPlayerSession player = playerMan.ServerSessions.Single(); + var player = playerMan.ServerSessions.Single(); await server.WaitAssertion(() => { @@ -399,7 +429,7 @@ await server.WaitAssertion(() => Assert.That(data?.Mind, Is.Not.EqualTo(null)); mind = data!.Mind!; - Assert.That(mind.OwnedEntity != null); + Assert.That(mind.OwnedEntity, Is.Not.Null); mouse = entMan.SpawnEntity("MobMouse", new MapCoordinates()); }); @@ -423,10 +453,10 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { var data = player.ContentData()!; - Assert.That(data.Mind!.OwnedEntity == mouse); + Assert.That(data.Mind!.OwnedEntity, Is.EqualTo(mouse)); serverConsole.ExecuteCommand(player, "aghost"); - Assert.That(player.AttachedEntity != null); + Assert.That(player.AttachedEntity, Is.Not.Null); ghost = player.AttachedEntity!.Value; }); @@ -434,8 +464,8 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(player.AttachedEntity != null); - Assert.That(ghost == player.AttachedEntity!.Value); + Assert.That(player.AttachedEntity, Is.Not.Null); + Assert.That(player.AttachedEntity!.Value, Is.EqualTo(ghost)); }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/NPC/NPCTest.cs b/Content.IntegrationTests/Tests/NPC/NPCTest.cs index 08df5f98a2c..a58f5af1cc4 100644 --- a/Content.IntegrationTests/Tests/NPC/NPCTest.cs +++ b/Content.IntegrationTests/Tests/NPC/NPCTest.cs @@ -1,8 +1,5 @@ -using System; using System.Collections.Generic; -using System.Threading.Tasks; using Content.Server.NPC.HTN; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Prototypes; using Robust.Shared.Utility; diff --git a/Content.IntegrationTests/Tests/Networking/AutoPredictReconcileTest.cs b/Content.IntegrationTests/Tests/Networking/AutoPredictReconcileTest.cs new file mode 100644 index 00000000000..a9b76138760 --- /dev/null +++ b/Content.IntegrationTests/Tests/Networking/AutoPredictReconcileTest.cs @@ -0,0 +1,453 @@ +#nullable enable +using System.Collections.Generic; +using System.Linq; +using Robust.Client.GameStates; +using Robust.Client.Timing; +using Robust.Server.Player; +using Robust.Shared; +using Robust.Shared.Analyzers; +using Robust.Shared.Configuration; +using Robust.Shared.GameObjects; +using Robust.Shared.GameStates; +using Robust.Shared.IoC; +using Robust.Shared.Log; +using Robust.Shared.Map; +using Robust.Shared.Reflection; +using Robust.Shared.Timing; + +namespace Content.IntegrationTests.Tests.Networking +{ + // This test checks that the prediction & reconciling system is working correctly with a simple boolean flag. + // An entity system sets a flag on a networked component via a RaisePredictiveEvent, + // so it runs predicted on client and eventually on server. + // All the tick values are checked to ensure it arrives on client & server at the exact correct ticks. + // On the client, the reconciling system is checked to ensure that the state correctly reset every tick, + // until the server acknowledges it. + // Then, the same test is performed again, but the server does not handle the message (it ignores it). + // To simulate a mispredict. + // This means the client is forced to reset it once it gets to the server tick where the server didn't do anything. + // the tick where the server *should* have, but did not, acknowledge the state change. + // Finally, we run two events inside the prediction area to ensure reconciling does for incremental stuff. + [TestFixture] + public sealed class AutoPredictReconcileTest + { + [Test] + public async Task Test() + { + await using var pairTracker = await PoolManager.GetServerClient(new() { Fresh = true, DummyTicker = true }); + var server = pairTracker.Pair.Server; + var client = pairTracker.Pair.Client; + + // Pull in all dependencies we need. + var sPlayerManager = server.ResolveDependency(); + var sMapManager = server.ResolveDependency(); + var sEntityManager = server.ResolveDependency(); + var cEntityManager = client.ResolveDependency(); + var sGameTiming = server.ResolveDependency(); + var cGameTiming = client.ResolveDependency(); + var cGameStateManager = client.ResolveDependency(); + var cfg = client.ResolveDependency(); + var log = cfg.GetCVar(CVars.NetLogging); + + //cfg.SetCVar(CVars.NetLogging, true); + + EntityUid serverEnt = default; + AutoPredictionTestComponent serverComponent = default!; + AutoPredictionTestComponent clientComponent = default!; + + var serverSystem = server.ResolveDependency() + .GetEntitySystem(); + var clientSystem = client.ResolveDependency() + .GetEntitySystem(); + + await server.WaitPost(() => + { + // Spawn dummy component entity. + var map = sMapManager.CreateMap(); + var player = sPlayerManager.ServerSessions.Single(); + serverEnt = sEntityManager.SpawnEntity(null, new MapCoordinates((0, 0), map)); + serverComponent = sEntityManager.AddComponent(serverEnt); + + // Make client "join game" so they receive game state updates. + player.JoinGame(); + }); + + // Run some ticks so that + await PoolManager.RunTicksSync(pairTracker.Pair, 3); + + // Check client buffer is full + Assert.That(cGameStateManager.CurrentBufferSize, Is.EqualTo(cGameStateManager.TargetBufferSize)); + + // This isn't required anymore, but the test had this for the sake of "technical things", and I cbf shifting + // all the tick times over. So it stays. + await client.WaitRunTicks(1); + + await client.WaitPost(() => + { + clientComponent = cEntityManager.GetComponent(serverEnt); + }); + + Assert.Multiple(() => + { + Assert.That(clientComponent.Foo, Is.False); + + // KEEP IN MIND WHEN READING THIS. + // The game loop increments CurTick AFTER running the tick. + // So when reading CurTick inside an Assert or Post or whatever, the tick reported is the NEXT one to run. + + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(14))); + Assert.That(serverComponent.Foo, Is.False); + + // Client last ran tick 15 meaning it's ahead of the last server tick it processed (12) + Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(16))); + Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(12))); + }); + + // *** I am using block scopes to visually distinguish these sections of the test to make it more readable. + + + // Send an event to change the flag and instantly see the effect replicate client side, + // while it's queued on server and reconciling works (constantly needs re-firing on client). + { + await client.WaitPost(() => + { + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, true)); + + Assert.That(clientComponent.Foo, Is.True); + }); + + // Event correctly arrived on client system. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(16), true, false, true, true) })); + clientSystem.EventTriggerList.Clear(); + + // Two ticks happen on both sides with nothing really "changing". + // Server doesn't receive it yet, + // client is still replaying the past prediction. + for (var i = 0; i < 2; i++) + { + await server.WaitRunTicks(1); + + // Event did not arrive on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(16), false, false, true, true) })); + clientSystem.EventTriggerList.Clear(); + } + + { + await server.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event arrived on server at tick 16. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(17))); + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(16), true, false, true, true) })); + }); + serverSystem.EventTriggerList.Clear(); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(16), false, false, true, true) })); + clientSystem.EventTriggerList.Clear(); + } + + { + await server.WaitRunTicks(1); + + // Nothing happened on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, Is.Empty); + Assert.That(clientComponent.Foo, Is.True); + }); + clientSystem.EventTriggerList.Clear(); + } + } + + // Disallow changes to simulate a misprediction. + serverSystem.Allow = false; + + Assert.Multiple(() => + { + // Assert timing is still correct, should be but it's a good reference for the rest of the test. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(18))); + Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(20))); + Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(16))); + }); + + { + // Send event to server to change flag again, this time to disable it.. + await client.WaitPost(() => + { + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, false)); + + Assert.That(clientComponent.Foo, Is.False); + }); + + // Event correctly arrived on client system. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(20), true, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + + for (var i = 0; i < 2; i++) + { + await server.WaitRunTicks(1); + + // Event did not arrive on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(20), false, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + } + + { + await server.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event arrived on server at tick 20. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(21))); + // But the server didn't listen! + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(20), true, true, true, false) })); + }); + serverSystem.EventTriggerList.Clear(); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(20), false, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + } + + { + await server.WaitRunTicks(1); + + // Nothing happened on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event no longer got repeated and flag was *not* set by server state. + // Mispredict gracefully handled! + Assert.That(clientSystem.EventTriggerList, Is.Empty); + Assert.That(clientComponent.Foo, Is.True); + }); + clientSystem.EventTriggerList.Clear(); + } + } + + // Re-allow changes to make everything work correctly again. + serverSystem.Allow = true; + + Assert.Multiple(() => + { + // Assert timing is still correct. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(22))); + Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(24))); + Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(20))); + }); + + { + // Send first event to disable the flag (reminder: it never got accepted by the server). + await client.WaitPost(() => + { + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, false)); + + Assert.That(clientComponent.Foo, Is.False); + }); + + // Event correctly arrived on client system. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(24), true, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + + // Run one tick, everything checks out. + { + await server.WaitRunTicks(1); + + // Event did not arrive on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(24), false, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + } + + // Send another event, to re-enable it. + await client.WaitPost(() => + { + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, true)); + + Assert.That(clientComponent.Foo, Is.True); + }); + + // Event correctly arrived on client system. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(25), true, false, true, true) })); + clientSystem.EventTriggerList.Clear(); + + // Next tick we run, both events come in, but at different times. + { + await server.WaitRunTicks(1); + + // Event did not arrive on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] + { + (new GameTick(24), false, true, false, false), (new GameTick(25), false, false, true, true) + })); + clientSystem.EventTriggerList.Clear(); + } + + // FIRST event arrives on server! + { + await server.WaitRunTicks(1); + + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(24), true, true, false, false) })); + serverSystem.EventTriggerList.Clear(); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] + { + (new GameTick(24), false, true, false, false), (new GameTick(25), false, false, true, true) + })); + clientSystem.EventTriggerList.Clear(); + } + + // SECOND event arrived on server, client receives ack for first event, + // still runs second event as past prediction. + { + await server.WaitRunTicks(1); + + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(25), true, false, true, true) })); + serverSystem.EventTriggerList.Clear(); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] + { + (new GameTick(25), false, false, true, true) + })); + clientSystem.EventTriggerList.Clear(); + } + + // Finally, second event acknowledged on client and we're good. + { + await server.WaitRunTicks(1); + + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, Is.Empty); + + Assert.That(clientComponent.Foo, Is.True); + }); + } + } + + cfg.SetCVar(CVars.NetLogging, log); + await pairTracker.CleanReturnAsync(); + } + + [Reflect(false)] + public sealed class AutoPredictionTestEntitySystem : EntitySystem + { + public bool Allow { get; set; } = true; + + // Queue of all the events that come in so we can test that they come in perfectly as expected. + public List<(GameTick tick, bool firstPredict, bool old, bool @new, bool value)> EventTriggerList { get; } = + new(); + + [Dependency] private readonly IGameTiming _gameTiming = default!; + + public override void Initialize() + { + base.Initialize(); + + SubscribeNetworkEvent(HandleMessage); + SubscribeLocalEvent(HandleMessage); + SubscribeLocalEvent(AfterAutoHandleState); + } + + private void HandleMessage(SetFooMessage message, EntitySessionEventArgs args) + { + var component = EntityManager.GetComponent(message.Uid); + var old = component.Foo; + if (Allow) + { + component.Foo = message.NewFoo; + Dirty(message.Uid, component); + } + + EventTriggerList.Add((_gameTiming.CurTick, _gameTiming.IsFirstTimePredicted, old, component.Foo, message.NewFoo)); + } + + private void AfterAutoHandleState(EntityUid uid, AutoPredictionTestComponent comp, ref AfterAutoHandleStateEvent args) + { + Dirty(uid, comp); + } + } + + public sealed class SetFooMessage : EntityEventArgs + { + public SetFooMessage(EntityUid uid, bool newFoo) + { + Uid = uid; + NewFoo = newFoo; + } + + public EntityUid Uid { get; } + public bool NewFoo { get; } + } + } + + // Must be directly located in the namespace or the sourcegen can't find it. + [NetworkedComponent()] + [AutoGenerateComponentState] + [Access(typeof(AutoPredictReconcileTest.AutoPredictionTestEntitySystem))] + public sealed partial class AutoPredictionTestComponent : Component + { + [AutoNetworkedField] + public bool Foo; + } +} diff --git a/Content.IntegrationTests/Tests/Networking/ConnectTest.cs b/Content.IntegrationTests/Tests/Networking/ConnectTest.cs index 59843368413..23f995a9b43 100644 --- a/Content.IntegrationTests/Tests/Networking/ConnectTest.cs +++ b/Content.IntegrationTests/Tests/Networking/ConnectTest.cs @@ -1,12 +1,7 @@ using System.Linq; -using System.Threading.Tasks; -using NUnit.Framework; using Robust.Server.Player; -using Robust.Shared; using Robust.Shared.Enums; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Network; namespace Content.IntegrationTests.Tests.Networking { @@ -23,8 +18,10 @@ public async Task TestConnect() // Basic checks to ensure that they're connected and data got replicated. var playerManager = server.ResolveDependency(); +#pragma warning disable NUnit2045 // Interdependent assertions. Assert.That(playerManager.PlayerCount, Is.EqualTo(1)); Assert.That(playerManager.Sessions.First().Status, Is.EqualTo(SessionStatus.InGame)); +#pragma warning restore NUnit2045 var clEntityManager = client.ResolveDependency(); var svEntityManager = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/Networking/NetworkIdsMatchTest.cs b/Content.IntegrationTests/Tests/Networking/NetworkIdsMatchTest.cs index d848f7ca1c6..7071c3d16eb 100644 --- a/Content.IntegrationTests/Tests/Networking/NetworkIdsMatchTest.cs +++ b/Content.IntegrationTests/Tests/Networking/NetworkIdsMatchTest.cs @@ -1,13 +1,9 @@ -using System.Threading.Tasks; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Network; namespace Content.IntegrationTests.Tests.Networking { [TestFixture] - sealed class NetworkIdsMatchTest + public sealed class NetworkIdsMatchTest { [Test] public async Task TestConnect() @@ -22,17 +18,26 @@ public async Task TestConnect() var clientNetComps = clientCompFactory.NetworkedComponents; var serverNetComps = serverCompFactory.NetworkedComponents; - Assert.That(clientNetComps, Is.Not.Null); - Assert.That(serverNetComps, Is.Not.Null); - Assert.That(clientNetComps.Count, Is.EqualTo(serverNetComps.Count)); + Assert.Multiple(() => + { + Assert.That(clientNetComps, Is.Not.Null); + Assert.That(serverNetComps, Is.Not.Null); + }); + Assert.Multiple(() => + { + Assert.That(clientNetComps, Has.Count.EqualTo(serverNetComps.Count)); - // Checks that at least Metadata and Transform are registered. - Assert.That(clientNetComps.Count, Is.GreaterThanOrEqualTo(2)); + // Checks that at least Metadata and Transform are registered. + Assert.That(clientNetComps, Has.Count.GreaterThanOrEqualTo(2)); + }); - for (var netId = 0; netId < clientNetComps.Count; netId++) + Assert.Multiple(() => { - Assert.That(clientNetComps[netId].Name, Is.EqualTo(serverNetComps[netId].Name)); - } + for (var netId = 0; netId < clientNetComps.Count; netId++) + { + Assert.That(clientNetComps[netId].Name, Is.EqualTo(serverNetComps[netId].Name)); + } + }); await pairTracker.CleanReturnAsync(); } } diff --git a/Content.IntegrationTests/Tests/Networking/ReconnectTest.cs b/Content.IntegrationTests/Tests/Networking/ReconnectTest.cs index 893694d509c..51d6297bc0f 100644 --- a/Content.IntegrationTests/Tests/Networking/ReconnectTest.cs +++ b/Content.IntegrationTests/Tests/Networking/ReconnectTest.cs @@ -1,7 +1,4 @@ -using System.Threading.Tasks; -using NUnit.Framework; using Robust.Client.Console; -using Robust.Shared.IoC; using Robust.Shared.Network; namespace Content.IntegrationTests.Tests.Networking diff --git a/Content.IntegrationTests/Tests/Networking/SimplePredictReconcileTest.cs b/Content.IntegrationTests/Tests/Networking/SimplePredictReconcileTest.cs index b7000b5d202..eecaef69955 100644 --- a/Content.IntegrationTests/Tests/Networking/SimplePredictReconcileTest.cs +++ b/Content.IntegrationTests/Tests/Networking/SimplePredictReconcileTest.cs @@ -1,15 +1,11 @@ #nullable enable -using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; -using NUnit.Framework; -using Robust.Client.GameObjects; using Robust.Client.GameStates; using Robust.Client.Timing; -using Robust.Server.GameStates; using Robust.Server.Player; using Robust.Shared; +using Robust.Shared.Analyzers; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; @@ -32,13 +28,14 @@ namespace Content.IntegrationTests.Tests.Networking // This means the client is forced to reset it once it gets to the server tick where the server didn't do anything. // the tick where the server *should* have, but did not, acknowledge the state change. // Finally, we run two events inside the prediction area to ensure reconciling does for incremental stuff. + // TODO: This test relies on the EC version of component state handling. Remove in favor of the other two tests for the ECS and auto versions. [TestFixture] public sealed class SimplePredictReconcileTest { [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new (){Fresh = true, DummyTicker = true}); + await using var pairTracker = await PoolManager.GetServerClient(new() { Fresh = true, DummyTicker = true }); var server = pairTracker.Pair.Server; var client = pairTracker.Pair.Client; @@ -91,18 +88,21 @@ await client.WaitPost(() => clientComponent = cEntityManager.GetComponent(serverEnt); }); - Assert.That(clientComponent.Foo, Is.False); + Assert.Multiple(() => + { + Assert.That(clientComponent.Foo, Is.False); - // KEEP IN MIND WHEN READING THIS. - // The game loop increments CurTick AFTER running the tick. - // So when reading CurTick inside an Assert or Post or whatever, the tick reported is the NEXT one to run. + // KEEP IN MIND WHEN READING THIS. + // The game loop increments CurTick AFTER running the tick. + // So when reading CurTick inside an Assert or Post or whatever, the tick reported is the NEXT one to run. - Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(14))); - Assert.That(serverComponent.Foo, Is.False); + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(14))); + Assert.That(serverComponent.Foo, Is.False); - // Client last ran tick 15 meaning it's ahead of the last server tick it processed (12) - Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(16))); - Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(12))); + // Client last ran tick 15 meaning it's ahead of the last server tick it processed (12) + Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(16))); + Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(12))); + }); // *** I am using block scopes to visually distinguish these sections of the test to make it more readable. @@ -119,7 +119,7 @@ await client.WaitPost(() => // Event correctly arrived on client system. Assert.That(clientSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(16), true, false, true, true)})); + Is.EquivalentTo(new[] { (new GameTick(16), true, false, true, true) })); clientSystem.EventTriggerList.Clear(); // Two ticks happen on both sides with nothing really "changing". @@ -136,24 +136,27 @@ await client.WaitPost(() => // Event got repeated on client as a past prediction. Assert.That(clientSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(16), false, false, true, true)})); + Is.EquivalentTo(new[] { (new GameTick(16), false, false, true, true) })); clientSystem.EventTriggerList.Clear(); } { await server.WaitRunTicks(1); - // Event arrived on server at tick 16. - Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(17))); - Assert.That(serverSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(16), true, false, true, true)})); + Assert.Multiple(() => + { + // Event arrived on server at tick 16. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(17))); + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(16), true, false, true, true) })); + }); serverSystem.EventTriggerList.Clear(); await client.WaitRunTicks(1); // Event got repeated on client as a past prediction. Assert.That(clientSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(16), false, false, true, true)})); + Is.EquivalentTo(new[] { (new GameTick(16), false, false, true, true) })); clientSystem.EventTriggerList.Clear(); } @@ -165,9 +168,12 @@ await client.WaitPost(() => await client.WaitRunTicks(1); - // Event got repeated on client as a past prediction. - Assert.That(clientSystem.EventTriggerList, Is.Empty); - Assert.That(clientComponent.Foo, Is.True); + Assert.Multiple(() => + { + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, Is.Empty); + Assert.That(clientComponent.Foo, Is.True); + }); clientSystem.EventTriggerList.Clear(); } } @@ -175,10 +181,13 @@ await client.WaitPost(() => // Disallow changes to simulate a misprediction. serverSystem.Allow = false; - // Assert timing is still correct, should be but it's a good reference for the rest of the test. - Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(18))); - Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(20))); - Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(16))); + Assert.Multiple(() => + { + // Assert timing is still correct, should be but it's a good reference for the rest of the test. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(18))); + Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(20))); + Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(16))); + }); { // Send event to server to change flag again, this time to disable it.. @@ -191,7 +200,7 @@ await client.WaitPost(() => // Event correctly arrived on client system. Assert.That(clientSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(20), true, true, false, false)})); + Is.EquivalentTo(new[] { (new GameTick(20), true, true, false, false) })); clientSystem.EventTriggerList.Clear(); for (var i = 0; i < 2; i++) @@ -205,25 +214,28 @@ await client.WaitPost(() => // Event got repeated on client as a past prediction. Assert.That(clientSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(20), false, true, false, false)})); + Is.EquivalentTo(new[] { (new GameTick(20), false, true, false, false) })); clientSystem.EventTriggerList.Clear(); } { await server.WaitRunTicks(1); - // Event arrived on server at tick 20. - Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(21))); - // But the server didn't listen! - Assert.That(serverSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(20), true, true, true, false)})); + Assert.Multiple(() => + { + // Event arrived on server at tick 20. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(21))); + // But the server didn't listen! + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(20), true, true, true, false) })); + }); serverSystem.EventTriggerList.Clear(); await client.WaitRunTicks(1); // Event got repeated on client as a past prediction. Assert.That(clientSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(20), false, true, false, false)})); + Is.EquivalentTo(new[] { (new GameTick(20), false, true, false, false) })); clientSystem.EventTriggerList.Clear(); } @@ -235,10 +247,13 @@ await client.WaitPost(() => await client.WaitRunTicks(1); - // Event no longer got repeated and flag was *not* set by server state. - // Mispredict gracefully handled! - Assert.That(clientSystem.EventTriggerList, Is.Empty); - Assert.That(clientComponent.Foo, Is.True); + Assert.Multiple(() => + { + // Event no longer got repeated and flag was *not* set by server state. + // Mispredict gracefully handled! + Assert.That(clientSystem.EventTriggerList, Is.Empty); + Assert.That(clientComponent.Foo, Is.True); + }); clientSystem.EventTriggerList.Clear(); } } @@ -246,10 +261,13 @@ await client.WaitPost(() => // Re-allow changes to make everything work correctly again. serverSystem.Allow = true; - // Assert timing is still correct. - Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(22))); - Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(24))); - Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(20))); + Assert.Multiple(() => + { + // Assert timing is still correct. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(22))); + Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(24))); + Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(20))); + }); { // Send first event to disable the flag (reminder: it never got accepted by the server). @@ -262,7 +280,7 @@ await client.WaitPost(() => // Event correctly arrived on client system. Assert.That(clientSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(24), true, true, false, false)})); + Is.EquivalentTo(new[] { (new GameTick(24), true, true, false, false) })); clientSystem.EventTriggerList.Clear(); // Run one tick, everything checks out. @@ -276,7 +294,7 @@ await client.WaitPost(() => // Event got repeated on client as a past prediction. Assert.That(clientSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(24), false, true, false, false)})); + Is.EquivalentTo(new[] { (new GameTick(24), false, true, false, false) })); clientSystem.EventTriggerList.Clear(); } @@ -290,7 +308,7 @@ await client.WaitPost(() => // Event correctly arrived on client system. Assert.That(clientSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(25), true, false, true, true)})); + Is.EquivalentTo(new[] { (new GameTick(25), true, false, true, true) })); clientSystem.EventTriggerList.Clear(); // Next tick we run, both events come in, but at different times. @@ -316,7 +334,7 @@ await client.WaitPost(() => await server.WaitRunTicks(1); Assert.That(serverSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(24), true, true, false, false)})); + Is.EquivalentTo(new[] { (new GameTick(24), true, true, false, false) })); serverSystem.EventTriggerList.Clear(); await client.WaitRunTicks(1); @@ -336,7 +354,7 @@ await client.WaitPost(() => await server.WaitRunTicks(1); Assert.That(serverSystem.EventTriggerList, - Is.EquivalentTo(new[] {(new GameTick(25), true, false, true, true)})); + Is.EquivalentTo(new[] { (new GameTick(25), true, false, true, true) })); serverSystem.EventTriggerList.Clear(); await client.WaitRunTicks(1); @@ -358,10 +376,13 @@ await client.WaitPost(() => await client.WaitRunTicks(1); - // Event got repeated on client as a past prediction. - Assert.That(clientSystem.EventTriggerList, Is.Empty); + Assert.Multiple(() => + { + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, Is.Empty); - Assert.That(clientComponent.Foo, Is.True); + Assert.That(clientComponent.Foo, Is.True); + }); } } @@ -370,33 +391,23 @@ await client.WaitPost(() => } [NetworkedComponent()] + [Access(typeof(PredictionTestEntitySystem))] public sealed class PredictionTestComponent : Component { - private bool _foo; + public bool Foo; - public bool Foo + public override ComponentState GetComponentState() { - get => _foo; - set - { - _foo = value; - Dirty(); - } + return new PredictionComponentState(Foo); } public override void HandleComponentState(ComponentState? curState, ComponentState? nextState) { - if (curState is not PredictionComponentState pred) - { + if (curState is not PredictionComponentState state) return; - } - - Foo = pred.Foo; - } - public override ComponentState GetComponentState() - { - return new PredictionComponentState(Foo); + Foo = state.Foo; + Dirty(); } [Serializable, NetSerializable] @@ -437,10 +448,10 @@ private void HandleMessage(SetFooMessage message, EntitySessionEventArgs args) if (Allow) { component.Foo = message.NewFoo; + Dirty(message.Uid, component); } - EventTriggerList.Add((_gameTiming.CurTick, _gameTiming.IsFirstTimePredicted, old, component.Foo, - message.NewFoo)); + EventTriggerList.Add((_gameTiming.CurTick, _gameTiming.IsFirstTimePredicted, old, component.Foo, message.NewFoo)); } } diff --git a/Content.IntegrationTests/Tests/Networking/SystemPredictReconcileTest.cs b/Content.IntegrationTests/Tests/Networking/SystemPredictReconcileTest.cs new file mode 100644 index 00000000000..19f7f10c2e4 --- /dev/null +++ b/Content.IntegrationTests/Tests/Networking/SystemPredictReconcileTest.cs @@ -0,0 +1,471 @@ +#nullable enable +using System.Collections.Generic; +using System.Linq; +using Robust.Client.GameStates; +using Robust.Client.Timing; +using Robust.Server.Player; +using Robust.Shared; +using Robust.Shared.Analyzers; +using Robust.Shared.Configuration; +using Robust.Shared.GameObjects; +using Robust.Shared.GameStates; +using Robust.Shared.IoC; +using Robust.Shared.Map; +using Robust.Shared.Reflection; +using Robust.Shared.Serialization; +using Robust.Shared.Timing; + +namespace Content.IntegrationTests.Tests.Networking +{ + // This test checks that the prediction & reconciling system is working correctly with a simple boolean flag. + // An entity system sets a flag on a networked component via a RaisePredictiveEvent, + // so it runs predicted on client and eventually on server. + // All the tick values are checked to ensure it arrives on client & server at the exact correct ticks. + // On the client, the reconciling system is checked to ensure that the state correctly reset every tick, + // until the server acknowledges it. + // Then, the same test is performed again, but the server does not handle the message (it ignores it). + // To simulate a mispredict. + // This means the client is forced to reset it once it gets to the server tick where the server didn't do anything. + // the tick where the server *should* have, but did not, acknowledge the state change. + // Finally, we run two events inside the prediction area to ensure reconciling does for incremental stuff. + [TestFixture] + public sealed class SystemPredictReconcileTest + { + [Test] + public async Task Test() + { + await using var pairTracker = await PoolManager.GetServerClient(new() { Fresh = true, DummyTicker = true }); + var server = pairTracker.Pair.Server; + var client = pairTracker.Pair.Client; + + // Pull in all dependencies we need. + var sPlayerManager = server.ResolveDependency(); + var sMapManager = server.ResolveDependency(); + var sEntityManager = server.ResolveDependency(); + var cEntityManager = client.ResolveDependency(); + var sGameTiming = server.ResolveDependency(); + var cGameTiming = client.ResolveDependency(); + var cGameStateManager = client.ResolveDependency(); + var cfg = client.ResolveDependency(); + var log = cfg.GetCVar(CVars.NetLogging); + + //cfg.SetCVar(CVars.NetLogging, true); + + EntityUid serverEnt = default; + SystemPredictionTestComponent serverComponent = default!; + SystemPredictionTestComponent clientComponent = default!; + + var serverSystem = server.ResolveDependency() + .GetEntitySystem(); + var clientSystem = client.ResolveDependency() + .GetEntitySystem(); + + await server.WaitPost(() => + { + // Spawn dummy component entity. + var map = sMapManager.CreateMap(); + var player = sPlayerManager.ServerSessions.Single(); + serverEnt = sEntityManager.SpawnEntity(null, new MapCoordinates((0, 0), map)); + serverComponent = sEntityManager.AddComponent(serverEnt); + + // Make client "join game" so they receive game state updates. + player.JoinGame(); + }); + + // Run some ticks so that + await PoolManager.RunTicksSync(pairTracker.Pair, 3); + + // Check client buffer is full + Assert.That(cGameStateManager.CurrentBufferSize, Is.EqualTo(cGameStateManager.TargetBufferSize)); + + // This isn't required anymore, but the test had this for the sake of "technical things", and I cbf shifting + // all the tick times over. So it stays. + await client.WaitRunTicks(1); + + await client.WaitPost(() => + { + clientComponent = cEntityManager.GetComponent(serverEnt); + }); + + Assert.Multiple(() => + { + Assert.That(clientComponent.Foo, Is.False); + + // KEEP IN MIND WHEN READING THIS. + // The game loop increments CurTick AFTER running the tick. + // So when reading CurTick inside an Assert or Post or whatever, the tick reported is the NEXT one to run. + + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(14))); + Assert.That(serverComponent.Foo, Is.False); + + // Client last ran tick 15 meaning it's ahead of the last server tick it processed (12) + Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(16))); + Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(12))); + }); + + // *** I am using block scopes to visually distinguish these sections of the test to make it more readable. + + + // Send an event to change the flag and instantly see the effect replicate client side, + // while it's queued on server and reconciling works (constantly needs re-firing on client). + { + await client.WaitPost(() => + { + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, true)); + + Assert.That(clientComponent.Foo, Is.True); + }); + + // Event correctly arrived on client system. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(16), true, false, true, true) })); + clientSystem.EventTriggerList.Clear(); + + // Two ticks happen on both sides with nothing really "changing". + // Server doesn't receive it yet, + // client is still replaying the past prediction. + for (var i = 0; i < 2; i++) + { + await server.WaitRunTicks(1); + + // Event did not arrive on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(16), false, false, true, true) })); + clientSystem.EventTriggerList.Clear(); + } + + { + await server.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event arrived on server at tick 16. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(17))); + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(16), true, false, true, true) })); + }); + serverSystem.EventTriggerList.Clear(); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(16), false, false, true, true) })); + clientSystem.EventTriggerList.Clear(); + } + + { + await server.WaitRunTicks(1); + + // Nothing happened on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, Is.Empty); + Assert.That(clientComponent.Foo, Is.True); + }); + clientSystem.EventTriggerList.Clear(); + } + } + + // Disallow changes to simulate a misprediction. + serverSystem.Allow = false; + + Assert.Multiple(() => + { + // Assert timing is still correct, should be but it's a good reference for the rest of the test. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(18))); + Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(20))); + Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(16))); + }); + + { + // Send event to server to change flag again, this time to disable it.. + await client.WaitPost(() => + { + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, false)); + + Assert.That(clientComponent.Foo, Is.False); + }); + + // Event correctly arrived on client system. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(20), true, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + + for (var i = 0; i < 2; i++) + { + await server.WaitRunTicks(1); + + // Event did not arrive on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(20), false, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + } + + { + await server.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event arrived on server at tick 20. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(21))); + // But the server didn't listen! + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(20), true, true, true, false) })); + }); + serverSystem.EventTriggerList.Clear(); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(20), false, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + } + + { + await server.WaitRunTicks(1); + + // Nothing happened on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event no longer got repeated and flag was *not* set by server state. + // Mispredict gracefully handled! + Assert.That(clientSystem.EventTriggerList, Is.Empty); + Assert.That(clientComponent.Foo, Is.True); + }); + clientSystem.EventTriggerList.Clear(); + } + } + + // Re-allow changes to make everything work correctly again. + serverSystem.Allow = true; + + Assert.Multiple(() => + { + // Assert timing is still correct. + Assert.That(sGameTiming.CurTick, Is.EqualTo(new GameTick(22))); + Assert.That(cGameTiming.CurTick, Is.EqualTo(new GameTick(24))); + Assert.That(cGameTiming.LastProcessedTick, Is.EqualTo(new GameTick(20))); + }); + + { + // Send first event to disable the flag (reminder: it never got accepted by the server). + await client.WaitPost(() => + { + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, false)); + + Assert.That(clientComponent.Foo, Is.False); + }); + + // Event correctly arrived on client system. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(24), true, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + + // Run one tick, everything checks out. + { + await server.WaitRunTicks(1); + + // Event did not arrive on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(24), false, true, false, false) })); + clientSystem.EventTriggerList.Clear(); + } + + // Send another event, to re-enable it. + await client.WaitPost(() => + { + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, true)); + + Assert.That(clientComponent.Foo, Is.True); + }); + + // Event correctly arrived on client system. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(25), true, false, true, true) })); + clientSystem.EventTriggerList.Clear(); + + // Next tick we run, both events come in, but at different times. + { + await server.WaitRunTicks(1); + + // Event did not arrive on server. + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] + { + (new GameTick(24), false, true, false, false), (new GameTick(25), false, false, true, true) + })); + clientSystem.EventTriggerList.Clear(); + } + + // FIRST event arrives on server! + { + await server.WaitRunTicks(1); + + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(24), true, true, false, false) })); + serverSystem.EventTriggerList.Clear(); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] + { + (new GameTick(24), false, true, false, false), (new GameTick(25), false, false, true, true) + })); + clientSystem.EventTriggerList.Clear(); + } + + // SECOND event arrived on server, client receives ack for first event, + // still runs second event as past prediction. + { + await server.WaitRunTicks(1); + + Assert.That(serverSystem.EventTriggerList, + Is.EquivalentTo(new[] { (new GameTick(25), true, false, true, true) })); + serverSystem.EventTriggerList.Clear(); + + await client.WaitRunTicks(1); + + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, + Is.EquivalentTo(new[] + { + (new GameTick(25), false, false, true, true) + })); + clientSystem.EventTriggerList.Clear(); + } + + // Finally, second event acknowledged on client and we're good. + { + await server.WaitRunTicks(1); + + Assert.That(serverSystem.EventTriggerList, Is.Empty); + + await client.WaitRunTicks(1); + + Assert.Multiple(() => + { + // Event got repeated on client as a past prediction. + Assert.That(clientSystem.EventTriggerList, Is.Empty); + + Assert.That(clientComponent.Foo, Is.True); + }); + } + } + + cfg.SetCVar(CVars.NetLogging, log); + await pairTracker.CleanReturnAsync(); + } + + [NetworkedComponent()] + [Access(typeof(SystemPredictionTestEntitySystem))] + public sealed class SystemPredictionTestComponent : Component + { + public bool Foo; + } + + [Reflect(false)] + public sealed class SystemPredictionTestEntitySystem : EntitySystem + { + public bool Allow { get; set; } = true; + + // Queue of all the events that come in so we can test that they come in perfectly as expected. + public List<(GameTick tick, bool firstPredict, bool old, bool @new, bool value)> EventTriggerList { get; } = + new(); + + [Dependency] private readonly IGameTiming _gameTiming = default!; + + public override void Initialize() + { + base.Initialize(); + + SubscribeNetworkEvent(HandleMessage); + SubscribeLocalEvent(HandleMessage); + SubscribeLocalEvent(OnGetState); + SubscribeLocalEvent(OnHandleState); + } + + private void HandleMessage(SetFooMessage message, EntitySessionEventArgs args) + { + var component = EntityManager.GetComponent(message.Uid); + var old = component.Foo; + if (Allow) + { + component.Foo = message.NewFoo; + Dirty(message.Uid, component); + } + + EventTriggerList.Add((_gameTiming.CurTick, _gameTiming.IsFirstTimePredicted, old, component.Foo, message.NewFoo)); + } + + private void OnGetState(EntityUid uid, SystemPredictionTestComponent comp, ref ComponentGetState args) + { + args.State = new SystemPredictionComponentState(comp.Foo); + } + + private void OnHandleState(EntityUid uid, SystemPredictionTestComponent comp, ref ComponentHandleState args) + { + if (args.Current is not SystemPredictionComponentState state) + return; + + comp.Foo = state.Foo; + Dirty(uid, comp); + } + + [Serializable, NetSerializable] + private sealed class SystemPredictionComponentState : ComponentState + { + public bool Foo { get; } + + public SystemPredictionComponentState(bool foo) + { + Foo = foo; + } + } + } + + private sealed class SetFooMessage : EntityEventArgs + { + public SetFooMessage(EntityUid uid, bool newFoo) + { + Uid = uid; + NewFoo = newFoo; + } + + public EntityUid Uid { get; } + public bool NewFoo { get; } + } + } +} diff --git a/Content.IntegrationTests/Tests/Payload/ModularGrenadeTests.cs b/Content.IntegrationTests/Tests/Payload/ModularGrenadeTests.cs index a404e63629d..7dafdf551cc 100644 --- a/Content.IntegrationTests/Tests/Payload/ModularGrenadeTests.cs +++ b/Content.IntegrationTests/Tests/Payload/ModularGrenadeTests.cs @@ -1,7 +1,5 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Server.Explosion.Components; -using NUnit.Framework; using Robust.Shared.Containers; using Robust.Shared.GameObjects; @@ -73,4 +71,3 @@ public async Task AssembleAndDetonateGrenade() AssertDeleted(); } } - diff --git a/Content.IntegrationTests/Tests/PostMapInitTest.cs b/Content.IntegrationTests/Tests/PostMapInitTest.cs index a415a04e694..7a8131bdb96 100644 --- a/Content.IntegrationTests/Tests/PostMapInitTest.cs +++ b/Content.IntegrationTests/Tests/PostMapInitTest.cs @@ -1,25 +1,21 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; -using System.Threading.Tasks; using Content.Server.GameTicking; using Content.Server.Maps; using Content.Server.Shuttles.Components; using Content.Server.Spawners.Components; using Content.Server.Station.Components; -using Content.Server.Station.Systems; using Content.Shared.CCVar; using Content.Shared.Roles; -using NUnit.Framework; using Robust.Server.GameObjects; -using Robust.Server.Maps; using Robust.Shared.Configuration; using Robust.Shared.ContentPack; using Robust.Shared.GameObjects; using Robust.Shared.Utility; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Prototypes; using YamlDotNet.RepresentationModel; using ShuttleSystem = Content.Server.Shuttles.Systems.ShuttleSystem; @@ -38,7 +34,7 @@ public sealed class PostMapInitTest "Dart", }; - private static string[] Grids = + private static readonly string[] Grids = { "/Maps/centcomm.yml", "/Maps/Shuttles/cargo.yml", @@ -52,10 +48,11 @@ public sealed class PostMapInitTest [Test, TestCaseSource(nameof(Grids))] public async Task GridsLoadableTest(string mapFile) { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; - var mapLoader = server.ResolveDependency().GetEntitySystem(); + var entManager = server.ResolveDependency(); + var mapLoader = entManager.System(); var mapManager = server.ResolveDependency(); var cfg = server.ResolveDependency(); Assert.That(cfg.GetCVar(CCVars.GridFill), Is.False); @@ -65,7 +62,10 @@ await server.WaitPost(() => var mapId = mapManager.CreateMap(); try { - mapLoader.LoadGrid(mapId, mapFile); +#pragma warning disable NUnit2045 + Assert.That(mapLoader.TryLoad(mapId, mapFile, out var roots)); + Assert.That(roots.Where(uid => entManager.HasComponent(uid)), Is.Not.Empty); +#pragma warning restore NUnit2045 } catch (Exception ex) { @@ -89,7 +89,7 @@ await server.WaitPost(() => [Test] public async Task NoSavedPostMapInitTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var resourceManager = server.ResolveDependency(); @@ -123,14 +123,14 @@ public async Task NoSavedPostMapInitTest() var meta = root["meta"]; var postMapInit = meta["postmapinit"].AsBool(); - Assert.False(postMapInit, $"Map {map.Filename} was saved postmapinit"); + Assert.That(postMapInit, Is.False, $"Map {map.Filename} was saved postmapinit"); } await pairTracker.CleanReturnAsync(); } private static string[] GetGameMapNames() { - Task task; + Task task; using (ExecutionContext.SuppressFlow()) { task = Task.Run(static async () => @@ -168,7 +168,7 @@ private static string[] GetGameMapNames() await pairTracker.CleanReturnAsync(); return mapNames.ToArray(); }); - Task.WaitAll(task); + Task.WaitAny(task); } return task.GetAwaiter().GetResult(); @@ -177,7 +177,7 @@ private static string[] GetGameMapNames() [Test, TestCaseSource(nameof(GetGameMapNames))] public async Task GameMapsLoadableTest(string mapProto) { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); @@ -212,7 +212,8 @@ await server.WaitPost(() => foreach (var grid in grids) { - if (!memberQuery.HasComponent(grid.Owner)) + var gridEnt = grid.Owner; + if (!memberQuery.HasComponent(gridEnt)) continue; var area = grid.LocalAABB.Width * grid.LocalAABB.Height; @@ -220,7 +221,7 @@ await server.WaitPost(() => if (area > largest) { largest = area; - targetGrid = grid.Owner; + targetGrid = gridEnt; } } @@ -230,11 +231,18 @@ await server.WaitPost(() => if (entManager.TryGetComponent(station, out var stationEvac)) { var shuttlePath = stationEvac.EmergencyShuttlePath; - var shuttle = mapLoader.LoadGrid(shuttleMap, shuttlePath.ToString()); +#pragma warning disable NUnit2045 + Assert.That(mapLoader.TryLoad(shuttleMap, shuttlePath.ToString(), out var roots)); + EntityUid shuttle = default!; + Assert.DoesNotThrow(() => + { + shuttle = roots.First(uid => entManager.HasComponent(uid)); + }, $"Failed to load {shuttlePath}"); Assert.That( - shuttle != null && shuttleSystem.TryFTLDock(shuttle.Value, - entManager.GetComponent(shuttle.Value), targetGrid.Value), + shuttleSystem.TryFTLDock(shuttle, + entManager.GetComponent(shuttle), targetGrid.Value), $"Unable to dock {shuttlePath} to {mapProto}"); +#pragma warning restore NUnit2045 } mapManager.DeleteMap(shuttleMap); @@ -246,12 +254,13 @@ await server.WaitPost(() => { var lateSpawns = 0; - foreach (var comp in entManager.EntityQuery(true)) + var query = entManager.AllEntityQueryEnumerator(); + while (query.MoveNext(out var uid, out var comp)) { - if (comp.SpawnType != SpawnPointType.LateJoin || - !xformQuery.TryGetComponent(comp.Owner, out var xform) || - xform.GridUid == null || - !gridUids.Contains(xform.GridUid.Value)) + if (comp.SpawnType != SpawnPointType.LateJoin + || !xformQuery.TryGetComponent(uid, out var xform) + || xform.GridUid == null + || !gridUids.Contains(xform.GridUid.Value)) { continue; } @@ -279,8 +288,8 @@ await server.WaitPost(() => missingSpawnPoints.Add(spawnpoint); } - Assert.That(missingSpawnPoints.Count() == 0, - $"There is no spawnpoint for {String.Join(", ", missingSpawnPoints)} on {mapProto}."); + Assert.That(missingSpawnPoints, Has.Count.EqualTo(0), + $"There is no spawnpoint for {string.Join(", ", missingSpawnPoints)} on {mapProto}."); } try @@ -308,7 +317,7 @@ private static string[] GetMaps() task = Task.Run(static async () => { await Task.Yield(); - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{Disconnected = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { Disconnected = true }); var server = pairTracker.Pair.Server; var resourceManager = server.ResolveDependency(); var protoManager = server.ResolveDependency(); @@ -337,7 +346,7 @@ private static string[] GetMaps() await pairTracker.CleanReturnAsync(); return mapNames.ToArray(); }); - Task.WaitAll(task); + Task.WaitAny(task); } return task.GetAwaiter().GetResult(); @@ -346,7 +355,7 @@ private static string[] GetMaps() [Test, TestCaseSource(nameof(GetMaps))] public async Task MapsLoadableTest(string mapName) { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var mapLoader = server.ResolveDependency().GetEntitySystem(); @@ -359,7 +368,7 @@ await server.WaitPost(() => var mapId = mapManager.CreateMap(); try { - mapLoader.LoadMap(mapId, mapName); + Assert.That(mapLoader.TryLoad(mapId, mapName, out _)); } catch (Exception ex) { diff --git a/Content.IntegrationTests/Tests/Power/PowerTest.cs b/Content.IntegrationTests/Tests/Power/PowerTest.cs index 942676253db..a3f040744b9 100644 --- a/Content.IntegrationTests/Tests/Power/PowerTest.cs +++ b/Content.IntegrationTests/Tests/Power/PowerTest.cs @@ -1,6 +1,4 @@ #nullable enable -using System; -using System.Threading.Tasks; using Content.Server.NodeContainer; using Content.Server.NodeContainer.EntitySystems; using Content.Server.NodeContainer.Nodes; @@ -8,13 +6,10 @@ using Content.Server.Power.EntitySystems; using Content.Server.Power.Nodes; using Content.Shared.Coordinates; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Timing; -using TerraFX.Interop.Windows; -using static Content.Server.Power.Pow3r.PowerState; namespace Content.IntegrationTests.Tests.Power { @@ -166,7 +161,11 @@ public sealed class PowerTest [Test] public async Task TestSimpleSurplus() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); @@ -206,12 +205,15 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // Assert both consumers fully powered - Assert.That(consumer1.ReceivedPower, Is.EqualTo(consumer1.DrawRate).Within(0.1)); - Assert.That(consumer2.ReceivedPower, Is.EqualTo(consumer2.DrawRate).Within(0.1)); + Assert.Multiple(() => + { + // Assert both consumers fully powered + Assert.That(consumer1.ReceivedPower, Is.EqualTo(consumer1.DrawRate).Within(0.1)); + Assert.That(consumer2.ReceivedPower, Is.EqualTo(consumer2.DrawRate).Within(0.1)); - // Assert that load adds up on supply. - Assert.That(supplier.CurrentSupply, Is.EqualTo(loadPower * 2).Within(0.1)); + // Assert that load adds up on supply. + Assert.That(supplier.CurrentSupply, Is.EqualTo(loadPower * 2).Within(0.1)); + }); }); await pairTracker.CleanReturnAsync(); @@ -224,7 +226,11 @@ await server.WaitAssertion(() => [Test] public async Task TestSimpleDeficit() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); @@ -264,12 +270,15 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // Assert both consumers get 33% power. - Assert.That(consumer1.ReceivedPower, Is.EqualTo(consumer1.DrawRate / 3).Within(0.1)); - Assert.That(consumer2.ReceivedPower, Is.EqualTo(consumer2.DrawRate / 3).Within(0.1)); + Assert.Multiple(() => + { + // Assert both consumers get 33% power. + Assert.That(consumer1.ReceivedPower, Is.EqualTo(consumer1.DrawRate / 3).Within(0.1)); + Assert.That(consumer2.ReceivedPower, Is.EqualTo(consumer2.DrawRate / 3).Within(0.1)); - // Supply should be maxed out - Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); + // Supply should be maxed out + Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); + }); }); await pairTracker.CleanReturnAsync(); @@ -278,7 +287,11 @@ await server.WaitAssertion(() => [Test] public async Task TestSupplyRamp() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); @@ -319,9 +332,12 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // First tick, supply should be delivering 100 W (max tolerance) and start ramping up. - Assert.That(supplier.CurrentSupply, Is.EqualTo(100).Within(0.1)); - Assert.That(consumer.ReceivedPower, Is.EqualTo(100).Within(0.1)); + Assert.Multiple(() => + { + // First tick, supply should be delivering 100 W (max tolerance) and start ramping up. + Assert.That(supplier.CurrentSupply, Is.EqualTo(100).Within(0.1)); + Assert.That(consumer.ReceivedPower, Is.EqualTo(100).Within(0.1)); + }); }); // run for 0.25 seconds (minus the previous tick) @@ -330,10 +346,13 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // After 15 ticks (0.25 seconds), supply ramp pos should be at 100 W and supply at 100, approx. - Assert.That(supplier.CurrentSupply, Is.EqualTo(200).Within(tickDev)); - Assert.That(supplier.SupplyRampPosition, Is.EqualTo(100).Within(tickDev)); - Assert.That(consumer.ReceivedPower, Is.EqualTo(200).Within(tickDev)); + Assert.Multiple(() => + { + // After 15 ticks (0.25 seconds), supply ramp pos should be at 100 W and supply at 100, approx. + Assert.That(supplier.CurrentSupply, Is.EqualTo(200).Within(tickDev)); + Assert.That(supplier.SupplyRampPosition, Is.EqualTo(100).Within(tickDev)); + Assert.That(consumer.ReceivedPower, Is.EqualTo(200).Within(tickDev)); + }); }); @@ -344,10 +363,13 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // After 1 second total, ramp should be at 400 and supply should be at 400, everybody happy. - Assert.That(supplier.CurrentSupply, Is.EqualTo(400).Within(tickDev)); - Assert.That(supplier.SupplyRampPosition, Is.EqualTo(400).Within(tickDev)); - Assert.That(consumer.ReceivedPower, Is.EqualTo(400).Within(tickDev)); + Assert.Multiple(() => + { + // After 1 second total, ramp should be at 400 and supply should be at 400, everybody happy. + Assert.That(supplier.CurrentSupply, Is.EqualTo(400).Within(tickDev)); + Assert.That(supplier.SupplyRampPosition, Is.EqualTo(400).Within(tickDev)); + Assert.That(consumer.ReceivedPower, Is.EqualTo(400).Within(tickDev)); + }); }); await pairTracker.CleanReturnAsync(); @@ -356,11 +378,16 @@ await server.WaitAssertion(() => [Test] public async Task TestBatteryRamp() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); var gameTiming = server.ResolveDependency(); + var batterySys = entityManager.System(); const float startingCharge = 100_000; PowerNetworkBatteryComponent netBattery = default!; @@ -386,8 +413,8 @@ await server.WaitAssertion(() => battery = entityManager.GetComponent(generatorEnt); consumer = entityManager.GetComponent(consumerEnt); - battery.MaxCharge = startingCharge; - battery.CurrentCharge = startingCharge; + batterySys.SetMaxCharge(generatorEnt, startingCharge, battery); + batterySys.SetCharge(generatorEnt, startingCharge, battery); netBattery.MaxSupply = 400; netBattery.SupplyRampRate = 400; netBattery.SupplyRampTolerance = 100; @@ -402,9 +429,12 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // First tick, supply should be delivering 100 W (max tolerance) and start ramping up. - Assert.That(netBattery.CurrentSupply, Is.EqualTo(100).Within(0.1)); - Assert.That(consumer.ReceivedPower, Is.EqualTo(100).Within(0.1)); + Assert.Multiple(() => + { + // First tick, supply should be delivering 100 W (max tolerance) and start ramping up. + Assert.That(netBattery.CurrentSupply, Is.EqualTo(100).Within(0.1)); + Assert.That(consumer.ReceivedPower, Is.EqualTo(100).Within(0.1)); + }); }); // run for 0.25 seconds (minus the previous tick) @@ -413,14 +443,17 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // After 15 ticks (0.25 seconds), supply ramp pos should be at 100 W and supply at 100, approx. - Assert.That(netBattery.CurrentSupply, Is.EqualTo(200).Within(tickDev)); - Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(100).Within(tickDev)); - Assert.That(consumer.ReceivedPower, Is.EqualTo(200).Within(tickDev)); - - // Trivial integral to calculate expected power spent. - const double spentExpected = (200 + 100) / 2.0 * 0.25; - Assert.That(battery.CurrentCharge, Is.EqualTo(startingCharge - spentExpected).Within(tickDev)); + Assert.Multiple(() => + { + // After 15 ticks (0.25 seconds), supply ramp pos should be at 100 W and supply at 100, approx. + Assert.That(netBattery.CurrentSupply, Is.EqualTo(200).Within(tickDev)); + Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(100).Within(tickDev)); + Assert.That(consumer.ReceivedPower, Is.EqualTo(200).Within(tickDev)); + + // Trivial integral to calculate expected power spent. + const double spentExpected = (200 + 100) / 2.0 * 0.25; + Assert.That(battery.CurrentCharge, Is.EqualTo(startingCharge - spentExpected).Within(tickDev)); + }); }); // run for 0.75 seconds @@ -429,14 +462,17 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // After 1 second total, ramp should be at 400 and supply should be at 400, everybody happy. - Assert.That(netBattery.CurrentSupply, Is.EqualTo(400).Within(tickDev)); - Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(400).Within(tickDev)); - Assert.That(consumer.ReceivedPower, Is.EqualTo(400).Within(tickDev)); - - // Trivial integral to calculate expected power spent. - const double spentExpected = (400 + 100) / 2.0 * 0.75 + 400 * 0.25; - Assert.That(battery.CurrentCharge, Is.EqualTo(startingCharge - spentExpected).Within(tickDev)); + Assert.Multiple(() => + { + // After 1 second total, ramp should be at 400 and supply should be at 400, everybody happy. + Assert.That(netBattery.CurrentSupply, Is.EqualTo(400).Within(tickDev)); + Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(400).Within(tickDev)); + Assert.That(consumer.ReceivedPower, Is.EqualTo(400).Within(tickDev)); + + // Trivial integral to calculate expected power spent. + const double spentExpected = (400 + 100) / 2.0 * 0.75 + 400 * 0.25; + Assert.That(battery.CurrentCharge, Is.EqualTo(startingCharge - spentExpected).Within(tickDev)); + }); }); await pairTracker.CleanReturnAsync(); @@ -451,6 +487,7 @@ public async Task TestNoDemandRampdown() var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); + var batterySys = entityManager.System(); PowerSupplierComponent supplier = default!; PowerNetworkBatteryComponent netBattery = default!; BatteryComponent battery = default!; @@ -474,7 +511,7 @@ await server.WaitAssertion(() => var generatorEnt = entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates()); var consumerEnt = entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 1)); - var batteryEnt = entityManager.SpawnEntity("DischargingBatteryDummy", grid.ToCoordinates(0,2)); + var batteryEnt = entityManager.SpawnEntity("DischargingBatteryDummy", grid.ToCoordinates(0, 2)); netBattery = entityManager.GetComponent(batteryEnt); battery = entityManager.GetComponent(batteryEnt); supplier = entityManager.GetComponent(generatorEnt); @@ -482,13 +519,13 @@ await server.WaitAssertion(() => consumer.DrawRate = draw; - supplier.MaxSupply = draw/2; + supplier.MaxSupply = draw / 2; supplier.SupplyRampRate = rampRate; supplier.SupplyRampTolerance = rampTol; - battery.MaxCharge = 100_000; - battery.CurrentCharge = 100_000; - netBattery.MaxSupply = draw/2; + batterySys.SetMaxCharge(batteryEnt, 100_000, battery); + batterySys.SetCharge(batteryEnt, 100_000, battery); + netBattery.MaxSupply = draw / 2; netBattery.SupplyRampRate = rampRate; netBattery.SupplyRampTolerance = rampTol; }); @@ -497,20 +534,26 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(supplier.CurrentSupply, Is.EqualTo(rampTol).Within(0.1)); - Assert.That(netBattery.CurrentSupply, Is.EqualTo(rampTol).Within(0.1)); - Assert.That(consumer.ReceivedPower, Is.EqualTo(rampTol*2).Within(0.1)); + Assert.Multiple(() => + { + Assert.That(supplier.CurrentSupply, Is.EqualTo(rampTol).Within(0.1)); + Assert.That(netBattery.CurrentSupply, Is.EqualTo(rampTol).Within(0.1)); + Assert.That(consumer.ReceivedPower, Is.EqualTo(rampTol * 2).Within(0.1)); + }); }); server.RunTicks(60); await server.WaitAssertion(() => { - Assert.That(supplier.CurrentSupply, Is.EqualTo(draw/2).Within(0.1)); - Assert.That(supplier.SupplyRampPosition, Is.EqualTo(draw/2).Within(0.1)); - Assert.That(netBattery.CurrentSupply, Is.EqualTo(draw / 2).Within(0.1)); - Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(draw / 2).Within(0.1)); - Assert.That(consumer.ReceivedPower, Is.EqualTo(draw).Within(0.1)); + Assert.Multiple(() => + { + Assert.That(supplier.CurrentSupply, Is.EqualTo(draw / 2).Within(0.1)); + Assert.That(supplier.SupplyRampPosition, Is.EqualTo(draw / 2).Within(0.1)); + Assert.That(netBattery.CurrentSupply, Is.EqualTo(draw / 2).Within(0.1)); + Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(draw / 2).Within(0.1)); + Assert.That(consumer.ReceivedPower, Is.EqualTo(draw).Within(0.1)); + }); }); // now we disconnect the load; @@ -520,11 +563,14 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(supplier.CurrentSupply, Is.EqualTo(0).Within(0.1)); - Assert.That(supplier.SupplyRampPosition, Is.EqualTo(0).Within(0.1)); - Assert.That(netBattery.CurrentSupply, Is.EqualTo(0).Within(0.1)); - Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(0).Within(0.1)); - Assert.That(consumer.ReceivedPower, Is.EqualTo(0).Within(0.1)); + Assert.Multiple(() => + { + Assert.That(supplier.CurrentSupply, Is.EqualTo(0).Within(0.1)); + Assert.That(supplier.SupplyRampPosition, Is.EqualTo(0).Within(0.1)); + Assert.That(netBattery.CurrentSupply, Is.EqualTo(0).Within(0.1)); + Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(0).Within(0.1)); + Assert.That(consumer.ReceivedPower, Is.EqualTo(0).Within(0.1)); + }); }); await pairTracker.CleanReturnAsync(); @@ -533,11 +579,16 @@ await server.WaitAssertion(() => [Test] public async Task TestSimpleBatteryChargeDeficit() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var gameTiming = server.ResolveDependency(); var entityManager = server.ResolveDependency(); + var batterySys = entityManager.System(); PowerSupplierComponent supplier = default!; BatteryComponent battery = default!; @@ -562,8 +613,8 @@ await server.WaitAssertion(() => supplier.MaxSupply = 500; supplier.SupplyRampTolerance = 500; - battery.MaxCharge = 100000; - netBattery.MaxChargeRate = 1000; + batterySys.SetMaxCharge(batteryEnt, 100_000, battery); + netBattery.MaxChargeRate = 1_000; netBattery.Efficiency = 0.5f; }); @@ -573,10 +624,13 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // half a second @ 500 W = 250 - // 50% efficiency, so 125 J stored total. - Assert.That(battery.CurrentCharge, Is.EqualTo(125).Within(0.1)); - Assert.That(supplier.CurrentSupply, Is.EqualTo(500).Within(0.1)); + Assert.Multiple(() => + { + // half a second @ 500 W = 250 + // 50% efficiency, so 125 J stored total. + Assert.That(battery.CurrentCharge, Is.EqualTo(125).Within(0.1)); + Assert.That(supplier.CurrentSupply, Is.EqualTo(500).Within(0.1)); + }); }); await pairTracker.CleanReturnAsync(); @@ -585,11 +639,16 @@ await server.WaitAssertion(() => [Test] public async Task TestFullBattery() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); var gameTiming = server.ResolveDependency(); + var batterySys = entityManager.System(); PowerConsumerComponent consumer = default!; PowerSupplierComponent supplier = default!; PowerNetworkBatteryComponent netBattery = default!; @@ -627,8 +686,8 @@ await server.WaitAssertion(() => netBattery.MaxSupply = 400; netBattery.SupplyRampTolerance = 400; netBattery.SupplyRampRate = 100_000; - battery.MaxCharge = 100_000; - battery.CurrentCharge = 100_000; + batterySys.SetMaxCharge(batteryEnt, 100_000, battery); + batterySys.SetCharge(batteryEnt, 100_000, battery); }); // Run some ticks so everything is stable. @@ -640,16 +699,19 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(consumer.ReceivedPower, Is.EqualTo(consumer.DrawRate).Within(0.1)); - Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); + Assert.Multiple(() => + { + Assert.That(consumer.ReceivedPower, Is.EqualTo(consumer.DrawRate).Within(0.1)); + Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); - // Battery's current supply includes passed-through power from the supply. - // Assert ramp position is correct to make sure it's only supplying 200 W for real. - Assert.That(netBattery.CurrentSupply, Is.EqualTo(1000).Within(0.1)); - Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(200).Within(0.1)); + // Battery's current supply includes passed-through power from the supply. + // Assert ramp position is correct to make sure it's only supplying 200 W for real. + Assert.That(netBattery.CurrentSupply, Is.EqualTo(1000).Within(0.1)); + Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(200).Within(0.1)); - const int expectedSpent = 200; - Assert.That(battery.CurrentCharge, Is.EqualTo(battery.MaxCharge - expectedSpent).Within(tickDev)); + const int expectedSpent = 200; + Assert.That(battery.CurrentCharge, Is.EqualTo(battery.MaxCharge - expectedSpent).Within(tickDev)); + }); }); await pairTracker.CleanReturnAsync(); @@ -658,11 +720,16 @@ await server.WaitAssertion(() => [Test] public async Task TestFullBatteryEfficiencyPassThrough() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); var gameTiming = server.ResolveDependency(); + var batterySys = entityManager.System(); PowerConsumerComponent consumer = default!; PowerSupplierComponent supplier = default!; PowerNetworkBatteryComponent netBattery = default!; @@ -702,8 +769,8 @@ await server.WaitAssertion(() => netBattery.SupplyRampTolerance = 400; netBattery.SupplyRampRate = 100_000; netBattery.Efficiency = 0.5f; - battery.MaxCharge = 1_000_000; - battery.CurrentCharge = 1_000_000; + batterySys.SetMaxCharge(batteryEnt, 1_000_000, battery); + batterySys.SetCharge(batteryEnt, 1_000_000, battery); }); // Run some ticks so everything is stable. @@ -715,14 +782,17 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(consumer.ReceivedPower, Is.EqualTo(600).Within(0.1)); - Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); + Assert.Multiple(() => + { + Assert.That(consumer.ReceivedPower, Is.EqualTo(600).Within(0.1)); + Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); - Assert.That(netBattery.CurrentSupply, Is.EqualTo(600).Within(0.1)); - Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(400).Within(0.1)); + Assert.That(netBattery.CurrentSupply, Is.EqualTo(600).Within(0.1)); + Assert.That(netBattery.SupplyRampPosition, Is.EqualTo(400).Within(0.1)); - const int expectedSpent = 400; - Assert.That(battery.CurrentCharge, Is.EqualTo(battery.MaxCharge - expectedSpent).Within(tickDev)); + const int expectedSpent = 400; + Assert.That(battery.CurrentCharge, Is.EqualTo(battery.MaxCharge - expectedSpent).Within(tickDev)); + }); }); await pairTracker.CleanReturnAsync(); @@ -731,10 +801,15 @@ await server.WaitAssertion(() => [Test] public async Task TestFullBatteryEfficiencyDemandPassThrough() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); + var batterySys = entityManager.System(); PowerConsumerComponent consumer1 = default!; PowerConsumerComponent consumer2 = default!; PowerSupplierComponent supplier = default!; @@ -788,8 +863,8 @@ await server.WaitAssertion(() => supplier.MaxSupply = 1000; supplier.SupplyRampTolerance = 1000; - battery1.MaxCharge = 1_000_000; - battery2.MaxCharge = 1_000_000; + batterySys.SetMaxCharge(batteryEnt1, 1_000_000, battery1); + batterySys.SetMaxCharge(batteryEnt2, 1_000_000, battery2); netBattery1.MaxChargeRate = 1_000; netBattery2.MaxChargeRate = 1_000; @@ -808,9 +883,12 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(consumer1.ReceivedPower, Is.EqualTo(250).Within(0.1)); - Assert.That(consumer2.ReceivedPower, Is.EqualTo(500).Within(0.1)); - Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); + Assert.Multiple(() => + { + Assert.That(consumer1.ReceivedPower, Is.EqualTo(250).Within(0.1)); + Assert.That(consumer2.ReceivedPower, Is.EqualTo(500).Within(0.1)); + Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); + }); }); await pairTracker.CleanReturnAsync(); @@ -828,6 +906,7 @@ public async Task TestSupplyPrioritized() var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); var gameTiming = server.ResolveDependency(); + var batterySys = entityManager.System(); PowerConsumerComponent consumer = default!; PowerSupplierComponent supplier1 = default!; PowerSupplierComponent supplier2 = default!; @@ -887,10 +966,10 @@ await server.WaitAssertion(() => netBattery2.SupplyRampTolerance = 1000; netBattery1.SupplyRampRate = 100_000; netBattery2.SupplyRampRate = 100_000; - battery1.MaxCharge = 100_000; - battery2.MaxCharge = 100_000; - battery1.CurrentCharge = 100_000; - battery2.CurrentCharge = 100_000; + batterySys.SetMaxCharge(batteryEnt1, 100_000, battery1); + batterySys.SetMaxCharge(batteryEnt2, 100_000, battery2); + batterySys.SetCharge(batteryEnt1, 100_000, battery1); + batterySys.SetCharge(batteryEnt2, 100_000, battery2); }); // Run some ticks so everything is stable. @@ -898,14 +977,17 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(consumer.ReceivedPower, Is.EqualTo(consumer.DrawRate).Within(0.1)); - Assert.That(supplier1.CurrentSupply, Is.EqualTo(supplier1.MaxSupply).Within(0.1)); - Assert.That(supplier2.CurrentSupply, Is.EqualTo(supplier2.MaxSupply).Within(0.1)); - - Assert.That(netBattery1.CurrentSupply, Is.EqualTo(500).Within(0.1)); - Assert.That(netBattery2.CurrentSupply, Is.EqualTo(500).Within(0.1)); - Assert.That(netBattery2.SupplyRampPosition, Is.EqualTo(500).Within(0.1)); - Assert.That(netBattery2.SupplyRampPosition, Is.EqualTo(500).Within(0.1)); + Assert.Multiple(() => + { + Assert.That(consumer.ReceivedPower, Is.EqualTo(consumer.DrawRate).Within(0.1)); + Assert.That(supplier1.CurrentSupply, Is.EqualTo(supplier1.MaxSupply).Within(0.1)); + Assert.That(supplier2.CurrentSupply, Is.EqualTo(supplier2.MaxSupply).Within(0.1)); + + Assert.That(netBattery1.CurrentSupply, Is.EqualTo(500).Within(0.1)); + Assert.That(netBattery2.CurrentSupply, Is.EqualTo(500).Within(0.1)); + Assert.That(netBattery2.SupplyRampPosition, Is.EqualTo(500).Within(0.1)); + Assert.That(netBattery2.SupplyRampPosition, Is.EqualTo(500).Within(0.1)); + }); }); await pairTracker.CleanReturnAsync(); @@ -917,10 +999,15 @@ await server.WaitAssertion(() => [Test] public async Task TestBatteriesProportional() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); + var batterySys = entityManager.System(); PowerConsumerComponent consumer1 = default!; PowerConsumerComponent consumer2 = default!; PowerSupplierComponent supplier = default!; @@ -968,8 +1055,8 @@ await server.WaitAssertion(() => supplier.MaxSupply = 1000; supplier.SupplyRampTolerance = 1000; - battery1.MaxCharge = 1_000_000; - battery2.MaxCharge = 1_000_000; + batterySys.SetMaxCharge(batteryEnt1, 1_000_000, battery1); + batterySys.SetMaxCharge(batteryEnt2, 1_000_000, battery2); netBattery1.MaxChargeRate = 20; netBattery2.MaxChargeRate = 20; @@ -986,12 +1073,15 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // NOTE: MaxChargeRate on batteries actually skews the demand. - // So that's why the tolerance is so high, the charge rate is so *low*, - // and we run so many ticks to stabilize. - Assert.That(consumer1.ReceivedPower, Is.EqualTo(333.333).Within(10)); - Assert.That(consumer2.ReceivedPower, Is.EqualTo(666.666).Within(10)); - Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); + Assert.Multiple(() => + { + // NOTE: MaxChargeRate on batteries actually skews the demand. + // So that's why the tolerance is so high, the charge rate is so *low*, + // and we run so many ticks to stabilize. + Assert.That(consumer1.ReceivedPower, Is.EqualTo(333.333).Within(10)); + Assert.That(consumer2.ReceivedPower, Is.EqualTo(666.666).Within(10)); + Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.1)); + }); }); await pairTracker.CleanReturnAsync(); @@ -1000,10 +1090,15 @@ await server.WaitAssertion(() => [Test] public async Task TestBatteryEngineCut() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); + var batterySys = entityManager.System(); PowerConsumerComponent consumer = default!; PowerSupplierComponent supplier = default!; PowerNetworkBatteryComponent netBattery = default!; @@ -1039,8 +1134,8 @@ await server.WaitPost(() => netBattery.MaxSupply = 1000; netBattery.SupplyRampTolerance = 200; netBattery.SupplyRampRate = 10; - battery.MaxCharge = 100_000; - battery.CurrentCharge = 100_000; + batterySys.SetMaxCharge(batteryEnt, 100_000, battery); + batterySys.SetCharge(batteryEnt, 100_000, battery); }); // Run some ticks so everything is stable. @@ -1048,9 +1143,12 @@ await server.WaitPost(() => await server.WaitAssertion(() => { - // Supply and consumer are fully loaded/supplied. - Assert.That(consumer.ReceivedPower, Is.EqualTo(consumer.DrawRate).Within(0.5)); - Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.5)); + Assert.Multiple(() => + { + // Supply and consumer are fully loaded/supplied. + Assert.That(consumer.ReceivedPower, Is.EqualTo(consumer.DrawRate).Within(0.5)); + Assert.That(supplier.CurrentSupply, Is.EqualTo(supplier.MaxSupply).Within(0.5)); + }); // Cut off the supplier supplier.Enabled = false; @@ -1062,10 +1160,13 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - // Assert that network drops to 0 power and starts ramping up - Assert.That(consumer.ReceivedPower, Is.LessThan(50).And.GreaterThan(0)); - Assert.That(netBattery.CurrentReceiving, Is.EqualTo(0)); - Assert.That(netBattery.CurrentSupply, Is.GreaterThan(0)); + Assert.Multiple(() => + { + // Assert that network drops to 0 power and starts ramping up + Assert.That(consumer.ReceivedPower, Is.LessThan(50).And.GreaterThan(0)); + Assert.That(netBattery.CurrentReceiving, Is.EqualTo(0)); + Assert.That(netBattery.CurrentSupply, Is.GreaterThan(0)); + }); }); await pairTracker.CleanReturnAsync(); @@ -1077,11 +1178,15 @@ await server.WaitAssertion(() => [Test] public async Task TestTerminalNodeGroups() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); - var _nodeContainer = entityManager.System(); + var nodeContainer = entityManager.System(); CableNode leftNode = default!; CableNode rightNode = default!; Node batteryInput = default!; @@ -1109,16 +1214,16 @@ await server.WaitAssertion(() => var battery = entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 2)); var batteryNodeContainer = entityManager.GetComponent(battery); - if (_nodeContainer.TryGetNode(entityManager.GetComponent(leftEnt), + if (nodeContainer.TryGetNode(entityManager.GetComponent(leftEnt), "power", out var leftN)) leftNode = leftN; - if (_nodeContainer.TryGetNode(entityManager.GetComponent(rightEnt), + if (nodeContainer.TryGetNode(entityManager.GetComponent(rightEnt), "power", out var rightN)) rightNode = rightN; - if (_nodeContainer.TryGetNode(batteryNodeContainer, "input", out var nInput)) + if (nodeContainer.TryGetNode(batteryNodeContainer, "input", out var nInput)) batteryInput = nInput; - if (_nodeContainer.TryGetNode(batteryNodeContainer, "output", out var nOutput)) + if (nodeContainer.TryGetNode(batteryNodeContainer, "output", out var nOutput)) batteryOutput = nOutput; }); @@ -1127,10 +1232,13 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(batteryInput.NodeGroup, Is.EqualTo(leftNode.NodeGroup)); - Assert.That(batteryOutput.NodeGroup, Is.EqualTo(rightNode.NodeGroup)); + Assert.Multiple(() => + { + Assert.That(batteryInput.NodeGroup, Is.EqualTo(leftNode.NodeGroup)); + Assert.That(batteryOutput.NodeGroup, Is.EqualTo(rightNode.NodeGroup)); - Assert.That(leftNode.NodeGroup, Is.Not.EqualTo(rightNode.NodeGroup)); + Assert.That(leftNode.NodeGroup, Is.Not.EqualTo(rightNode.NodeGroup)); + }); }); await pairTracker.CleanReturnAsync(); @@ -1139,10 +1247,15 @@ await server.WaitAssertion(() => [Test] public async Task ApcChargingTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); + var batterySys = entityManager.System(); PowerNetworkBatteryComponent substationNetBattery = default!; BatteryComponent apcBattery = default!; @@ -1173,15 +1286,18 @@ await server.WaitAssertion(() => generatorSupplier.MaxSupply = 1000; generatorSupplier.SupplyRampTolerance = 1000; - apcBattery.CurrentCharge = 0; + batterySys.SetCharge(apcEnt, 0, apcBattery); }); server.RunTicks(5); //let run a few ticks for PowerNets to reevaluate and start charging apc await server.WaitAssertion(() => { - Assert.That(substationNetBattery.CurrentSupply, Is.GreaterThan(0)); //substation should be providing power - Assert.That(apcBattery.CurrentCharge, Is.GreaterThan(0)); //apc battery should have gained charge + Assert.Multiple(() => + { + Assert.That(substationNetBattery.CurrentSupply, Is.GreaterThan(0)); //substation should be providing power + Assert.That(apcBattery.CurrentCharge, Is.GreaterThan(0)); //apc battery should have gained charge + }); }); await pairTracker.CleanReturnAsync(); @@ -1190,11 +1306,16 @@ await server.WaitAssertion(() => [Test] public async Task ApcNetTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); - var extensionCableSystem = entityManager.EntitySysManager.GetEntitySystem(); + var batterySys = entityManager.System(); + var extensionCableSystem = entityManager.System(); PowerNetworkBatteryComponent apcNetBattery = default!; ApcPowerReceiverComponent receiver = default!; ApcPowerReceiverComponent unpoweredReceiver = default!; @@ -1229,15 +1350,16 @@ await server.WaitAssertion(() => extensionCableSystem.SetProviderTransferRange(apcExtensionEnt, range); extensionCableSystem.SetReceiverReceptionRange(powerReceiverEnt, range); - battery.MaxCharge = 10000; //arbitrary nonzero amount of charge - battery.CurrentCharge = battery.MaxCharge; //fill battery + batterySys.SetMaxCharge(apcEnt, 10000, battery); //arbitrary nonzero amount of charge + batterySys.SetCharge(apcEnt, battery.MaxCharge, battery); //fill battery receiver.Load = 1; //arbitrary small amount of power }); server.RunTicks(1); //let run a tick for ApcNet to process power - await server.WaitAssertion(() => { + await server.WaitAssertion(() => + { Assert.Multiple(() => { Assert.That(receiver.Powered, "Receiver in range should be powered"); diff --git a/Content.IntegrationTests/Tests/Procedural/DungeonTests.cs b/Content.IntegrationTests/Tests/Procedural/DungeonTests.cs index 9f3694e1dfe..6566126bd38 100644 --- a/Content.IntegrationTests/Tests/Procedural/DungeonTests.cs +++ b/Content.IntegrationTests/Tests/Procedural/DungeonTests.cs @@ -1,8 +1,6 @@ using System.Collections.Generic; -using System.Threading.Tasks; using Content.Server.Procedural; using Content.Shared.Procedural; -using NUnit.Framework; using Robust.Shared.Maths; using Robust.Shared.Prototypes; @@ -14,7 +12,7 @@ public sealed class DungeonTests [Test] public async Task TestDungeonRoomPackBounds() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var protoManager = pairTracker.Pair.Server.ResolveDependency(); await pairTracker.Pair.Server.WaitAssertion(() => @@ -64,7 +62,7 @@ await pairTracker.Pair.Server.WaitAssertion(() => [Test] public async Task TestDungeonPresets() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var protoManager = pairTracker.Pair.Server.ResolveDependency(); await pairTracker.Pair.Server.WaitAssertion(() => @@ -86,9 +84,11 @@ await pairTracker.Pair.Server.WaitAssertion(() => // Assert that anything exists at this size var rotated = new Vector2i(pack.Size.Y, pack.Size.X); - Assert.That(sizes.Contains(pack.Size) || sizes.Contains(rotated), $"Didn't find any dungeon room prototypes for {pack.Size} for {preset.ID} index {i}"); - - Assert.That(pack.Bottom, Is.GreaterThanOrEqualTo(0), "All dungeon room packs need their y-axis to be above 0!"); + Assert.Multiple(() => + { + Assert.That(sizes.Contains(pack.Size) || sizes.Contains(rotated), $"Didn't find any dungeon room prototypes for {pack.Size} for {preset.ID} index {i}"); + Assert.That(pack.Bottom, Is.GreaterThanOrEqualTo(0), "All dungeon room packs need their y-axis to be above 0!"); + }); } } }); diff --git a/Content.IntegrationTests/Tests/PrototypeSaveTest.cs b/Content.IntegrationTests/Tests/PrototypeSaveTest.cs index cf87ae84f54..5b87c6f36c4 100644 --- a/Content.IntegrationTests/Tests/PrototypeSaveTest.cs +++ b/Content.IntegrationTests/Tests/PrototypeSaveTest.cs @@ -1,11 +1,7 @@ #nullable enable -using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Content.Shared.Coordinates; -using Content.Shared.Sound.Components; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -19,7 +15,6 @@ using Robust.Shared.Serialization.Markdown.Validation; using Robust.Shared.Serialization.Markdown.Value; using Robust.Shared.Serialization.TypeSerializers.Interfaces; -using Robust.Shared.Timing; namespace Content.IntegrationTests.Tests; @@ -181,7 +176,7 @@ await server.WaitAssertion(() => // An entity may also remove components on init -> check no components are missing. foreach (var (compType, comp) in prototype.Components) { - Assert.That(compNames.Contains(compType), $"Prototype {prototype.ID} removes component {compType} on spawn."); + Assert.That(compNames, Does.Contain(compType), $"Prototype {prototype.ID} removes component {compType} on spawn."); } if (!entityMan.Deleted(uid)) diff --git a/Content.IntegrationTests/Tests/ResearchTest.cs b/Content.IntegrationTests/Tests/ResearchTest.cs index e38698ebaa3..7e7be713cef 100644 --- a/Content.IntegrationTests/Tests/ResearchTest.cs +++ b/Content.IntegrationTests/Tests/ResearchTest.cs @@ -1,9 +1,7 @@ using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Content.Shared.Lathe; using Content.Shared.Research.Prototypes; -using NUnit.Framework; using Robust.Shared.Prototypes; namespace Content.IntegrationTests.Tests; @@ -14,7 +12,7 @@ public sealed class ResearchTest [Test] public async Task DisciplineValidTierPrerequesitesTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings {NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoManager = server.ResolveDependency(); @@ -23,23 +21,25 @@ await server.WaitAssertion(() => { var allTechs = protoManager.EnumeratePrototypes().ToList(); - foreach (var discipline in protoManager.EnumeratePrototypes()) + Assert.Multiple(() => { - foreach (var tech in allTechs) + foreach (var discipline in protoManager.EnumeratePrototypes()) { - if (tech.Discipline != discipline.ID) - continue; - - // we ignore these, anyways - if (tech.Tier == 1) - continue; - - Assert.That(tech.Tier, Is.GreaterThan(0), $"Technology {tech} has invalid tier {tech.Tier}."); - - Assert.That(discipline.TierPrerequisites.ContainsKey(tech.Tier), - $"Discipline {discipline.ID} does not have a TierPrerequisites definition for tier {tech.Tier}"); + foreach (var tech in allTechs) + { + if (tech.Discipline != discipline.ID) + continue; + + // we ignore these, anyways + if (tech.Tier == 1) + continue; + + Assert.That(tech.Tier, Is.GreaterThan(0), $"Technology {tech} has invalid tier {tech.Tier}."); + Assert.That(discipline.TierPrerequisites.ContainsKey(tech.Tier), + $"Discipline {discipline.ID} does not have a TierPrerequisites definition for tier {tech.Tier}"); + } } - } + }); }); await pairTracker.CleanReturnAsync(); @@ -48,7 +48,7 @@ await server.WaitAssertion(() => [Test] public async Task AllTechPrintableTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings {NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoManager = server.ResolveDependency(); @@ -79,13 +79,16 @@ await server.WaitAssertion(() => } } - foreach (var tech in protoManager.EnumeratePrototypes()) + Assert.Multiple(() => { - foreach (var recipe in tech.RecipeUnlocks) + foreach (var tech in protoManager.EnumeratePrototypes()) { - Assert.That(latheTechs, Does.Contain(recipe), $"Recipe \"{recipe}\" cannot be unlocked on any lathes."); + foreach (var recipe in tech.RecipeUnlocks) + { + Assert.That(latheTechs, Does.Contain(recipe), $"Recipe \"{recipe}\" cannot be unlocked on any lathes."); + } } - } + }); }); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/ResettingEntitySystemTests.cs b/Content.IntegrationTests/Tests/ResettingEntitySystemTests.cs index 6da5acf549d..c12a6ee861b 100644 --- a/Content.IntegrationTests/Tests/ResettingEntitySystemTests.cs +++ b/Content.IntegrationTests/Tests/ResettingEntitySystemTests.cs @@ -1,9 +1,6 @@ -using System.Threading.Tasks; -using Content.Server.GameTicking; +using Content.Server.GameTicking; using Content.Shared.GameTicking; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; using Robust.Shared.Reflection; namespace Content.IntegrationTests.Tests @@ -33,7 +30,7 @@ public void Reset(RoundRestartCleanupEvent ev) [Test] public async Task ResettingEntitySystemResetTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var entitySystemManager = server.ResolveDependency(); @@ -47,11 +44,11 @@ await server.WaitAssertion(() => system.HasBeenReset = false; - Assert.False(system.HasBeenReset); + Assert.That(system.HasBeenReset, Is.False); gameTicker.RestartRound(); - Assert.True(system.HasBeenReset); + Assert.That(system.HasBeenReset); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/RestartRoundTest.cs b/Content.IntegrationTests/Tests/RestartRoundTest.cs index f54bd74e223..454e94cc395 100644 --- a/Content.IntegrationTests/Tests/RestartRoundTest.cs +++ b/Content.IntegrationTests/Tests/RestartRoundTest.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; using Content.Server.GameTicking; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.IoC; diff --git a/Content.IntegrationTests/Tests/RoundEndTest.cs b/Content.IntegrationTests/Tests/RoundEndTest.cs index 2b8143038a1..4232a635e7a 100644 --- a/Content.IntegrationTests/Tests/RoundEndTest.cs +++ b/Content.IntegrationTests/Tests/RoundEndTest.cs @@ -1,14 +1,9 @@ -using System; using System.Threading; -using System.Threading.Tasks; using Content.Server.GameTicking; using Content.Server.RoundEnd; using Content.Shared.CCVar; -using NUnit.Framework; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Network; namespace Content.IntegrationTests.Tests { @@ -44,14 +39,18 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { var bus = entManager.EventBus; - bus.SubscribeEvent(EventSource.Local, this, _ => { + bus.SubscribeEvent(EventSource.Local, this, _ => + { Interlocked.Increment(ref eventCount); }); // Press the shuttle call button roundEndSystem.RequestRoundEnd(); - Assert.That(roundEndSystem.ExpectedCountdownEnd, Is.Not.Null, "Shuttle was called, but countdown time was not set"); - Assert.That(roundEndSystem.CanCallOrRecall(), Is.False, "Started the shuttle, but didn't have to wait cooldown to press cancel button"); + Assert.Multiple(() => + { + Assert.That(roundEndSystem.ExpectedCountdownEnd, Is.Not.Null, "Shuttle was called, but countdown time was not set"); + Assert.That(roundEndSystem.CanCallOrRecall(), Is.False, "Started the shuttle, but didn't have to wait cooldown to press cancel button"); + }); // Check that we can't recall the shuttle yet roundEndSystem.CancelRoundEndCountdown(); Assert.That(roundEndSystem.ExpectedCountdownEnd, Is.Not.Null, "Shuttle was cancelled, even though the button was on cooldown"); @@ -61,12 +60,18 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(roundEndSystem.CanCallOrRecall(), Is.True, "We waited a while, but the cooldown is not expired"); - Assert.That(roundEndSystem.ExpectedCountdownEnd, Is.Not.Null, "We were waiting for the cooldown, but the round also ended"); + Assert.Multiple(() => + { + Assert.That(roundEndSystem.CanCallOrRecall(), Is.True, "We waited a while, but the cooldown is not expired"); + Assert.That(roundEndSystem.ExpectedCountdownEnd, Is.Not.Null, "We were waiting for the cooldown, but the round also ended"); + }); // Recall the shuttle, which should trigger the cooldown again roundEndSystem.CancelRoundEndCountdown(); - Assert.That(roundEndSystem.ExpectedCountdownEnd, Is.Null, "Recalled shuttle, but countdown has not ended"); - Assert.That(roundEndSystem.CanCallOrRecall(), Is.False, "Recalled shuttle, but cooldown has not been enabled"); + Assert.Multiple(() => + { + Assert.That(roundEndSystem.ExpectedCountdownEnd, Is.Null, "Recalled shuttle, but countdown has not ended"); + Assert.That(roundEndSystem.CanCallOrRecall(), Is.False, "Recalled shuttle, but cooldown has not been enabled"); + }); }); await WaitForEvent(); // Wait for Cooldown @@ -82,8 +87,11 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.That(roundEndSystem.CanCallOrRecall(), Is.True, "We waited a while, but the cooldown is not expired"); - Assert.That(roundEndSystem.ExpectedCountdownEnd, Is.Not.Null, "The countdown ended, but we just wanted the cooldown to end"); + Assert.Multiple(() => + { + Assert.That(roundEndSystem.CanCallOrRecall(), Is.True, "We waited a while, but the cooldown is not expired"); + Assert.That(roundEndSystem.ExpectedCountdownEnd, Is.Not.Null, "The countdown ended, but we just wanted the cooldown to end"); + }); }); await WaitForEvent(); // Wait for countdown to end round diff --git a/Content.IntegrationTests/Tests/SaveLoadMapTest.cs b/Content.IntegrationTests/Tests/SaveLoadMapTest.cs index 07d335eb673..e6af36e36a7 100644 --- a/Content.IntegrationTests/Tests/SaveLoadMapTest.cs +++ b/Content.IntegrationTests/Tests/SaveLoadMapTest.cs @@ -1,12 +1,8 @@ -using System.Threading.Tasks; using Content.Shared.CCVar; -using NUnit.Framework; using Robust.Server.GameObjects; -using Robust.Server.Maps; using Robust.Shared.Configuration; using Robust.Shared.ContentPack; using Robust.Shared.GameObjects; -using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Utility; @@ -14,14 +10,14 @@ namespace Content.IntegrationTests.Tests { [TestFixture] - sealed class SaveLoadMapTest + public sealed class SaveLoadMapTest { [Test] public async Task SaveLoadMultiGridMap() { const string mapPath = @"/Maps/Test/TestMap.yml"; - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var mapManager = server.ResolveDependency(); var sEntities = server.ResolveDependency(); @@ -42,13 +38,13 @@ await server.WaitAssertion(() => var mapGrid = mapManager.CreateGrid(mapId); var mapGridEnt = mapGrid.Owner; xformSystem.SetWorldPosition(mapGridEnt, new Vector2(10, 10)); - mapGrid.SetTile(new Vector2i(0,0), new Tile(1, (TileRenderFlag)1, 255)); + mapGrid.SetTile(new Vector2i(0, 0), new Tile(1, (TileRenderFlag) 1, 255)); } { var mapGrid = mapManager.CreateGrid(mapId); var mapGridEnt = mapGrid.Owner; xformSystem.SetWorldPosition(mapGridEnt, new Vector2(-8, -8)); - mapGrid.SetTile(new Vector2i(0, 0), new Tile(2, (TileRenderFlag)1, 254)); + mapGrid.SetTile(new Vector2i(0, 0), new Tile(2, (TileRenderFlag) 1, 254)); } Assert.Multiple(() => mapLoader.SaveMap(mapId, mapPath)); @@ -59,8 +55,7 @@ await server.WaitAssertion(() => await server.WaitAssertion(() => { - Assert.Multiple(() => mapLoader.LoadMap(new MapId(10), mapPath)); - + Assert.That(mapLoader.TryLoad(new MapId(10), mapPath, out _)); }); await server.WaitIdleAsync(); @@ -75,9 +70,11 @@ await server.WaitAssertion(() => return; } - Assert.That(xformSystem.GetWorldPosition(gridXform), Is.EqualTo(new Vector2(10, 10))); - - Assert.That(mapGrid.GetTileRef(new Vector2i(0, 0)).Tile, Is.EqualTo(new Tile(1, (TileRenderFlag)1, 255))); + Assert.Multiple(() => + { + Assert.That(xformSystem.GetWorldPosition(gridXform), Is.EqualTo(new Vector2(10, 10))); + Assert.That(mapGrid.GetTileRef(new Vector2i(0, 0)).Tile, Is.EqualTo(new Tile(1, (TileRenderFlag) 1, 255))); + }); } { if (!mapManager.TryFindGridAt(new MapId(10), new Vector2(-8, -8), out var gridUid, out var mapGrid) || @@ -87,8 +84,11 @@ await server.WaitAssertion(() => return; } - Assert.That(xformSystem.GetWorldPosition(gridXform), Is.EqualTo(new Vector2(-8, -8))); - Assert.That(mapGrid.GetTileRef(new Vector2i(0, 0)).Tile, Is.EqualTo(new Tile(2, (TileRenderFlag)1, 254))); + Assert.Multiple(() => + { + Assert.That(xformSystem.GetWorldPosition(gridXform), Is.EqualTo(new Vector2(-8, -8))); + Assert.That(mapGrid.GetTileRef(new Vector2i(0, 0)).Tile, Is.EqualTo(new Tile(2, (TileRenderFlag) 1, 254))); + }); } }); diff --git a/Content.IntegrationTests/Tests/SaveLoadSaveTest.cs b/Content.IntegrationTests/Tests/SaveLoadSaveTest.cs index eeb35f6a685..f032e432e4e 100644 --- a/Content.IntegrationTests/Tests/SaveLoadSaveTest.cs +++ b/Content.IntegrationTests/Tests/SaveLoadSaveTest.cs @@ -1,15 +1,13 @@ using System.IO; using System.Linq; -using System.Threading.Tasks; using Content.Shared.CCVar; -using NUnit.Framework; using Robust.Server.GameObjects; using Robust.Server.Maps; using Robust.Shared.Configuration; using Robust.Shared.ContentPack; using Robust.Shared.GameObjects; -using Robust.Shared.Log; using Robust.Shared.Map; +using Robust.Shared.Map.Components; using Robust.Shared.Utility; namespace Content.IntegrationTests.Tests @@ -23,9 +21,10 @@ public sealed class SaveLoadSaveTest [Test] public async Task SaveLoadSave() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings {Fresh = true, Disconnected = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { Fresh = true, Disconnected = true }); var server = pairTracker.Pair.Server; - var mapLoader = server.ResolveDependency().GetEntitySystem(); + var entManager = server.ResolveDependency(); + var mapLoader = entManager.System(); var mapManager = server.ResolveDependency(); var cfg = server.ResolveDependency(); Assert.That(cfg.GetCVar(CCVars.GridFill), Is.False); @@ -37,8 +36,15 @@ await server.WaitPost(() => var grid0 = mapManager.CreateGrid(mapId0); mapLoader.Save(grid0.Owner, "save load save 1.yml"); var mapId1 = mapManager.CreateMap(); - var grid1 = mapLoader.LoadGrid(mapId1, "save load save 1.yml", new MapLoadOptions() {LoadMap = false}); - mapLoader.Save(grid1!.Value, "save load save 2.yml"); + EntityUid grid1 = default!; +#pragma warning disable NUnit2045 + Assert.That(mapLoader.TryLoad(mapId1, "save load save 1.yml", out var roots, new MapLoadOptions() { LoadMap = false }), $"Failed to load test map {TestMap}"); + Assert.DoesNotThrow(() => + { + grid1 = roots.First(uid => entManager.HasComponent(uid)); + }); +#pragma warning restore NUnit2045 + mapLoader.Save(grid1, "save load save 2.yml"); }); await server.WaitIdleAsync(); @@ -61,7 +67,8 @@ await server.WaitPost(() => two = await reader.ReadToEndAsync(); } - Assert.Multiple(() => { + Assert.Multiple(() => + { Assert.That(two, Is.EqualTo(one)); var failed = TestContext.CurrentContext.Result.Assertions.FirstOrDefault(); if (failed != null) @@ -82,7 +89,7 @@ await server.WaitPost(() => await pairTracker.CleanReturnAsync(); } - const string TestMap = "Maps/bagel.yml"; + private const string TestMap = "Maps/bagel.yml"; /// /// Loads the default map, runs it for 5 ticks, then assert that it did not change. @@ -90,7 +97,7 @@ await server.WaitPost(() => [Test] public async Task LoadSaveTicksSaveBagel() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var mapLoader = server.ResolveDependency().GetEntitySystem(); var mapManager = server.ResolveDependency(); @@ -105,7 +112,7 @@ public async Task LoadSaveTicksSaveBagel() mapId = mapManager.CreateMap(); mapManager.AddUninitializedMap(mapId); mapManager.SetMapPaused(mapId, true); - mapLoader.LoadMap(mapId, TestMap); + Assert.That(mapLoader.TryLoad(mapId, TestMap, out _), $"Failed to load test map {TestMap}"); mapLoader.SaveMap(mapId, "load save ticks save 1.yml"); }); @@ -135,7 +142,8 @@ await server.WaitPost(() => two = await reader.ReadToEndAsync(); } - Assert.Multiple(() => { + Assert.Multiple(() => + { Assert.That(two, Is.EqualTo(one)); var failed = TestContext.CurrentContext.Result.Assertions.FirstOrDefault(); if (failed != null) @@ -171,7 +179,7 @@ await server.WaitPost(() => [Test] public async Task LoadTickLoadBagel() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var mapLoader = server.ResolveDependency().GetEntitySystem(); @@ -192,7 +200,7 @@ public async Task LoadTickLoadBagel() mapId = mapManager.CreateMap(); mapManager.AddUninitializedMap(mapId); mapManager.SetMapPaused(mapId, true); - mapLoader.LoadMap(mapId, TestMap); + Assert.That(mapLoader.TryLoad(mapId, TestMap, out _), $"Failed to load test map {TestMap}"); mapLoader.SaveMap(mapId, fileA); }); @@ -212,7 +220,7 @@ public async Task LoadTickLoadBagel() mapManager.CreateMap(mapId); mapManager.AddUninitializedMap(mapId); mapManager.SetMapPaused(mapId, true); - mapLoader.LoadMap(mapId, TestMap); + Assert.That(mapLoader.TryLoad(mapId, TestMap, out _), $"Failed to load test map {TestMap}"); mapLoader.SaveMap(mapId, fileB); }); diff --git a/Content.IntegrationTests/Tests/Shuttle/DockTest.cs b/Content.IntegrationTests/Tests/Shuttle/DockTest.cs index e4fcb097469..7ee4aa5271d 100644 --- a/Content.IntegrationTests/Tests/Shuttle/DockTest.cs +++ b/Content.IntegrationTests/Tests/Shuttle/DockTest.cs @@ -1,9 +1,6 @@ -using System; using System.Collections.Generic; -using System.Threading.Tasks; using Content.Server.Shuttles.Systems; using Content.Tests; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -12,7 +9,7 @@ namespace Content.IntegrationTests.Tests.Shuttle; public sealed class DockTest : ContentUnitTest { - static IEnumerable TestSource() + private static IEnumerable TestSource() { // I-shape for grid1, T-shape for grid2 yield return new object[] { new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Angle.Zero, Angle.Zero, true }; @@ -31,6 +28,7 @@ public async Task TestDockingConfig(Vector2 dock1Pos, Vector2 dock2Pos, Angle do var entManager = server.ResolveDependency(); var mapManager = server.ResolveDependency(); var dockingSystem = entManager.System(); + var xformSystem = entManager.System(); var mapId = map.MapId; @@ -39,8 +37,10 @@ await server.WaitAssertion(() => entManager.DeleteEntity(map.GridUid); var grid1 = mapManager.CreateGrid(mapId); var grid2 = mapManager.CreateGrid(mapId); + var grid1Ent = grid1.Owner; + var grid2Ent = grid2.Owner; var grid2Offset = new Vector2(50f, 50f); - entManager.GetComponent(grid2.Owner).LocalPosition = grid2Offset; + xformSystem.SetLocalPosition(grid2Ent, grid2Offset); // Tetris tests // Grid1 is a vertical I @@ -54,7 +54,7 @@ await server.WaitAssertion(() => }; grid1.SetTiles(tiles1); - var dock1 = entManager.SpawnEntity("AirlockShuttle", new EntityCoordinates(grid1.Owner, dock1Pos)); + var dock1 = entManager.SpawnEntity("AirlockShuttle", new EntityCoordinates(grid1Ent, dock1Pos)); var dock1Xform = entManager.GetComponent(dock1); dock1Xform.LocalRotation = dock1Angle; @@ -68,11 +68,11 @@ await server.WaitAssertion(() => }; grid2.SetTiles(tiles2); - var dock2 = entManager.SpawnEntity("AirlockShuttle", new EntityCoordinates(grid2.Owner, dock2Pos)); + var dock2 = entManager.SpawnEntity("AirlockShuttle", new EntityCoordinates(grid2Ent, dock2Pos)); var dock2Xform = entManager.GetComponent(dock2); dock2Xform.LocalRotation = dock2Angle; - var config = dockingSystem.GetDockingConfig(grid1.Owner, grid2.Owner); + var config = dockingSystem.GetDockingConfig(grid1Ent, grid2Ent); Assert.That(result, Is.EqualTo(config != null)); }); diff --git a/Content.IntegrationTests/Tests/ShuttleTest.cs b/Content.IntegrationTests/Tests/ShuttleTest.cs index d999b596d66..08dc30bb33f 100644 --- a/Content.IntegrationTests/Tests/ShuttleTest.cs +++ b/Content.IntegrationTests/Tests/ShuttleTest.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; using Content.Server.Shuttles.Components; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -16,7 +14,7 @@ public sealed class ShuttleTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); @@ -25,6 +23,7 @@ public async Task Test() var physicsSystem = entManager.System(); EntityUid gridEnt = default; + PhysicsComponent gridPhys = null; await server.WaitAssertion(() => { @@ -32,11 +31,17 @@ await server.WaitAssertion(() => var grid = mapMan.CreateGrid(mapId); gridEnt = grid.Owner; - Assert.That(entManager.HasComponent(gridEnt)); - Assert.That(entManager.TryGetComponent(gridEnt, out var physicsComponent)); - Assert.That(physicsComponent!.BodyType, Is.EqualTo(BodyType.Dynamic)); - Assert.That(entManager.GetComponent(gridEnt).LocalPosition, Is.EqualTo(Vector2.Zero)); - physicsSystem.ApplyLinearImpulse(gridEnt, Vector2.One, body: physicsComponent); + Assert.Multiple(() => + { + Assert.That(entManager.HasComponent(gridEnt)); + Assert.That(entManager.TryGetComponent(gridEnt, out gridPhys)); + }); + Assert.Multiple(() => + { + Assert.That(gridPhys.BodyType, Is.EqualTo(BodyType.Dynamic)); + Assert.That(entManager.GetComponent(gridEnt).LocalPosition, Is.EqualTo(Vector2.Zero)); + }); + physicsSystem.ApplyLinearImpulse(gridEnt, Vector2.One, body: gridPhys); }); await server.WaitRunTicks(1); diff --git a/Content.IntegrationTests/Tests/Slipping/SlippingTest.cs b/Content.IntegrationTests/Tests/Slipping/SlippingTest.cs index 3e3196cd97e..53ae1e63b48 100644 --- a/Content.IntegrationTests/Tests/Slipping/SlippingTest.cs +++ b/Content.IntegrationTests/Tests/Slipping/SlippingTest.cs @@ -1,10 +1,8 @@ #nullable enable using System.Collections.Generic; -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Shared.Slippery; using Content.Shared.Stunnable; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Input; using Robust.Shared.Maths; @@ -34,20 +32,24 @@ public async Task BananaSlipTest() await SpawnTarget("TrashBananaPeel"); // Player is to the left of the banana peel and has not slipped. +#pragma warning disable NUnit2045 Assert.That(Delta(), Is.GreaterThan(0.5f)); - Assert.That(sys.Slipped.Contains(Player), Is.False); + Assert.That(sys.Slipped, Does.Not.Contain(Player)); +#pragma warning restore NUnit2045 // Walking over the banana slowly does not trigger a slip. await SetKey(EngineKeyFunctions.Walk, BoundKeyState.Down); await Move(DirectionFlag.East, 1f); +#pragma warning disable NUnit2045 Assert.That(Delta(), Is.LessThan(0.5f)); - Assert.That(sys.Slipped.Contains(Player), Is.False); + Assert.That(sys.Slipped, Does.Not.Contain(Player)); +#pragma warning restore NUnit2045 AssertComp(false, Player); // Moving at normal speeds does trigger a slip. await SetKey(EngineKeyFunctions.Walk, BoundKeyState.Up); await Move(DirectionFlag.West, 1f); - Assert.That(sys.Slipped.Contains(Player), Is.True); + Assert.That(sys.Slipped, Does.Contain(Player)); AssertComp(true, Player); } } diff --git a/Content.IntegrationTests/Tests/StackTest.cs b/Content.IntegrationTests/Tests/StackTest.cs index 5cab75b292d..12cea312bdf 100644 --- a/Content.IntegrationTests/Tests/StackTest.cs +++ b/Content.IntegrationTests/Tests/StackTest.cs @@ -1,8 +1,5 @@ -using System.Threading.Tasks; -using Content.Server.Storage.Components; using Content.Shared.Item; using Content.Shared.Stacks; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Prototypes; @@ -14,7 +11,7 @@ public sealed class StackTest [Test] public async Task StackCorrectItemSize() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoManager = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/StartTest.cs b/Content.IntegrationTests/Tests/StartTest.cs index 7b02bd22db8..f0f8bb1880d 100644 --- a/Content.IntegrationTests/Tests/StartTest.cs +++ b/Content.IntegrationTests/Tests/StartTest.cs @@ -1,5 +1,3 @@ -using System.Threading.Tasks; -using NUnit.Framework; using Robust.Shared.Exceptions; namespace Content.IntegrationTests.Tests @@ -13,7 +11,7 @@ public sealed class StartTest [Test] public async Task TestClientStart() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{Disconnected = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { Disconnected = true }); var client = pairTracker.Pair.Client; Assert.That(client.IsAlive); await client.WaitRunTicks(5); diff --git a/Content.IntegrationTests/Tests/Station/StationJobsTest.cs b/Content.IntegrationTests/Tests/Station/StationJobsTest.cs index 675a6409455..a552384302c 100644 --- a/Content.IntegrationTests/Tests/Station/StationJobsTest.cs +++ b/Content.IntegrationTests/Tests/Station/StationJobsTest.cs @@ -1,13 +1,10 @@ -using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Content.Server.Maps; using Content.Server.Station.Components; using Content.Server.Station.Systems; using Content.Shared.Preferences; using Content.Shared.Roles; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Log; using Robust.Shared.Map; @@ -76,7 +73,11 @@ public sealed class StationJobsTest [Test] public async Task AssignJobsTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var prototypeManager = server.ResolveDependency(); @@ -84,6 +85,7 @@ public async Task AssignJobsTest() var entSysMan = server.ResolveDependency().EntitySysManager; var stationJobs = entSysMan.GetEntitySystem(); var stationSystem = entSysMan.GetEntitySystem(); + var logmill = server.ResolveDependency().RootSawmill; List stations = new(); await server.WaitPost(() => @@ -111,34 +113,37 @@ await server.WaitAssertion(() => var assigned = stationJobs.AssignJobs(fakePlayers, stations); Assert.That(assigned, Is.Not.Empty); var time = start.Elapsed.TotalMilliseconds; - Logger.Info($"Took {time} ms to distribute {TotalPlayers} players."); + logmill.Info($"Took {time} ms to distribute {TotalPlayers} players."); - foreach (var station in stations) + Assert.Multiple(() => { - var assignedHere = assigned - .Where(x => x.Value.Item2 == station) - .ToDictionary(x => x.Key, x => x.Value); - - // Each station should have SOME players. - Assert.That(assignedHere, Is.Not.Empty); - // And it should have at least the minimum players to be considered a "fair" share, as they're all the same. - Assert.That(assignedHere, Has.Count.GreaterThanOrEqualTo(TotalPlayers/stations.Count), "Station has too few players."); - // And it shouldn't have ALL the players, either. - Assert.That(assignedHere, Has.Count.LessThan(TotalPlayers), "Station has too many players."); - // And there should be *A* captain, as there's one player with captain enabled per station. - Assert.That(assignedHere.Where(x => x.Value.Item1 == "TCaptain").ToList(), Has.Count.EqualTo(1)); - } + foreach (var station in stations) + { + var assignedHere = assigned + .Where(x => x.Value.Item2 == station) + .ToDictionary(x => x.Key, x => x.Value); + + // Each station should have SOME players. + Assert.That(assignedHere, Is.Not.Empty); + // And it should have at least the minimum players to be considered a "fair" share, as they're all the same. + Assert.That(assignedHere, Has.Count.GreaterThanOrEqualTo(TotalPlayers / stations.Count), "Station has too few players."); + // And it shouldn't have ALL the players, either. + Assert.That(assignedHere, Has.Count.LessThan(TotalPlayers), "Station has too many players."); + // And there should be *A* captain, as there's one player with captain enabled per station. + Assert.That(assignedHere.Where(x => x.Value.Item1 == "TCaptain").ToList(), Has.Count.EqualTo(1)); + } - // All clown players have assistant as a higher priority. - Assert.That(assigned.Values.Select(x => x.Item1).ToList(), Does.Not.Contain("TClown")); - // Mime isn't an open job-slot at round-start. - Assert.That(assigned.Values.Select(x => x.Item1).ToList(), Does.Not.Contain("TMime")); - // All players have slots they can fill. - Assert.That(assigned.Values, Has.Count.EqualTo(TotalPlayers), $"Expected {TotalPlayers} players."); - // There must be assistants present. - Assert.That(assigned.Values.Select(x => x.Item1).ToList(), Does.Contain("TAssistant")); - // There must be captains present, too. - Assert.That(assigned.Values.Select(x => x.Item1).ToList(), Does.Contain("TCaptain")); + // All clown players have assistant as a higher priority. + Assert.That(assigned.Values.Select(x => x.Item1).ToList(), Does.Not.Contain("TClown")); + // Mime isn't an open job-slot at round-start. + Assert.That(assigned.Values.Select(x => x.Item1).ToList(), Does.Not.Contain("TMime")); + // All players have slots they can fill. + Assert.That(assigned.Values, Has.Count.EqualTo(TotalPlayers), $"Expected {TotalPlayers} players."); + // There must be assistants present. + Assert.That(assigned.Values.Select(x => x.Item1).ToList(), Does.Contain("TAssistant")); + // There must be captains present, too. + Assert.That(assigned.Values.Select(x => x.Item1).ToList(), Does.Contain("TCaptain")); + }); }); await pairTracker.CleanReturnAsync(); } @@ -146,7 +151,11 @@ await server.WaitAssertion(() => [Test] public async Task AdjustJobsTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var prototypeManager = server.ResolveDependency(); @@ -197,7 +206,11 @@ await server.WaitAssertion(() => [Test] public async Task InvalidRoundstartJobsTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var prototypeManager = server.ResolveDependency(); @@ -213,20 +226,22 @@ await server.WaitAssertion(() => invalidJobs.Add(job.ID); } - foreach (var gameMap in prototypeManager.EnumeratePrototypes()) + Assert.Multiple(() => { - foreach (var (stationId, station) in gameMap.Stations) + foreach (var gameMap in prototypeManager.EnumeratePrototypes()) { - if (!station.StationComponentOverrides.TryGetComponent("StationJobs", out var comp)) - continue; - - foreach (var (job, _) in ((StationJobsComponent)comp).SetupAvailableJobs) + foreach (var (stationId, station) in gameMap.Stations) { - Assert.That(invalidJobs.Contains(job), Is.False, $"Station {stationId} contains job prototype {job} which cannot be present roundstart."); + if (!station.StationComponentOverrides.TryGetComponent("StationJobs", out var comp)) + continue; + + foreach (var (job, _) in ((StationJobsComponent) comp).SetupAvailableJobs) + { + Assert.That(invalidJobs, Does.Not.Contain(job), $"Station {stationId} contains job prototype {job} which cannot be present roundstart."); + } } } - } - + }); }); await pairTracker.CleanReturnAsync(); } @@ -256,6 +271,6 @@ public static Dictionary WithPlayers( this Dictionary inp, Dictionary second) { - return new[] {inp, second}.SelectMany(x => x).ToDictionary(x => x.Key, x => x.Value); + return new[] { inp, second }.SelectMany(x => x).ToDictionary(x => x.Key, x => x.Value); } } diff --git a/Content.IntegrationTests/Tests/StorageTest.cs b/Content.IntegrationTests/Tests/StorageTest.cs index fca27733bab..c85747934c6 100644 --- a/Content.IntegrationTests/Tests/StorageTest.cs +++ b/Content.IntegrationTests/Tests/StorageTest.cs @@ -1,12 +1,9 @@ #nullable enable -using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Content.Server.Storage.Components; using Content.Shared.Item; using Content.Shared.Storage; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Prototypes; using Robust.UnitTesting; @@ -23,7 +20,7 @@ public sealed class StorageTest [Test] public async Task StorageSizeArbitrageTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoManager = server.ResolveDependency(); @@ -45,23 +42,27 @@ await server.WaitAssertion(() => [Test] public async Task TestStorageFillPrototypes() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoManager = server.ResolveDependency(); await server.WaitAssertion(() => { - foreach (var proto in protoManager.EnumeratePrototypes()) + Assert.Multiple(() => { - if (!proto.TryGetComponent("StorageFill", out var storage)) continue; - - foreach (var entry in storage.Contents) + foreach (var proto in protoManager.EnumeratePrototypes()) { - Assert.That(entry.Amount, Is.GreaterThan(0), $"Specified invalid amount of {entry.Amount} for prototype {proto.ID}"); - Assert.That(entry.SpawnProbability, Is.GreaterThan(0), $"Specified invalid probability of {entry.SpawnProbability} for prototype {proto.ID}"); + if (!proto.TryGetComponent("StorageFill", out var storage)) + continue; + + foreach (var entry in storage.Contents) + { + Assert.That(entry.Amount, Is.GreaterThan(0), $"Specified invalid amount of {entry.Amount} for prototype {proto.ID}"); + Assert.That(entry.SpawnProbability, Is.GreaterThan(0), $"Specified invalid probability of {entry.SpawnProbability} for prototype {proto.ID}"); + } } - } + }); }); await pairTracker.CleanReturnAsync(); } @@ -69,7 +70,7 @@ await server.WaitAssertion(() => [Test] public async Task TestSufficientSpaceForFill() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; var protoMan = server.ResolveDependency(); diff --git a/Content.IntegrationTests/Tests/Tag/TagTest.cs b/Content.IntegrationTests/Tests/Tag/TagTest.cs index 1b9c313093c..0f835cca81c 100644 --- a/Content.IntegrationTests/Tests/Tag/TagTest.cs +++ b/Content.IntegrationTests/Tests/Tag/TagTest.cs @@ -1,8 +1,6 @@ #nullable enable using System.Collections.Generic; -using System.Threading.Tasks; using Content.Shared.Tag; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Prototypes; @@ -45,7 +43,11 @@ public sealed class TagTest [Test] public async Task TagComponentTest() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var sEntityManager = server.ResolveDependency(); @@ -65,53 +67,62 @@ await server.WaitAssertion(() => { var tagSystem = entManager.GetEntitySystem(); // Has one tag, the starting tag - Assert.That(sTagComponent.Tags.Count, Is.EqualTo(1)); + Assert.That(sTagComponent.Tags, Has.Count.EqualTo(1)); sPrototypeManager.Index(StartingTag); - Assert.That(sTagComponent.Tags, Contains.Item(StartingTag)); + Assert.Multiple(() => + { + Assert.That(sTagComponent.Tags, Contains.Item(StartingTag)); - // Single - Assert.True(tagSystem.HasTag(sTagDummy, StartingTag)); - Assert.True(tagSystem.HasTag(sTagComponent, StartingTag)); + // Single + Assert.That(tagSystem.HasTag(sTagDummy, StartingTag)); + Assert.That(tagSystem.HasTag(sTagComponent, StartingTag)); - // Any - Assert.True(tagSystem.HasAnyTag(sTagDummy, StartingTag)); - Assert.True(tagSystem.HasAnyTag(sTagComponent, StartingTag)); + // Any + Assert.That(tagSystem.HasAnyTag(sTagDummy, StartingTag)); + Assert.That(tagSystem.HasAnyTag(sTagComponent, StartingTag)); - // All - Assert.True(tagSystem.HasAllTags(sTagDummy, StartingTag)); - Assert.True(tagSystem.HasAllTags(sTagComponent, StartingTag)); + // All + Assert.That(tagSystem.HasAllTags(sTagDummy, StartingTag)); + Assert.That(tagSystem.HasAllTags(sTagComponent, StartingTag)); + }); // Does not have the added tag var addedTagPrototype = sPrototypeManager.Index(AddedTag); - Assert.That(sTagComponent.Tags, Does.Not.Contains(addedTagPrototype)); + Assert.Multiple(() => + { + Assert.That(sTagComponent.Tags, Does.Not.Contains(addedTagPrototype)); - // Single - Assert.False(tagSystem.HasTag(sTagDummy, AddedTag)); - Assert.False(tagSystem.HasTag(sTagComponent, AddedTag)); + // Single + Assert.That(tagSystem.HasTag(sTagDummy, AddedTag), Is.False); + Assert.That(tagSystem.HasTag(sTagComponent, AddedTag), Is.False); - // Any - Assert.False(tagSystem.HasAnyTag(sTagDummy, AddedTag)); - Assert.False(tagSystem.HasAnyTag(sTagComponent, AddedTag)); + // Any + Assert.That(tagSystem.HasAnyTag(sTagDummy, AddedTag), Is.False); + Assert.That(tagSystem.HasAnyTag(sTagComponent, AddedTag), Is.False); - // All - Assert.False(tagSystem.HasAllTags(sTagDummy, AddedTag)); - Assert.False(tagSystem.HasAllTags(sTagComponent, AddedTag)); + // All + Assert.That(tagSystem.HasAllTags(sTagDummy, AddedTag), Is.False); + Assert.That(tagSystem.HasAllTags(sTagComponent, AddedTag), Is.False); + }); // Does not have the unused tag var unusedTagPrototype = sPrototypeManager.Index(UnusedTag); - Assert.That(sTagComponent.Tags, Does.Not.Contains(unusedTagPrototype)); + Assert.Multiple(() => + { + Assert.That(sTagComponent.Tags, Does.Not.Contains(unusedTagPrototype)); - // Single - Assert.False(tagSystem.HasTag(sTagDummy, UnusedTag)); - Assert.False(tagSystem.HasTag(sTagComponent, UnusedTag)); + // Single + Assert.That(tagSystem.HasTag(sTagDummy, UnusedTag), Is.False); + Assert.That(tagSystem.HasTag(sTagComponent, UnusedTag), Is.False); - // Any - Assert.False(tagSystem.HasAnyTag(sTagDummy, UnusedTag)); - Assert.False(tagSystem.HasAnyTag(sTagComponent, UnusedTag)); + // Any + Assert.That(tagSystem.HasAnyTag(sTagDummy, UnusedTag), Is.False); + Assert.That(tagSystem.HasAnyTag(sTagComponent, UnusedTag), Is.False); - // All - Assert.False(tagSystem.HasAllTags(sTagDummy, UnusedTag)); - Assert.False(tagSystem.HasAllTags(sTagComponent, UnusedTag)); + // All + Assert.That(tagSystem.HasAllTags(sTagDummy, UnusedTag), Is.False); + Assert.That(tagSystem.HasAllTags(sTagComponent, UnusedTag), Is.False); + }); // Throws when checking for an unregistered tag Assert.Throws(() => @@ -119,76 +130,88 @@ await server.WaitAssertion(() => sPrototypeManager.Index(UnregisteredTag); }); - // Cannot add the starting tag again - Assert.That(tagSystem.AddTag(sTagComponent, StartingTag), Is.False); - Assert.That(tagSystem.AddTags(sTagComponent, StartingTag, StartingTag), Is.False); - Assert.That(tagSystem.AddTags(sTagComponent, new List {StartingTag, StartingTag}), Is.False); - - // Has the starting tag - Assert.That(tagSystem.HasTag(sTagComponent, StartingTag), Is.True); - Assert.That(tagSystem.HasAllTags(sTagComponent, StartingTag, StartingTag), Is.True); - Assert.That(tagSystem.HasAllTags(sTagComponent, new List {StartingTag, StartingTag}), Is.True); - Assert.That(tagSystem.HasAnyTag(sTagComponent, StartingTag, StartingTag), Is.True); - Assert.That(tagSystem.HasAnyTag(sTagComponent, new List {StartingTag, StartingTag}), Is.True); - - // Does not have the added tag yet - Assert.That(tagSystem.HasTag(sTagComponent, AddedTag), Is.False); - Assert.That(tagSystem.HasAllTags(sTagComponent, AddedTag, AddedTag), Is.False); - Assert.That(tagSystem.HasAllTags(sTagComponent, new List {AddedTag, AddedTag}), Is.False); - Assert.That(tagSystem.HasAnyTag(sTagComponent, AddedTag, AddedTag), Is.False); - Assert.That(tagSystem.HasAnyTag(sTagComponent, new List {AddedTag, AddedTag}), Is.False); - - // Has a combination of the two tags - Assert.That(tagSystem.HasAnyTag(sTagComponent, StartingTag, AddedTag), Is.True); - Assert.That(tagSystem.HasAnyTag(sTagComponent, new List {StartingTag, AddedTag}), Is.True); - - // Does not have both tags - Assert.That(tagSystem.HasAllTags(sTagComponent, StartingTag, AddedTag), Is.False); - Assert.That(tagSystem.HasAllTags(sTagComponent, new List {StartingTag, AddedTag}), Is.False); - - // Cannot remove a tag that does not exist - Assert.That(tagSystem.RemoveTag(sTagComponent, AddedTag), Is.False); - Assert.That(tagSystem.RemoveTags(sTagComponent, AddedTag, AddedTag), Is.False); - Assert.That(tagSystem.RemoveTags(sTagComponent, new List {AddedTag, AddedTag}), Is.False); + Assert.Multiple(() => + { + // Cannot add the starting tag again + Assert.That(tagSystem.AddTag(sTagComponent, StartingTag), Is.False); + Assert.That(tagSystem.AddTags(sTagComponent, StartingTag, StartingTag), Is.False); + Assert.That(tagSystem.AddTags(sTagComponent, new List { StartingTag, StartingTag }), Is.False); + + // Has the starting tag + Assert.That(tagSystem.HasTag(sTagComponent, StartingTag), Is.True); + Assert.That(tagSystem.HasAllTags(sTagComponent, StartingTag, StartingTag), Is.True); + Assert.That(tagSystem.HasAllTags(sTagComponent, new List { StartingTag, StartingTag }), Is.True); + Assert.That(tagSystem.HasAnyTag(sTagComponent, StartingTag, StartingTag), Is.True); + Assert.That(tagSystem.HasAnyTag(sTagComponent, new List { StartingTag, StartingTag }), Is.True); + + // Does not have the added tag yet + Assert.That(tagSystem.HasTag(sTagComponent, AddedTag), Is.False); + Assert.That(tagSystem.HasAllTags(sTagComponent, AddedTag, AddedTag), Is.False); + Assert.That(tagSystem.HasAllTags(sTagComponent, new List { AddedTag, AddedTag }), Is.False); + Assert.That(tagSystem.HasAnyTag(sTagComponent, AddedTag, AddedTag), Is.False); + Assert.That(tagSystem.HasAnyTag(sTagComponent, new List { AddedTag, AddedTag }), Is.False); + + // Has a combination of the two tags + Assert.That(tagSystem.HasAnyTag(sTagComponent, StartingTag, AddedTag), Is.True); + Assert.That(tagSystem.HasAnyTag(sTagComponent, new List { StartingTag, AddedTag }), Is.True); + + // Does not have both tags + Assert.That(tagSystem.HasAllTags(sTagComponent, StartingTag, AddedTag), Is.False); + Assert.That(tagSystem.HasAllTags(sTagComponent, new List { StartingTag, AddedTag }), Is.False); + + // Cannot remove a tag that does not exist + Assert.That(tagSystem.RemoveTag(sTagComponent, AddedTag), Is.False); + Assert.That(tagSystem.RemoveTags(sTagComponent, AddedTag, AddedTag), Is.False); + Assert.That(tagSystem.RemoveTags(sTagComponent, new List { AddedTag, AddedTag }), Is.False); + }); // Can add the new tag Assert.That(tagSystem.AddTag(sTagComponent, AddedTag), Is.True); - // Cannot add it twice - Assert.That(tagSystem.AddTag(sTagComponent, AddedTag), Is.False); - - // Cannot add existing tags - Assert.That(tagSystem.AddTags(sTagComponent, StartingTag, AddedTag), Is.False); - Assert.That(tagSystem.AddTags(sTagComponent, new List {StartingTag, AddedTag}), Is.False); - - // Now has two tags - Assert.That(sTagComponent.Tags.Count, Is.EqualTo(2)); - - // Has both tags - Assert.That(tagSystem.HasTag(sTagComponent, StartingTag), Is.True); - Assert.That(tagSystem.HasTag(sTagComponent, AddedTag), Is.True); - Assert.That(tagSystem.HasAllTags(sTagComponent, StartingTag, StartingTag), Is.True); - Assert.That(tagSystem.HasAllTags(sTagComponent, AddedTag, StartingTag), Is.True); - Assert.That(tagSystem.HasAllTags(sTagComponent, new List {StartingTag, AddedTag}), Is.True); - Assert.That(tagSystem.HasAllTags(sTagComponent, new List {AddedTag, StartingTag}), Is.True); - Assert.That(tagSystem.HasAnyTag(sTagComponent, StartingTag, AddedTag), Is.True); - Assert.That(tagSystem.HasAnyTag(sTagComponent, AddedTag, StartingTag), Is.True); + Assert.Multiple(() => + { + // Cannot add it twice + Assert.That(tagSystem.AddTag(sTagComponent, AddedTag), Is.False); + + // Cannot add existing tags + Assert.That(tagSystem.AddTags(sTagComponent, StartingTag, AddedTag), Is.False); + Assert.That(tagSystem.AddTags(sTagComponent, new List { StartingTag, AddedTag }), Is.False); + + // Now has two tags + Assert.That(sTagComponent.Tags, Has.Count.EqualTo(2)); + + // Has both tags + Assert.That(tagSystem.HasTag(sTagComponent, StartingTag), Is.True); + Assert.That(tagSystem.HasTag(sTagComponent, AddedTag), Is.True); + Assert.That(tagSystem.HasAllTags(sTagComponent, StartingTag, StartingTag), Is.True); + Assert.That(tagSystem.HasAllTags(sTagComponent, AddedTag, StartingTag), Is.True); + Assert.That(tagSystem.HasAllTags(sTagComponent, new List { StartingTag, AddedTag }), Is.True); + Assert.That(tagSystem.HasAllTags(sTagComponent, new List { AddedTag, StartingTag }), Is.True); + Assert.That(tagSystem.HasAnyTag(sTagComponent, StartingTag, AddedTag), Is.True); + Assert.That(tagSystem.HasAnyTag(sTagComponent, AddedTag, StartingTag), Is.True); + }); - // Remove the existing starting tag - Assert.That(tagSystem.RemoveTag(sTagComponent, StartingTag), Is.True); + Assert.Multiple(() => + { + // Remove the existing starting tag + Assert.That(tagSystem.RemoveTag(sTagComponent, StartingTag), Is.True); - // Remove the existing added tag - Assert.That(tagSystem.RemoveTags(sTagComponent, AddedTag, AddedTag), Is.True); + // Remove the existing added tag + Assert.That(tagSystem.RemoveTags(sTagComponent, AddedTag, AddedTag), Is.True); + }); - // No tags left to remove - Assert.That(tagSystem.RemoveTags(sTagComponent, new List {StartingTag, AddedTag}), Is.False); + Assert.Multiple(() => + { + // No tags left to remove + Assert.That(tagSystem.RemoveTags(sTagComponent, new List { StartingTag, AddedTag }), Is.False); - // No tags left in the component - Assert.That(sTagComponent.Tags, Is.Empty); + // No tags left in the component + Assert.That(sTagComponent.Tags, Is.Empty); + }); - #if !DEBUG +#if !DEBUG return; - #endif +#endif // Single Assert.Throws(() => diff --git a/Content.IntegrationTests/Tests/Tiles/TileConstructionTests.cs b/Content.IntegrationTests/Tests/Tiles/TileConstructionTests.cs index 18df4707cce..c4b09a8aa46 100644 --- a/Content.IntegrationTests/Tests/Tiles/TileConstructionTests.cs +++ b/Content.IntegrationTests/Tests/Tiles/TileConstructionTests.cs @@ -1,9 +1,5 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; -using NUnit.Framework; -using Robust.Shared.GameObjects; using Robust.Shared.Map; -using Robust.Shared.Map.Components; namespace Content.IntegrationTests.Tests.Tiles; @@ -21,7 +17,7 @@ public async Task PlaceThenCutLattice() await SetTile(null); await Interact(Rod); await AssertTile(Lattice); - Assert.IsNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Null); await Interact(Cut); await AssertTile(null); await AssertEntityLookup((Rod, 1)); @@ -53,7 +49,7 @@ public async Task CutThenPlaceLatticeNewGrid() AssertGridCount(1); // Cut lattice - Assert.IsNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Null); await Interact(Cut); await AssertTile(null); AssertGridCount(0); @@ -87,13 +83,13 @@ public async Task FloorConstructDeconstruct() // Lattice -> Plating await Interact(Steel); - Assert.IsNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Null); await AssertTile(Plating); AssertGridCount(1); // Plating -> Tile await Interact(FloorItem); - Assert.IsNull(Hands.ActiveHandEntity); + Assert.That(Hands.ActiveHandEntity, Is.Null); await AssertTile(Floor); AssertGridCount(1); @@ -105,4 +101,3 @@ public async Task FloorConstructDeconstruct() await AssertEntityLookup((FloorItem, 1)); } } - diff --git a/Content.IntegrationTests/Tests/Utility/EntitySystemExtensionsTest.cs b/Content.IntegrationTests/Tests/Utility/EntitySystemExtensionsTest.cs index 5e84b896868..e946cd15b47 100644 --- a/Content.IntegrationTests/Tests/Utility/EntitySystemExtensionsTest.cs +++ b/Content.IntegrationTests/Tests/Utility/EntitySystemExtensionsTest.cs @@ -1,12 +1,7 @@ #nullable enable -using System.Threading.Tasks; using Content.Shared.Physics; using Content.Shared.Spawning; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Map; -using Robust.Shared.Physics; using Robust.Shared.Physics.Systems; namespace Content.IntegrationTests.Tests.Utility @@ -36,7 +31,11 @@ public sealed class EntitySystemExtensionsTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings + { + NoClient = true, + ExtraPrototypes = Prototypes + }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -50,36 +49,54 @@ await server.WaitAssertion(() => { // Nothing blocking it, only entity is the grid - Assert.NotNull(sEntityManager.SpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.Impassable)); - Assert.True(sEntityManager.TrySpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.Impassable, out var entity)); - Assert.NotNull(entity); + Assert.Multiple(() => + { + Assert.That(sEntityManager.SpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.Impassable), Is.Not.Null); + Assert.That(sEntityManager.TrySpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.Impassable, out var entity)); + Assert.That(entity, Is.Not.Null); + }); // Nothing blocking it, only entity is the grid - Assert.NotNull(sEntityManager.SpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.Impassable)); - Assert.True(sEntityManager.TrySpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.Impassable, out entity)); - Assert.NotNull(entity); + Assert.Multiple(() => + { + Assert.That(sEntityManager.SpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.Impassable), Is.Not.Null); + Assert.That(sEntityManager.TrySpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.Impassable, out var entity)); + Assert.That(entity, Is.Not.Null); + }); // Spawn a blocker with an Impassable mask sEntityManager.SpawnEntity(BlockerDummyId, entityCoordinates); broady.Update(0.016f); // Cannot spawn something with an Impassable layer - Assert.Null(sEntityManager.SpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.Impassable)); - Assert.False(sEntityManager.TrySpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.Impassable, out entity)); - Assert.Null(entity); + Assert.Multiple(() => + { + Assert.That(sEntityManager.SpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.Impassable), Is.Null); + Assert.That(sEntityManager.TrySpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.Impassable, out var entity), Is.False); + Assert.That(entity, Is.Null); + }); - Assert.Null(sEntityManager.SpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.Impassable)); - Assert.False(sEntityManager.TrySpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.Impassable, out entity)); - Assert.Null(entity); + Assert.Multiple(() => + { + Assert.That(sEntityManager.SpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.Impassable), Is.Null); + Assert.That(sEntityManager.TrySpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.Impassable, out var entity), Is.False); + Assert.That(entity, Is.Null); + }); // Other layers are fine - Assert.NotNull(sEntityManager.SpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.MidImpassable)); - Assert.True(sEntityManager.TrySpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.MidImpassable, out entity)); - Assert.NotNull(entity); + Assert.Multiple(() => + { + Assert.That(sEntityManager.SpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.MidImpassable), Is.Not.Null); + Assert.That(sEntityManager.TrySpawnIfUnobstructed(null, entityCoordinates, CollisionGroup.MidImpassable, out var entity)); + Assert.That(entity, Is.Not.Null); + }); - Assert.NotNull(sEntityManager.SpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.MidImpassable)); - Assert.True(sEntityManager.TrySpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.MidImpassable, out entity)); - Assert.NotNull(entity); + Assert.Multiple(() => + { + Assert.That(sEntityManager.SpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.MidImpassable), Is.Not.Null); + Assert.That(sEntityManager.TrySpawnIfUnobstructed(null, mapCoordinates, CollisionGroup.MidImpassable, out var entity)); + Assert.That(entity, Is.Not.Null); + }); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Utility/EntityWhitelistTest.cs b/Content.IntegrationTests/Tests/Utility/EntityWhitelistTest.cs index 04b4d32cb1a..92d0359e5a7 100644 --- a/Content.IntegrationTests/Tests/Utility/EntityWhitelistTest.cs +++ b/Content.IntegrationTests/Tests/Utility/EntityWhitelistTest.cs @@ -1,10 +1,7 @@ using System.Linq; -using System.Threading.Tasks; using Content.Shared.Containers.ItemSlots; using Content.Shared.Whitelist; -using NUnit.Framework; using Robust.Shared.GameObjects; -using Robust.Shared.Map; namespace Content.IntegrationTests.Tests.Utility { @@ -60,7 +57,7 @@ public sealed class EntityWhitelistTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -79,34 +76,46 @@ await server.WaitAssertion(() => // Test instantiated on its own var whitelistInst = new EntityWhitelist { - Components = new[] { $"{ValidComponent}"}, - Tags = new() {"ValidTag"} + Components = new[] { $"{ValidComponent}" }, + Tags = new() { "ValidTag" } }; whitelistInst.UpdateRegistrations(); Assert.That(whitelistInst, Is.Not.Null); - Assert.That(whitelistInst.Components, Is.Not.Null); - Assert.That(whitelistInst.Tags, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(whitelistInst.Components, Is.Not.Null); + Assert.That(whitelistInst.Tags, Is.Not.Null); + }); - Assert.That(whitelistInst.IsValid(validComponent), Is.True); - Assert.That(whitelistInst.IsValid(validTag), Is.True); + Assert.Multiple(() => + { + Assert.That(whitelistInst.IsValid(validComponent), Is.True); + Assert.That(whitelistInst.IsValid(validTag), Is.True); - Assert.That(whitelistInst.IsValid(invalidComponent), Is.False); - Assert.That(whitelistInst.IsValid(invalidTag), Is.False); + Assert.That(whitelistInst.IsValid(invalidComponent), Is.False); + Assert.That(whitelistInst.IsValid(invalidTag), Is.False); + }); // Test from serialized var dummy = sEntities.SpawnEntity("WhitelistDummy", mapCoordinates); var whitelistSer = sEntities.GetComponent(dummy).Slots.Values.First().Whitelist; Assert.That(whitelistSer, Is.Not.Null); - Assert.That(whitelistSer.Components, Is.Not.Null); - Assert.That(whitelistSer.Tags, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(whitelistSer.Components, Is.Not.Null); + Assert.That(whitelistSer.Tags, Is.Not.Null); + }); - Assert.That(whitelistSer.IsValid(validComponent), Is.True); - Assert.That(whitelistSer.IsValid(validTag), Is.True); + Assert.Multiple(() => + { + Assert.That(whitelistSer.IsValid(validComponent), Is.True); + Assert.That(whitelistSer.IsValid(validTag), Is.True); - Assert.That(whitelistSer.IsValid(invalidComponent), Is.False); - Assert.That(whitelistSer.IsValid(invalidTag), Is.False); + Assert.That(whitelistSer.IsValid(invalidComponent), Is.False); + Assert.That(whitelistSer.IsValid(invalidTag), Is.False); + }); }); await pairTracker.CleanReturnAsync(); } diff --git a/Content.IntegrationTests/Tests/Utility/SandboxTest.cs b/Content.IntegrationTests/Tests/Utility/SandboxTest.cs index 45b681c2214..73baa2f0fcf 100644 --- a/Content.IntegrationTests/Tests/Utility/SandboxTest.cs +++ b/Content.IntegrationTests/Tests/Utility/SandboxTest.cs @@ -1,5 +1,3 @@ -using System.Threading.Tasks; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Utility; @@ -8,7 +6,7 @@ public sealed class SandboxTest [Test] public async Task Test() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoServer = true, Destructive = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoServer = true, Destructive = true }); var client = pairTracker.Pair.Client; await client.CheckSandboxed(typeof(Client.Entry.EntryPoint).Assembly); await pairTracker.CleanReturnAsync(); diff --git a/Content.IntegrationTests/Tests/VendingMachineRestockTest.cs b/Content.IntegrationTests/Tests/VendingMachineRestockTest.cs index 5760e00f0f3..db9e4ddf371 100644 --- a/Content.IntegrationTests/Tests/VendingMachineRestockTest.cs +++ b/Content.IntegrationTests/Tests/VendingMachineRestockTest.cs @@ -1,7 +1,5 @@ #nullable enable using System.Collections.Generic; -using System.Threading.Tasks; -using NUnit.Framework; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Prototypes; @@ -105,7 +103,7 @@ public sealed class VendingMachineRestockTest : EntitySystem [Test] public async Task TestAllRestocksAreAvailableToBuy() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); @@ -159,11 +157,14 @@ await server.WaitAssertion(() => } } - Assert.That(restockStores.Count, Is.EqualTo(0), - $"Some entities containing entities with VendingMachineRestock components are unavailable for purchase: \n - {string.Join("\n - ", restockStores.Keys)}"); + Assert.Multiple(() => + { + Assert.That(restockStores, Has.Count.EqualTo(0), + $"Some entities containing entities with VendingMachineRestock components are unavailable for purchase: \n - {string.Join("\n - ", restockStores.Keys)}"); - Assert.That(restocks.Count, Is.EqualTo(0), - $"Some entities with VendingMachineRestock components are unavailable for purchase: \n - {string.Join("\n - ", restocks)}"); + Assert.That(restocks, Has.Count.EqualTo(0), + $"Some entities with VendingMachineRestock components are unavailable for purchase: \n - {string.Join("\n - ", restocks)}"); + }); }); await pairTracker.CleanReturnAsync(); @@ -172,7 +173,7 @@ await server.WaitAssertion(() => [Test] public async Task TestCompleteRestockProcess() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); @@ -184,10 +185,10 @@ public async Task TestCompleteRestockProcess() EntityUid packageWrong; EntityUid machine; EntityUid user; - VendingMachineComponent machineComponent; - VendingMachineRestockComponent restockRightComponent; - VendingMachineRestockComponent restockWrongComponent; - WiresPanelComponent machineWiresPanel; + VendingMachineComponent machineComponent = default!; + VendingMachineRestockComponent restockRightComponent = default!; + VendingMachineRestockComponent restockWrongComponent = default!; + WiresPanelComponent machineWiresPanel = default!; var testMap = await PoolManager.CreateTestMap(pairTracker); @@ -202,42 +203,51 @@ await server.WaitAssertion(() => packageWrong = entityManager.SpawnEntity("TestRestockWrong", coordinates); // Sanity test for components existing. - Assert.True(entityManager.TryGetComponent(machine, out machineComponent!), $"Machine has no {nameof(VendingMachineComponent)}"); - Assert.True(entityManager.TryGetComponent(packageRight, out restockRightComponent!), $"Correct package has no {nameof(VendingMachineRestockComponent)}"); - Assert.True(entityManager.TryGetComponent(packageWrong, out restockWrongComponent!), $"Wrong package has no {nameof(VendingMachineRestockComponent)}"); - Assert.True(entityManager.TryGetComponent(machine, out machineWiresPanel!), $"Machine has no {nameof(WiresPanelComponent)}"); + Assert.Multiple(() => + { + Assert.That(entityManager.TryGetComponent(machine, out machineComponent!), $"Machine has no {nameof(VendingMachineComponent)}"); + Assert.That(entityManager.TryGetComponent(packageRight, out restockRightComponent!), $"Correct package has no {nameof(VendingMachineRestockComponent)}"); + Assert.That(entityManager.TryGetComponent(packageWrong, out restockWrongComponent!), $"Wrong package has no {nameof(VendingMachineRestockComponent)}"); + Assert.That(entityManager.TryGetComponent(machine, out machineWiresPanel!), $"Machine has no {nameof(WiresPanelComponent)}"); + }); var systemMachine = entitySystemManager.GetEntitySystem(); // Test that the panel needs to be opened first. - Assert.That(systemMachine.TryAccessMachine(packageRight, restockRightComponent, machineComponent, user, machine), Is.False, "Right package is able to restock without opened access panel"); - Assert.That(systemMachine.TryAccessMachine(packageWrong, restockWrongComponent, machineComponent, user, machine), Is.False, "Wrong package is able to restock without opened access panel"); + Assert.Multiple(() => + { + Assert.That(systemMachine.TryAccessMachine(packageRight, restockRightComponent, machineComponent, user, machine), Is.False, "Right package is able to restock without opened access panel"); + Assert.That(systemMachine.TryAccessMachine(packageWrong, restockWrongComponent, machineComponent, user, machine), Is.False, "Wrong package is able to restock without opened access panel"); + }); var systemWires = entitySystemManager.GetEntitySystem(); // Open the panel. systemWires.TogglePanel(machine, machineWiresPanel, true); - // Test that the right package works for the right machine. - Assert.That(systemMachine.TryAccessMachine(packageRight, restockRightComponent, machineComponent, user, machine), Is.True, "Correct package is unable to restock with access panel opened"); + Assert.Multiple(() => + { + // Test that the right package works for the right machine. + Assert.That(systemMachine.TryAccessMachine(packageRight, restockRightComponent, machineComponent, user, machine), Is.True, "Correct package is unable to restock with access panel opened"); - // Test that the wrong package does not work. - Assert.That(systemMachine.TryMatchPackageToMachine(packageWrong, restockWrongComponent, machineComponent, user, machine), Is.False, "Package with invalid canRestock is able to restock machine"); + // Test that the wrong package does not work. + Assert.That(systemMachine.TryMatchPackageToMachine(packageWrong, restockWrongComponent, machineComponent, user, machine), Is.False, "Package with invalid canRestock is able to restock machine"); - // Test that the right package does work. - Assert.That(systemMachine.TryMatchPackageToMachine(packageRight, restockRightComponent, machineComponent, user, machine), Is.True, "Package with valid canRestock is unable to restock machine"); + // Test that the right package does work. + Assert.That(systemMachine.TryMatchPackageToMachine(packageRight, restockRightComponent, machineComponent, user, machine), Is.True, "Package with valid canRestock is unable to restock machine"); - // Make sure there's something in there to begin with. - Assert.That(systemMachine.GetAvailableInventory(machine, machineComponent).Count, Is.GreaterThan(0), - "Machine inventory is empty before emptying."); + // Make sure there's something in there to begin with. + Assert.That(systemMachine.GetAvailableInventory(machine, machineComponent), Has.Count.GreaterThan(0), + "Machine inventory is empty before emptying."); + }); // Empty the inventory. systemMachine.EjectRandom(machine, false, true, machineComponent); - Assert.That(systemMachine.GetAvailableInventory(machine, machineComponent).Count, Is.EqualTo(0), + Assert.That(systemMachine.GetAvailableInventory(machine, machineComponent), Has.Count.EqualTo(0), "Machine inventory is not empty after ejecting."); // Test that the inventory is actually restocked. systemMachine.TryRestockInventory(machine, machineComponent); - Assert.That(systemMachine.GetAvailableInventory(machine, machineComponent).Count, Is.GreaterThan(0), + Assert.That(systemMachine.GetAvailableInventory(machine, machineComponent), Has.Count.GreaterThan(0), "Machine available inventory count is not greater than zero after restock."); mapManager.DeleteMap(testMap.MapId); @@ -249,7 +259,7 @@ await server.WaitAssertion(() => [Test] public async Task TestRestockBreaksOpen() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); @@ -281,11 +291,13 @@ await server.WaitAssertion(() => var damageSpec = new DamageSpecifier(prototypeManager.Index("Blunt"), 100); var damageResult = damageableSystem.TryChangeDamage(restock, damageSpec); - Assert.IsNotNull(damageResult, +#pragma warning disable NUnit2045 + Assert.That(damageResult, Is.Not.Null, "Received null damageResult when attempting to damage restock box."); Assert.That((int) damageResult!.Total, Is.GreaterThan(0), "Box damage result was not greater than 0."); +#pragma warning restore NUnit2045 }); await server.WaitRunTicks(15); await server.WaitAssertion(() => @@ -311,7 +323,7 @@ await server.WaitAssertion(() => [Test] public async Task TestRestockInventoryBounds() { - await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true, ExtraPrototypes = Prototypes}); + await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes }); var server = pairTracker.Pair.Server; await server.WaitIdleAsync(); @@ -327,9 +339,9 @@ await server.WaitAssertion(() => { var coordinates = testMap.GridCoords; - EntityUid machine = entityManager.SpawnEntity("VendingMachineTest", coordinates); + var machine = entityManager.SpawnEntity("VendingMachineTest", coordinates); - Assert.That(vendingMachineSystem.GetAvailableInventory(machine).Count, Is.EqualTo(1), + Assert.That(vendingMachineSystem.GetAvailableInventory(machine), Has.Count.EqualTo(1), "Machine's available inventory did not contain one entry."); Assert.That(vendingMachineSystem.GetAvailableInventory(machine)[0].Amount, Is.EqualTo(1), diff --git a/Content.IntegrationTests/Tests/Weldable/WeldableTests.cs b/Content.IntegrationTests/Tests/Weldable/WeldableTests.cs index 337747deca8..504a51a33cb 100644 --- a/Content.IntegrationTests/Tests/Weldable/WeldableTests.cs +++ b/Content.IntegrationTests/Tests/Weldable/WeldableTests.cs @@ -1,7 +1,5 @@ -using System.Threading.Tasks; using Content.IntegrationTests.Tests.Interaction; using Content.Server.Tools.Components; -using NUnit.Framework; namespace Content.IntegrationTests.Tests.Weldable; @@ -18,8 +16,11 @@ public async Task WeldLocker() await SpawnTarget(Locker); var comp = Comp(); - Assert.That(comp.Weldable, Is.True); - Assert.That(comp.IsWelded, Is.False); + Assert.Multiple(() => + { + Assert.That(comp.Weldable, Is.True); + Assert.That(comp.IsWelded, Is.False); + }); await Interact(Weld); Assert.That(comp.IsWelded, Is.True);